예제 #1
0
파일: main.go 프로젝트: d4l3k/btcinterned
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
0
파일: chain.go 프로젝트: D-bank/btcwallet
// NewClient creates a client connection to the server described by the connect
// string.  If disableTLS is false, the remote RPC certificate must be provided
// in the certs slice.  The connection is not established immediately, but must
// be done using the Start method.  If the remote server does not operate on
// the same bitcoin network as described by the passed chain parameters, the
// connection will be disconnected.
func NewClient(chainParams *chaincfg.Params, connect, user, pass string, certs []byte, disableTLS bool) (*Client, error) {
	client := Client{
		chainParams:         chainParams,
		enqueueNotification: make(chan interface{}),
		dequeueNotification: make(chan interface{}),
		currentBlock:        make(chan *waddrmgr.BlockStamp),
		quit:                make(chan struct{}),
	}
	ntfnCallbacks := btcrpcclient.NotificationHandlers{
		OnClientConnected:   client.onClientConnect,
		OnBlockConnected:    client.onBlockConnected,
		OnBlockDisconnected: client.onBlockDisconnected,
		OnRecvTx:            client.onRecvTx,
		OnRedeemingTx:       client.onRedeemingTx,
		OnRescanFinished:    client.onRescanFinished,
		OnRescanProgress:    client.onRescanProgress,
	}
	conf := btcrpcclient.ConnConfig{
		Host:                 connect,
		Endpoint:             "ws",
		User:                 user,
		Pass:                 pass,
		Certificates:         certs,
		DisableAutoReconnect: true,
		DisableConnectOnNew:  true,
		DisableTLS:           disableTLS,
	}
	c, err := btcrpcclient.New(&conf, &ntfnCallbacks)
	if err != nil {
		return nil, err
	}
	client.Client = c
	return &client, nil
}
예제 #3
0
func createRPCClient(cfg *config) *btcrpcclient.Client {

	certs, err := ioutil.ReadFile(cfg.RPCCert)
	if err != nil {
		log.Fatal(err)
	}

	connCfg := &btcrpcclient.ConnConfig{
		Host:         cfg.RPCServer,
		User:         cfg.RPCUser,
		Pass:         cfg.RPCPassword,
		HTTPPostMode: true,
		Certificates: certs,
	}

	client, err := btcrpcclient.New(connCfg, nil)
	if err != nil {
		log.Fatal(err)
	}

	_, err = client.GetBlockCount()
	if err != nil {
		log.Fatal(err)
	}

	return client
}
예제 #4
0
파일: bitcoin.go 프로젝트: nonempty/degdb
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
}
예제 #5
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()
}
예제 #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()
}
예제 #7
0
func main() {
	var err error

	cfg, _, err = loadConfig()
	if err != nil {
		fmt.Fprintf(os.Stderr, "loadConfig failed: %v\n", err)
		os.Exit(-1)
	}

	listeners := make([]net.Listener, 0, len(cfg.Listeners))
	for _, addr := range cfg.Listeners {
		listener, err := net.Listen("tcp", addr)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Listen failed: %v\n", err)
			os.Exit(-1)
		}
		listeners = append(listeners, listener)
	}

	cert, err := ioutil.ReadFile(cfg.RPCCert)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to load certificate: %v\n", err)
		os.Exit(-1)
	}
	rpccfg := btcrpcclient.ConnConfig{
		Host:         cfg.RPCServer,
		Endpoint:     "ws",
		User:         cfg.RPCUser,
		Pass:         cfg.RPCPassword,
		Certificates: cert,
	}
	client, err = btcrpcclient.New(&rpccfg, nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "New RPC Client failed: %v\n", err)
		os.Exit(-1)
	}

	http.HandleFunc("/", handleRequest)

	httpServeMux := http.NewServeMux()
	httpServer := &http.Server{Handler: httpServeMux}
	httpServeMux.HandleFunc("/", handleRequest)

	var wg sync.WaitGroup
	for _, listener := range listeners {
		wg.Add(1)
		go func(listener net.Listener) {
			fmt.Fprintf(os.Stderr, "HTTP server listening on %s\n", listener.Addr())
			httpServer.Serve(listener)
			wg.Done()
		}(listener)
	}
	wg.Wait()
}
예제 #8
0
func initCoinClient(coinType string) {
	switch coinType {
	case models.CoinTypeEthereum, models.CoinTypeAlipay:
		return
	default:
		config := &btcrpcclient.ConnConfig{
			Host:         "localhost:8332",
			User:         "******",
			Pass:         "******",
			HTTPPostMode: true, // Bitcoin core only supports HTTP POST mode
			DisableTLS:   true, // Bitcoin core does not provide TLS by default
		}
		coinClient = must(btcrpcclient.New(config, nil)).(*btcrpcclient.Client)
	}
}
예제 #9
0
파일: node.go 프로젝트: stormasm/btcsim1020
// Connect tries to connect to the launched node and sets the
// client field. It returns an error if the connection times out
func (n *Node) Connect() error {
	var client *rpc.Client
	var err error

	rpcConf := n.RPCConnConfig()

	for i := 0; i < *maxConnRetries; i++ {
		if client, err = rpc.New(&rpcConf, n.handlers); err != nil {
			time.Sleep(time.Duration(i) * 50 * time.Millisecond)
			continue
		}
		break
	}
	if client == nil {
		return ErrConnectionTimeOut
	}
	n.client = client
	return nil
}
예제 #10
0
// NewRPCClient creates a client connection to the server described by the
// connect string.  If disableTLS is false, the remote RPC certificate must be
// provided in the certs slice.  The connection is not established immediately,
// but must be done using the Start method.  If the remote server does not
// operate on the same bitcoin network as described by the passed chain
// parameters, the connection will be disconnected.
func NewRPCClient(chainParams *chaincfg.Params, connect, user, pass string, certs []byte,
	disableTLS bool, reconnectAttempts int) (*RPCClient, error) {

	if reconnectAttempts < 0 {
		return nil, errors.New("reconnectAttempts must be positive")
	}

	client := &RPCClient{
		connConfig: &btcrpcclient.ConnConfig{
			Host:                 connect,
			Endpoint:             "ws",
			User:                 user,
			Pass:                 pass,
			Certificates:         certs,
			DisableAutoReconnect: true,
			DisableConnectOnNew:  true,
			DisableTLS:           disableTLS,
		},
		chainParams:         chainParams,
		reconnectAttempts:   reconnectAttempts,
		enqueueNotification: make(chan interface{}),
		dequeueNotification: make(chan interface{}),
		currentBlock:        make(chan *waddrmgr.BlockStamp),
		quit:                make(chan struct{}),
	}
	ntfnCallbacks := &btcrpcclient.NotificationHandlers{
		OnClientConnected:   client.onClientConnect,
		OnBlockConnected:    client.onBlockConnected,
		OnBlockDisconnected: client.onBlockDisconnected,
		OnRecvTx:            client.onRecvTx,
		OnRedeemingTx:       client.onRedeemingTx,
		OnRescanFinished:    client.onRescanFinished,
		OnRescanProgress:    client.onRescanProgress,
	}
	rpcClient, err := btcrpcclient.New(client.connConfig, ntfnCallbacks)
	if err != nil {
		return nil, err
	}
	client.Client = rpcClient
	return client, nil
}
예제 #11
0
파일: rpc_harness.go 프로젝트: tb00/btcd
// connectRPCClient attempts to establish an RPC connection to the created btcd
// process belonging to this Harness instance. If the initial connection
// attempt fails, this function will retry h.maxConnRetries times, backing off
// the time between subsequent attempts. If after h.maxConnRetries attempts,
// we're not able to establish a connection, this function returns with an
// error.
func (h *Harness) connectRPCClient() error {
	var client *btcrpcclient.Client
	var err error

	rpcConf := h.node.config.rpcConnConfig()
	for i := 0; i < h.maxConnRetries; i++ {
		if client, err = btcrpcclient.New(&rpcConf, h.handlers); err != nil {
			time.Sleep(time.Duration(i) * 50 * time.Millisecond)
			continue
		}
		break
	}

	if client == nil {
		return fmt.Errorf("connection timeout")
	}

	h.Node = client
	h.wallet.SetRPCClient(client)
	return nil
}
예제 #12
0
파일: main.go 프로젝트: dyzz/gobtclib
func main() {
	connCfg := loadConf()
	var err error

	client, err = btcrpcclient.New(connCfg, nil)
	if err != nil {
		logger.Crit(err.Error())
		return
	}
	defer client.Shutdown()

	var wg sync.WaitGroup

	wg.Add(1)

	http.HandleFunc("/block", blockNotify)
	logger.Info("Starting server...")

	// Start http server for bitcoind
	go func() {
		defer wg.Done()
		err = http.ListenAndServe("127.0.0.1:8000", nil)
		if err != nil {
			logger.Crit(err.Error())
		}
	}()

	// Start ZMQ server for braft
	sender, err = zmq.NewSocket(zmq.PUB)
	defer sender.Close()
	if err != nil {
		logger.Crit(err.Error())
	}
	sender.Bind("tcp://*:8001")
	logger.Info("ZMQ server started...")

	wg.Wait()
}
예제 #13
0
func main() {
	// Connect to local bitcoin core RPC server using HTTP POST mode.
	connCfg := &btcrpcclient.ConnConfig{
		Host:         "localhost:8332",
		User:         "******",
		Pass:         "******",
		HTTPPostMode: true, // Bitcoin core only supports HTTP POST mode
		DisableTLS:   true, // Bitcoin core does not provide TLS by default
	}
	// Notice the notification parameter is nil since notifications are
	// not supported in HTTP POST mode.
	client, err := btcrpcclient.New(connCfg, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Shutdown()

	// Get the current block count.
	blockCount, err := client.GetBlockCount()
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("Block count: %d", blockCount)
}
예제 #14
0
// POSTClient creates the equivalent HTTP POST btcrpcclient.Client.
func (c *RPCClient) POSTClient() (*btcrpcclient.Client, error) {
	configCopy := *c.connConfig
	configCopy.HTTPPostMode = true
	return btcrpcclient.New(&configCopy, nil)
}
예제 #15
0
func main() {
	var excludesearch arrayFlags
	hostnamePtr := flag.String("hostname", "", "zabbix hostname")
	basepathPtr := flag.String("basepath", "/srv", "base path")
	searchSuffixPtr := flag.String("searchSuffix", "-data", "search suffix")
	flag.Var(&excludesearch, "exclude", "exclude from search list")
	flag.Parse()
	log.SetOutput(os.Stderr)

	if *hostnamePtr == "" {
		flag.Usage()
		os.Exit(1)
	}

	discovery := make(lld.DiscoveryData, 0)
	err := filepath.Walk(*basepathPtr, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if !info.IsDir() {
			return nil
		}
		if strings.HasSuffix(path, *searchSuffixPtr) {
			name := strings.TrimSuffix(filepath.Base(path), *searchSuffixPtr)
			if stringInSlice(name, excludesearch) {
				return nil
			}
			item := make(lld.DiscoveryItem, 0)
			item["NAME"] = name
			item["PATH"] = path
			discovery = append(discovery, item)
		}
		return nil
	})
	if err != nil {
		log.Print(err)
		os.Exit(1)
	}
	fmt.Printf("\"%s\" \"wallet.discovery\" %s\n", *hostnamePtr, strconv.Quote(discovery.JsonLine()))
	for _, element := range discovery {
		config := &BitcoinConfig{Hostname: "127.0.0.1", Port: 8332}
		err := ini.MapTo(config, filepath.Join(element["PATH"], element["NAME"]+".conf"))
		if err != nil {
			log.Print(err)
			continue
		}
		connCfg := &btcrpcclient.ConnConfig{
			Host:         config.Hostname + ":" + strconv.Itoa(config.Port),
			User:         config.Username,
			Pass:         config.Password,
			HTTPPostMode: true, // Bitcoin core only supports HTTP POST mode
			DisableTLS:   true, // Bitcoin core does not provide TLS by default
		}
		// Notice the notification parameter is nil since notifications are
		// not supported in HTTP POST mode.
		client, err := btcrpcclient.New(connCfg, nil)
		if err != nil {
			log.Print(err)
			continue
		}
		defer client.Shutdown()

		// Get the current block count.
		blockCount, err := client.GetBlockCount()
		if err != nil {
			log.Print(err)
			continue
		}
		fmt.Printf("\"%s\" \"wallet.blocks[%s]\" \"%d\"\n", *hostnamePtr, element["NAME"], blockCount)
		balance, err := client.GetBalance("*")
		if err != nil {
			log.Print(err)
			continue
		}
		fmt.Printf("\"%s\" \"wallet.balance[%s]\" \"%f\"\n", *hostnamePtr, element["NAME"], balance.ToBTC())
	}
}
예제 #16
0
func sweep() error {
	rpcPassword, err := promptSecret("Wallet RPC password")
	if err != nil {
		return errContext(err, "failed to read RPC password")
	}

	// Open RPC client.
	rpcCertificate, err := ioutil.ReadFile(opts.RPCCertificateFile)
	if err != nil {
		return errContext(err, "failed to read RPC certificate")
	}
	rpcClient, err := btcrpcclient.New(&btcrpcclient.ConnConfig{
		Host:         opts.RPCConnect,
		User:         opts.RPCUsername,
		Pass:         rpcPassword,
		Certificates: rpcCertificate,
		HTTPPostMode: true,
	}, nil)
	if err != nil {
		return errContext(err, "failed to create RPC client")
	}
	defer rpcClient.Shutdown()

	// Fetch all unspent outputs, ignore those not from the source
	// account, and group by their destination address.  Each grouping of
	// outputs will be used as inputs for a single transaction sending to a
	// new destination account address.
	unspentOutputs, err := rpcClient.ListUnspent()
	if err != nil {
		return errContext(err, "failed to fetch unspent outputs")
	}
	sourceOutputs := make(map[string][]btcjson.ListUnspentResult)
	for _, unspentOutput := range unspentOutputs {
		if !unspentOutput.Spendable {
			continue
		}
		if unspentOutput.Confirmations < opts.RequiredConfirmations {
			continue
		}
		if unspentOutput.Account != opts.SourceAccount {
			continue
		}
		sourceAddressOutputs := sourceOutputs[unspentOutput.Address]
		sourceOutputs[unspentOutput.Address] = append(sourceAddressOutputs, unspentOutput)
	}

	var privatePassphrase string
	if len(sourceOutputs) != 0 {
		privatePassphrase, err = promptSecret("Wallet private passphrase")
		if err != nil {
			return errContext(err, "failed to read private passphrase")
		}
	}

	var totalSwept btcutil.Amount
	var numErrors int
	var reportError = func(format string, args ...interface{}) {
		fmt.Fprintf(os.Stderr, format, args...)
		os.Stderr.Write(newlineBytes)
		numErrors++
	}
	for _, previousOutputs := range sourceOutputs {
		inputSource := makeInputSource(previousOutputs)
		destinationSource := makeDestinationScriptSource(rpcClient, opts.DestinationAccount)
		tx, err := txauthor.NewUnsignedTransaction(nil, opts.FeeRate.Amount,
			inputSource, destinationSource)
		if err != nil {
			if err != (noInputValue{}) {
				reportError("Failed to create unsigned transaction: %v", err)
			}
			continue
		}

		// Unlock the wallet, sign the transaction, and immediately lock.
		err = rpcClient.WalletPassphrase(privatePassphrase, 60)
		if err != nil {
			reportError("Failed to unlock wallet: %v", err)
			continue
		}
		signedTransaction, complete, err := rpcClient.SignRawTransaction(tx.Tx)
		_ = rpcClient.WalletLock()
		if err != nil {
			reportError("Failed to sign transaction: %v", err)
			continue
		}
		if !complete {
			reportError("Failed to sign every input")
			continue
		}

		// Publish the signed sweep transaction.
		txHash, err := rpcClient.SendRawTransaction(signedTransaction, false)
		if err != nil {
			reportError("Failed to publish transaction: %v", err)
			continue
		}

		outputAmount := btcutil.Amount(tx.Tx.TxOut[0].Value)
		fmt.Printf("Swept %v to destination account with transaction %v\n",
			outputAmount, txHash)
		totalSwept += outputAmount
	}

	numPublished := len(sourceOutputs) - numErrors
	transactionNoun := pickNoun(numErrors, "transaction", "transactions")
	if numPublished != 0 {
		fmt.Printf("Swept %v to destination account across %d %s\n",
			totalSwept, numPublished, transactionNoun)
	}
	if numErrors > 0 {
		return fmt.Errorf("Failed to publish %d %s", numErrors, transactionNoun)
	}

	return nil
}