func CfgFromFile() (*btcrpcclient.ConnConfig, bool, error) { fileconf := &BitcoinConf{} path := btcutil.AppDataDir("bitcoin", false) + "/bitcoin.conf" parser := flags.NewParser(fileconf, flags.IgnoreUnknown) err := flags.NewIniParser(parser).ParseFile(path) if err != nil { return nil, false, err } if !fileconf.RPCListen { return nil, false, errors.New("Bitcoind not listening for rpc commands") } // TODO make rpcaddr configurable var rpcaddr string if fileconf.Testnet { rpcaddr = "127.0.0.1:18332" } else { rpcaddr = "127.0.0.1:8332" } // TODO use tls! connCfg := &btcrpcclient.ConnConfig{ Host: rpcaddr, User: fileconf.RPCUser, Pass: fileconf.RPCPassword, HttpPostMode: true, DisableTLS: true, } return connCfg, fileconf.Testnet, nil }
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 *btcwire.ShaHash, height int32) { log.Printf("Block connected: %v (%d)", hash, height) }, OnBlockDisconnected: func(hash *btcwire.ShaHash, height int32) { log.Printf("Block disconnected: %v (%d)", hash, height) }, } // 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() }
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() }
// 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)) }
func main() { flag.Parse() ntfnHandlers := btcrpcclient.NotificationHandlers{ OnTxAccepted: func(hash *btcwire.ShaHash, amount btcutil.Amount) { h.broadcast <- []byte(strconv.FormatFloat(amount.ToUnit(0), 'f', -1, 64)) log.Printf("Tx Accepted: %v (%s)", hash, amount.String()) }, } var certFile string if *rpcCert != "" { certFile = *rpcCert } else { btcdHomeDir := btcutil.AppDataDir("btcd", false) filepath.Join(btcdHomeDir, "rpc.cert") certFile = filepath.Join(btcdHomeDir, "rpc.cert") } certs, _ := ioutil.ReadFile(certFile) connCfg := &btcrpcclient.ConnConfig{ Host: *rpcHost, Endpoint: "ws", User: *rpcUser, Pass: *rpcPass, Certificates: certs, } // Connect to btcd server client, err := btcrpcclient.New(connCfg, &ntfnHandlers) if err != nil { log.Fatal(err) } client.NotifyNewTransactions(false) // Start Websocket server go h.run() http.HandleFunc("/", serveWs) err = http.ListenAndServe(*address, nil) if err != nil { log.Fatal("Error starting http listener: ", err) } }
func main() { var ( dataDir = flag.String("datadir", filepath.Join(btcutil.AppDataDir("btcd", false), "data"), "BTCD: Data directory") dbType = flag.String("dbtype", "leveldb", "BTCD: Database backend") ) flag.Parse() if *cpuprofile != "" { f, err := os.Create(*cpuprofile) if err != nil { log.Fatal(err) } pprof.StartCPUProfile(f) defer pprof.StopCPUProfile() } // Setup btcdb log, db, dbCleanup := btcdbSetup(*dataDir, *dbType) defer dbCleanup() duplicates := search(log, db) realDuplicates := make(map[string][]*rData) for k, v := range duplicates { if len(v) > 1 { realDuplicates[k] = v } } resultsFile, err := os.Create("blockchainr.json") if err != nil { log.Warnf("failed to create blockchainr.json: %v", err) return } if json.NewEncoder(resultsFile).Encode(realDuplicates) != nil { log.Warnf("failed to Encode the result: %v", err) return } }
type config struct { DataDir string `short:"b" long:"datadir" description:"Directory to store data"` DbType string `long:"dbtype" description:"Database backend"` TestNet3 bool `long:"testnet" description:"Use the test network"` OutFile string `short:"o" description:"outfile"` Progress bool `short:"p" description:"show progress"` ShaString string `short:"s" description:"Block SHA to process" required:"true"` EShaString string `short:"e" description:"End Block SHA to process"` RawBlock bool `short:"r" description:"Raw Block"` FmtBlock bool `short:"f" description:"Format Block"` ShowTx bool `short:"t" description:"Show transaction"` } var ( btcdHomeDir = btcutil.AppDataDir("btcd", false) defaultDataDir = filepath.Join(btcdHomeDir, "data") log btclog.Logger ) const ( ArgSha = iota ArgHeight ) func main() { end := int64(-1) cfg := config{ DbType: "leveldb", DataDir: defaultDataDir,
"log" "net" "os" "path/filepath" "strings" ) const ( defualtCAFilename = "btcwallet.cert" defaultConfigFilename = "btcgui.conf" defaultDataDirname = "data" defaultBtcNet = btcwire.TestNet3 ) var ( btcguiHomeDir = btcutil.AppDataDir("btcgui", false) btcwalletHomeDir = btcutil.AppDataDir("btcwallet", false) defaultCAFile = filepath.Join(btcguiHomeDir, defualtCAFilename) btcwalletHomedirCAFile = filepath.Join(btcwalletHomeDir, "rpc.cert") defaultConfigFile = filepath.Join(btcguiHomeDir, defaultConfigFilename) defaultDataDir = filepath.Join(btcguiHomeDir, defaultDataDirname) ) type config struct { ShowVersion bool `short:"V" long:"version" description:"Display version information and exit"` CAFile string `long:"cafile" description:"File containing root certificates to authenticate a TLS connections with btcwallet"` Connect string `short:"c" long:"connect" description:"Server and port of btcwallet instance to connect to (default localhost:18332, mainnet: localhost:8332)"` ConfigFile string `short:"C" long:"configfile" description:"Path to configuration file"` Username string `short:"u" long:"username" description:"Username for btcwallet authorization"` Password string `short:"P" long:"password" description:"Password for btcwallet authorization"` MainNet bool `long:"mainnet" description:"Use the main Bitcoin network (default testnet3)"`
package main import ( "fmt" "net" "os" "path/filepath" "strings" "github.com/conformal/btcutil" flags "github.com/conformal/go-flags" ) var ( btcdHomeDir = btcutil.AppDataDir("btcd", false) btcctlHomeDir = btcutil.AppDataDir("btcctl", false) btcwalletHomeDir = btcutil.AppDataDir("btcwallet", false) defaultConfigFile = filepath.Join(btcctlHomeDir, "btcctl.conf") defaultRPCServer = "localhost" defaultRPCCertFile = filepath.Join(btcdHomeDir, "rpc.cert") defaultWalletCertFile = filepath.Join(btcwalletHomeDir, "rpc.cert") ) // config defines the configuration options for btcctl. // // See loadConfig for details on the configuration load process. type config struct { ShowVersion bool `short:"V" long:"version" description:"Display version information and exit"` ConfigFile string `short:"C" long:"configfile" description:"Path to configuration file"` RPCUser string `short:"u" long:"rpcuser" description:"RPC username"` RPCPassword string `short:"P" long:"rpcpass" default-mask:"-" description:"RPC password"`
// 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
func main() { var ( dataDir = flag.String("datadir", filepath.Join(btcutil.AppDataDir("btcd", false), "data"), "BTCD: Data directory") dbType = flag.String("dbtype", "leveldb", "BTCD: Database backend") ) flag.Parse() db, err := btcdbSetup(*dataDir, *dbType) if err != nil { log.Println("btcdbSetup error:", err) return } defer db.Close() var jsonFile = flag.String("json", "blockchainr.json", "blockchainr output") flag.Parse() blockchainrFile, err := ioutil.ReadFile(*jsonFile) if err != nil { log.Println("failed to read blockchainr.json:", err) return } results := make(map[string][]*inData) err = json.Unmarshal(blockchainrFile, &results) if err != nil { log.Println("Unmarshal error:", err) return } fmt.Println("blkH\tblkSha\tblkTime\ttxIndex\ttxSha\ttxInIndex\tprevBlkH\tprevBlkSha\tprevBlkTime\tr\taddr\twif") targets := make(map[[2]string][]*rData) for r, inDataList := range results { for _, in := range inDataList { rd := &rData{r: r, in: in} if err := fetch(db, rd); err != nil { log.Println("Skipping at fetch:", err) printLine(rd) continue } switch t := btcscript.GetScriptClass(rd.txPrevOut.PkScript); t { case btcscript.PubKeyHashTy: if err := processPubKeyHash(db, rd); err != nil { log.Println("Skipping at opCheckSig:", err) printLine(rd) continue } default: log.Println("Unsupported pkScript type:", btcscript.ScriptClassToName[t], rd.in) printLine(rd) continue } // TODO: group compressed and uncompressed together key := [...]string{rd.address, rd.r} targets[key] = append(targets[key], rd) } } // Do the magic! for _, target := range targets { if len(target) < 2 { // The r value was reused across different addresses // TODO: also this information would be interesting to graph for _, rd := range target { printLine(rd) } continue } a := target[0] b := target[1] log.Printf("[%v]\n", a.address) log.Printf("Repeated r value: %v (%v times)\n", a.r, len(target)) privKey := recoverKey(a.signature, b.signature, a.hash, b.hash, a.pubKey) if privKey == nil { log.Print("recoverKey error\n\n") continue } wif, err := btcutil.NewWIF(privKey, &btcnet.MainNetParams, a.compressed) if err != nil { log.Printf("NewWIF error: %v\n\n", err) continue } for _, rd := range target { rd.wif = wif printLine(rd) } log.Printf("%v\n\n", wif.String()) } }