repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
btcsuite/btcwallet | chain/block_filterer.go | FilterOutputAddrs | func (bf *BlockFilterer) FilterOutputAddrs(addrs []btcutil.Address) bool {
var isRelevant bool
for _, addr := range addrs {
addrStr := addr.EncodeAddress()
if scopedIndex, ok := bf.ExReverseFilter[addrStr]; ok {
bf.foundExternal(scopedIndex)
isRelevant = true
}
if scopedIndex, ok := bf.InReverseFilter[addrStr]; ok {
bf.foundInternal(scopedIndex)
isRelevant = true
}
}
return isRelevant
} | go | func (bf *BlockFilterer) FilterOutputAddrs(addrs []btcutil.Address) bool {
var isRelevant bool
for _, addr := range addrs {
addrStr := addr.EncodeAddress()
if scopedIndex, ok := bf.ExReverseFilter[addrStr]; ok {
bf.foundExternal(scopedIndex)
isRelevant = true
}
if scopedIndex, ok := bf.InReverseFilter[addrStr]; ok {
bf.foundInternal(scopedIndex)
isRelevant = true
}
}
return isRelevant
} | [
"func",
"(",
"bf",
"*",
"BlockFilterer",
")",
"FilterOutputAddrs",
"(",
"addrs",
"[",
"]",
"btcutil",
".",
"Address",
")",
"bool",
"{",
"var",
"isRelevant",
"bool",
"\n",
"for",
"_",
",",
"addr",
":=",
"range",
"addrs",
"{",
"addrStr",
":=",
"addr",
".... | // FilterOutputAddrs tests the set of addresses against the block filterer's
// external and internal reverse address indexes. If any are found, they are
// added to set of external and internal found addresses, respectively. This
// method returns true iff a non-zero number of the provided addresses are of
// interest. | [
"FilterOutputAddrs",
"tests",
"the",
"set",
"of",
"addresses",
"against",
"the",
"block",
"filterer",
"s",
"external",
"and",
"internal",
"reverse",
"address",
"indexes",
".",
"If",
"any",
"are",
"found",
"they",
"are",
"added",
"to",
"set",
"of",
"external",
... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/block_filterer.go#L182-L197 | train |
btcsuite/btcwallet | chain/block_filterer.go | foundExternal | func (bf *BlockFilterer) foundExternal(scopedIndex waddrmgr.ScopedIndex) {
if _, ok := bf.FoundExternal[scopedIndex.Scope]; !ok {
bf.FoundExternal[scopedIndex.Scope] = make(map[uint32]struct{})
}
bf.FoundExternal[scopedIndex.Scope][scopedIndex.Index] = struct{}{}
} | go | func (bf *BlockFilterer) foundExternal(scopedIndex waddrmgr.ScopedIndex) {
if _, ok := bf.FoundExternal[scopedIndex.Scope]; !ok {
bf.FoundExternal[scopedIndex.Scope] = make(map[uint32]struct{})
}
bf.FoundExternal[scopedIndex.Scope][scopedIndex.Index] = struct{}{}
} | [
"func",
"(",
"bf",
"*",
"BlockFilterer",
")",
"foundExternal",
"(",
"scopedIndex",
"waddrmgr",
".",
"ScopedIndex",
")",
"{",
"if",
"_",
",",
"ok",
":=",
"bf",
".",
"FoundExternal",
"[",
"scopedIndex",
".",
"Scope",
"]",
";",
"!",
"ok",
"{",
"bf",
".",
... | // foundExternal marks the scoped index as found within the block filterer's
// FoundExternal map. If this the first index found for a particular scope, the
// scope's second layer map will be initialized before marking the index. | [
"foundExternal",
"marks",
"the",
"scoped",
"index",
"as",
"found",
"within",
"the",
"block",
"filterer",
"s",
"FoundExternal",
"map",
".",
"If",
"this",
"the",
"first",
"index",
"found",
"for",
"a",
"particular",
"scope",
"the",
"scope",
"s",
"second",
"laye... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/block_filterer.go#L202-L207 | train |
btcsuite/btcwallet | chain/block_filterer.go | foundInternal | func (bf *BlockFilterer) foundInternal(scopedIndex waddrmgr.ScopedIndex) {
if _, ok := bf.FoundInternal[scopedIndex.Scope]; !ok {
bf.FoundInternal[scopedIndex.Scope] = make(map[uint32]struct{})
}
bf.FoundInternal[scopedIndex.Scope][scopedIndex.Index] = struct{}{}
} | go | func (bf *BlockFilterer) foundInternal(scopedIndex waddrmgr.ScopedIndex) {
if _, ok := bf.FoundInternal[scopedIndex.Scope]; !ok {
bf.FoundInternal[scopedIndex.Scope] = make(map[uint32]struct{})
}
bf.FoundInternal[scopedIndex.Scope][scopedIndex.Index] = struct{}{}
} | [
"func",
"(",
"bf",
"*",
"BlockFilterer",
")",
"foundInternal",
"(",
"scopedIndex",
"waddrmgr",
".",
"ScopedIndex",
")",
"{",
"if",
"_",
",",
"ok",
":=",
"bf",
".",
"FoundInternal",
"[",
"scopedIndex",
".",
"Scope",
"]",
";",
"!",
"ok",
"{",
"bf",
".",
... | // foundInternal marks the scoped index as found within the block filterer's
// FoundInternal map. If this the first index found for a particular scope, the
// scope's second layer map will be initialized before marking the index. | [
"foundInternal",
"marks",
"the",
"scoped",
"index",
"as",
"found",
"within",
"the",
"block",
"filterer",
"s",
"FoundInternal",
"map",
".",
"If",
"this",
"the",
"first",
"index",
"found",
"for",
"a",
"particular",
"scope",
"the",
"scope",
"s",
"second",
"laye... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/block_filterer.go#L212-L217 | train |
btcsuite/btcwallet | rpc/rpcserver/server.go | StartWalletService | func StartWalletService(server *grpc.Server, wallet *wallet.Wallet) {
service := &walletServer{wallet}
pb.RegisterWalletServiceServer(server, service)
} | go | func StartWalletService(server *grpc.Server, wallet *wallet.Wallet) {
service := &walletServer{wallet}
pb.RegisterWalletServiceServer(server, service)
} | [
"func",
"StartWalletService",
"(",
"server",
"*",
"grpc",
".",
"Server",
",",
"wallet",
"*",
"wallet",
".",
"Wallet",
")",
"{",
"service",
":=",
"&",
"walletServer",
"{",
"wallet",
"}",
"\n",
"pb",
".",
"RegisterWalletServiceServer",
"(",
"server",
",",
"s... | // StartWalletService creates an implementation of the WalletService and
// registers it with the gRPC server. | [
"StartWalletService",
"creates",
"an",
"implementation",
"of",
"the",
"WalletService",
"and",
"registers",
"it",
"with",
"the",
"gRPC",
"server",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/rpcserver/server.go#L136-L139 | train |
btcsuite/btcwallet | rpc/rpcserver/server.go | StartWalletLoaderService | func StartWalletLoaderService(server *grpc.Server, loader *wallet.Loader,
activeNet *netparams.Params) {
service := &loaderServer{loader: loader, activeNet: activeNet}
pb.RegisterWalletLoaderServiceServer(server, service)
} | go | func StartWalletLoaderService(server *grpc.Server, loader *wallet.Loader,
activeNet *netparams.Params) {
service := &loaderServer{loader: loader, activeNet: activeNet}
pb.RegisterWalletLoaderServiceServer(server, service)
} | [
"func",
"StartWalletLoaderService",
"(",
"server",
"*",
"grpc",
".",
"Server",
",",
"loader",
"*",
"wallet",
".",
"Loader",
",",
"activeNet",
"*",
"netparams",
".",
"Params",
")",
"{",
"service",
":=",
"&",
"loaderServer",
"{",
"loader",
":",
"loader",
","... | // StartWalletLoaderService creates an implementation of the WalletLoaderService
// and registers it with the gRPC server. | [
"StartWalletLoaderService",
"creates",
"an",
"implementation",
"of",
"the",
"WalletLoaderService",
"and",
"registers",
"it",
"with",
"the",
"gRPC",
"server",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/rpcserver/server.go#L704-L709 | train |
btcsuite/btcwallet | rpc/legacyrpc/server.go | jsonAuthFail | func jsonAuthFail(w http.ResponseWriter) {
w.Header().Add("WWW-Authenticate", `Basic realm="btcwallet RPC"`)
http.Error(w, "401 Unauthorized.", http.StatusUnauthorized)
} | go | func jsonAuthFail(w http.ResponseWriter) {
w.Header().Add("WWW-Authenticate", `Basic realm="btcwallet RPC"`)
http.Error(w, "401 Unauthorized.", http.StatusUnauthorized)
} | [
"func",
"jsonAuthFail",
"(",
"w",
"http",
".",
"ResponseWriter",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"WWW-Authenticate\"",
",",
"`Basic realm=\"btcwallet RPC\"`",
")",
"\n",
"http",
".",
"Error",
"(",
"w",
",",
"\"401 Unauthorized.\"",
... | // jsonAuthFail sends a message back to the client if the http auth is rejected. | [
"jsonAuthFail",
"sends",
"a",
"message",
"back",
"to",
"the",
"client",
"if",
"the",
"http",
"auth",
"is",
"rejected",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/server.go#L83-L86 | train |
btcsuite/btcwallet | rpc/legacyrpc/server.go | NewServer | func NewServer(opts *Options, walletLoader *wallet.Loader, listeners []net.Listener) *Server {
serveMux := http.NewServeMux()
const rpcAuthTimeoutSeconds = 10
server := &Server{
httpServer: http.Server{
Handler: serveMux,
// Timeout connections which don't complete the initial
// handshake within the allowed timeframe.
ReadTimeout: time.Second * rpcAuthTimeoutSeconds,
},
walletLoader: walletLoader,
maxPostClients: opts.MaxPOSTClients,
maxWebsocketClients: opts.MaxWebsocketClients,
listeners: listeners,
// A hash of the HTTP basic auth string is used for a constant
// time comparison.
authsha: sha256.Sum256(httpBasicAuth(opts.Username, opts.Password)),
upgrader: websocket.Upgrader{
// Allow all origins.
CheckOrigin: func(r *http.Request) bool { return true },
},
quit: make(chan struct{}),
requestShutdownChan: make(chan struct{}, 1),
}
serveMux.Handle("/", throttledFn(opts.MaxPOSTClients,
func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Connection", "close")
w.Header().Set("Content-Type", "application/json")
r.Close = true
if err := server.checkAuthHeader(r); err != nil {
log.Warnf("Unauthorized client connection attempt")
jsonAuthFail(w)
return
}
server.wg.Add(1)
server.postClientRPC(w, r)
server.wg.Done()
}))
serveMux.Handle("/ws", throttledFn(opts.MaxWebsocketClients,
func(w http.ResponseWriter, r *http.Request) {
authenticated := false
switch server.checkAuthHeader(r) {
case nil:
authenticated = true
case ErrNoAuth:
// nothing
default:
// If auth was supplied but incorrect, rather than simply
// being missing, immediately terminate the connection.
log.Warnf("Disconnecting improperly authorized " +
"websocket client")
jsonAuthFail(w)
return
}
conn, err := server.upgrader.Upgrade(w, r, nil)
if err != nil {
log.Warnf("Cannot websocket upgrade client %s: %v",
r.RemoteAddr, err)
return
}
wsc := newWebsocketClient(conn, authenticated, r.RemoteAddr)
server.websocketClientRPC(wsc)
}))
for _, lis := range listeners {
server.serve(lis)
}
return server
} | go | func NewServer(opts *Options, walletLoader *wallet.Loader, listeners []net.Listener) *Server {
serveMux := http.NewServeMux()
const rpcAuthTimeoutSeconds = 10
server := &Server{
httpServer: http.Server{
Handler: serveMux,
// Timeout connections which don't complete the initial
// handshake within the allowed timeframe.
ReadTimeout: time.Second * rpcAuthTimeoutSeconds,
},
walletLoader: walletLoader,
maxPostClients: opts.MaxPOSTClients,
maxWebsocketClients: opts.MaxWebsocketClients,
listeners: listeners,
// A hash of the HTTP basic auth string is used for a constant
// time comparison.
authsha: sha256.Sum256(httpBasicAuth(opts.Username, opts.Password)),
upgrader: websocket.Upgrader{
// Allow all origins.
CheckOrigin: func(r *http.Request) bool { return true },
},
quit: make(chan struct{}),
requestShutdownChan: make(chan struct{}, 1),
}
serveMux.Handle("/", throttledFn(opts.MaxPOSTClients,
func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Connection", "close")
w.Header().Set("Content-Type", "application/json")
r.Close = true
if err := server.checkAuthHeader(r); err != nil {
log.Warnf("Unauthorized client connection attempt")
jsonAuthFail(w)
return
}
server.wg.Add(1)
server.postClientRPC(w, r)
server.wg.Done()
}))
serveMux.Handle("/ws", throttledFn(opts.MaxWebsocketClients,
func(w http.ResponseWriter, r *http.Request) {
authenticated := false
switch server.checkAuthHeader(r) {
case nil:
authenticated = true
case ErrNoAuth:
// nothing
default:
// If auth was supplied but incorrect, rather than simply
// being missing, immediately terminate the connection.
log.Warnf("Disconnecting improperly authorized " +
"websocket client")
jsonAuthFail(w)
return
}
conn, err := server.upgrader.Upgrade(w, r, nil)
if err != nil {
log.Warnf("Cannot websocket upgrade client %s: %v",
r.RemoteAddr, err)
return
}
wsc := newWebsocketClient(conn, authenticated, r.RemoteAddr)
server.websocketClientRPC(wsc)
}))
for _, lis := range listeners {
server.serve(lis)
}
return server
} | [
"func",
"NewServer",
"(",
"opts",
"*",
"Options",
",",
"walletLoader",
"*",
"wallet",
".",
"Loader",
",",
"listeners",
"[",
"]",
"net",
".",
"Listener",
")",
"*",
"Server",
"{",
"serveMux",
":=",
"http",
".",
"NewServeMux",
"(",
")",
"\n",
"const",
"rp... | // NewServer creates a new server for serving legacy RPC client connections,
// both HTTP POST and websocket. | [
"NewServer",
"creates",
"a",
"new",
"server",
"for",
"serving",
"legacy",
"RPC",
"client",
"connections",
"both",
"HTTP",
"POST",
"and",
"websocket",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/server.go#L90-L165 | train |
btcsuite/btcwallet | rpc/legacyrpc/server.go | serve | func (s *Server) serve(lis net.Listener) {
s.wg.Add(1)
go func() {
log.Infof("Listening on %s", lis.Addr())
err := s.httpServer.Serve(lis)
log.Tracef("Finished serving RPC: %v", err)
s.wg.Done()
}()
} | go | func (s *Server) serve(lis net.Listener) {
s.wg.Add(1)
go func() {
log.Infof("Listening on %s", lis.Addr())
err := s.httpServer.Serve(lis)
log.Tracef("Finished serving RPC: %v", err)
s.wg.Done()
}()
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"serve",
"(",
"lis",
"net",
".",
"Listener",
")",
"{",
"s",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"log",
".",
"Infof",
"(",
"\"Listening on %s\"",
",",
"lis",
".",
"Addr",... | // serve serves HTTP POST and websocket RPC for the legacy JSON-RPC RPC server.
// This function does not block on lis.Accept. | [
"serve",
"serves",
"HTTP",
"POST",
"and",
"websocket",
"RPC",
"for",
"the",
"legacy",
"JSON",
"-",
"RPC",
"RPC",
"server",
".",
"This",
"function",
"does",
"not",
"block",
"on",
"lis",
".",
"Accept",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/server.go#L189-L197 | train |
btcsuite/btcwallet | rpc/legacyrpc/server.go | RegisterWallet | func (s *Server) RegisterWallet(w *wallet.Wallet) {
s.handlerMu.Lock()
s.wallet = w
s.handlerMu.Unlock()
} | go | func (s *Server) RegisterWallet(w *wallet.Wallet) {
s.handlerMu.Lock()
s.wallet = w
s.handlerMu.Unlock()
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"RegisterWallet",
"(",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"{",
"s",
".",
"handlerMu",
".",
"Lock",
"(",
")",
"\n",
"s",
".",
"wallet",
"=",
"w",
"\n",
"s",
".",
"handlerMu",
".",
"Unlock",
"(",
")",
"\... | // RegisterWallet associates the legacy RPC server with the wallet. This
// function must be called before any wallet RPCs can be called by clients. | [
"RegisterWallet",
"associates",
"the",
"legacy",
"RPC",
"server",
"with",
"the",
"wallet",
".",
"This",
"function",
"must",
"be",
"called",
"before",
"any",
"wallet",
"RPCs",
"can",
"be",
"called",
"by",
"clients",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/server.go#L201-L205 | train |
btcsuite/btcwallet | rpc/legacyrpc/server.go | Stop | func (s *Server) Stop() {
s.quitMtx.Lock()
select {
case <-s.quit:
s.quitMtx.Unlock()
return
default:
}
// Stop the connected wallet and chain server, if any.
s.handlerMu.Lock()
wallet := s.wallet
chainClient := s.chainClient
s.handlerMu.Unlock()
if wallet != nil {
wallet.Stop()
}
if chainClient != nil {
chainClient.Stop()
}
// Stop all the listeners.
for _, listener := range s.listeners {
err := listener.Close()
if err != nil {
log.Errorf("Cannot close listener `%s`: %v",
listener.Addr(), err)
}
}
// Signal the remaining goroutines to stop.
close(s.quit)
s.quitMtx.Unlock()
// First wait for the wallet and chain server to stop, if they
// were ever set.
if wallet != nil {
wallet.WaitForShutdown()
}
if chainClient != nil {
chainClient.WaitForShutdown()
}
// Wait for all remaining goroutines to exit.
s.wg.Wait()
} | go | func (s *Server) Stop() {
s.quitMtx.Lock()
select {
case <-s.quit:
s.quitMtx.Unlock()
return
default:
}
// Stop the connected wallet and chain server, if any.
s.handlerMu.Lock()
wallet := s.wallet
chainClient := s.chainClient
s.handlerMu.Unlock()
if wallet != nil {
wallet.Stop()
}
if chainClient != nil {
chainClient.Stop()
}
// Stop all the listeners.
for _, listener := range s.listeners {
err := listener.Close()
if err != nil {
log.Errorf("Cannot close listener `%s`: %v",
listener.Addr(), err)
}
}
// Signal the remaining goroutines to stop.
close(s.quit)
s.quitMtx.Unlock()
// First wait for the wallet and chain server to stop, if they
// were ever set.
if wallet != nil {
wallet.WaitForShutdown()
}
if chainClient != nil {
chainClient.WaitForShutdown()
}
// Wait for all remaining goroutines to exit.
s.wg.Wait()
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"Stop",
"(",
")",
"{",
"s",
".",
"quitMtx",
".",
"Lock",
"(",
")",
"\n",
"select",
"{",
"case",
"<-",
"s",
".",
"quit",
":",
"s",
".",
"quitMtx",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"default",
... | // Stop gracefully shuts down the rpc server by stopping and disconnecting all
// clients, disconnecting the chain server connection, and closing the wallet's
// account files. This blocks until shutdown completes. | [
"Stop",
"gracefully",
"shuts",
"down",
"the",
"rpc",
"server",
"by",
"stopping",
"and",
"disconnecting",
"all",
"clients",
"disconnecting",
"the",
"chain",
"server",
"connection",
"and",
"closing",
"the",
"wallet",
"s",
"account",
"files",
".",
"This",
"blocks",... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/server.go#L210-L255 | train |
btcsuite/btcwallet | rpc/legacyrpc/server.go | SetChainServer | func (s *Server) SetChainServer(chainClient chain.Interface) {
s.handlerMu.Lock()
s.chainClient = chainClient
s.handlerMu.Unlock()
} | go | func (s *Server) SetChainServer(chainClient chain.Interface) {
s.handlerMu.Lock()
s.chainClient = chainClient
s.handlerMu.Unlock()
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"SetChainServer",
"(",
"chainClient",
"chain",
".",
"Interface",
")",
"{",
"s",
".",
"handlerMu",
".",
"Lock",
"(",
")",
"\n",
"s",
".",
"chainClient",
"=",
"chainClient",
"\n",
"s",
".",
"handlerMu",
".",
"Unlock"... | // SetChainServer sets the chain server client component needed to run a fully
// functional bitcoin wallet RPC server. This can be called to enable RPC
// passthrough even before a loaded wallet is set, but the wallet's RPC client
// is preferred. | [
"SetChainServer",
"sets",
"the",
"chain",
"server",
"client",
"component",
"needed",
"to",
"run",
"a",
"fully",
"functional",
"bitcoin",
"wallet",
"RPC",
"server",
".",
"This",
"can",
"be",
"called",
"to",
"enable",
"RPC",
"passthrough",
"even",
"before",
"a",... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/server.go#L261-L265 | train |
btcsuite/btcwallet | rpc/legacyrpc/server.go | checkAuthHeader | func (s *Server) checkAuthHeader(r *http.Request) error {
authhdr := r.Header["Authorization"]
if len(authhdr) == 0 {
return ErrNoAuth
}
authsha := sha256.Sum256([]byte(authhdr[0]))
cmp := subtle.ConstantTimeCompare(authsha[:], s.authsha[:])
if cmp != 1 {
return errors.New("bad auth")
}
return nil
} | go | func (s *Server) checkAuthHeader(r *http.Request) error {
authhdr := r.Header["Authorization"]
if len(authhdr) == 0 {
return ErrNoAuth
}
authsha := sha256.Sum256([]byte(authhdr[0]))
cmp := subtle.ConstantTimeCompare(authsha[:], s.authsha[:])
if cmp != 1 {
return errors.New("bad auth")
}
return nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"checkAuthHeader",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"authhdr",
":=",
"r",
".",
"Header",
"[",
"\"Authorization\"",
"]",
"\n",
"if",
"len",
"(",
"authhdr",
")",
"==",
"0",
"{",
"return",
... | // checkAuthHeader checks the HTTP Basic authentication supplied by a client
// in the HTTP request r. It errors with ErrNoAuth if the request does not
// contain the Authorization header, or another non-nil error if the
// authentication was provided but incorrect.
//
// This check is time-constant. | [
"checkAuthHeader",
"checks",
"the",
"HTTP",
"Basic",
"authentication",
"supplied",
"by",
"a",
"client",
"in",
"the",
"HTTP",
"request",
"r",
".",
"It",
"errors",
"with",
"ErrNoAuth",
"if",
"the",
"request",
"does",
"not",
"contain",
"the",
"Authorization",
"he... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/server.go#L298-L310 | train |
btcsuite/btcwallet | rpc/legacyrpc/server.go | throttledFn | func throttledFn(threshold int64, f http.HandlerFunc) http.Handler {
return throttled(threshold, f)
} | go | func throttledFn(threshold int64, f http.HandlerFunc) http.Handler {
return throttled(threshold, f)
} | [
"func",
"throttledFn",
"(",
"threshold",
"int64",
",",
"f",
"http",
".",
"HandlerFunc",
")",
"http",
".",
"Handler",
"{",
"return",
"throttled",
"(",
"threshold",
",",
"f",
")",
"\n",
"}"
] | // throttledFn wraps an http.HandlerFunc with throttling of concurrent active
// clients by responding with an HTTP 429 when the threshold is crossed. | [
"throttledFn",
"wraps",
"an",
"http",
".",
"HandlerFunc",
"with",
"throttling",
"of",
"concurrent",
"active",
"clients",
"by",
"responding",
"with",
"an",
"HTTP",
"429",
"when",
"the",
"threshold",
"is",
"crossed",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/server.go#L314-L316 | train |
btcsuite/btcwallet | rpc/legacyrpc/server.go | throttled | func throttled(threshold int64, h http.Handler) http.Handler {
var active int64
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
current := atomic.AddInt64(&active, 1)
defer atomic.AddInt64(&active, -1)
if current-1 >= threshold {
log.Warnf("Reached threshold of %d concurrent active clients", threshold)
http.Error(w, "429 Too Many Requests", 429)
return
}
h.ServeHTTP(w, r)
})
} | go | func throttled(threshold int64, h http.Handler) http.Handler {
var active int64
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
current := atomic.AddInt64(&active, 1)
defer atomic.AddInt64(&active, -1)
if current-1 >= threshold {
log.Warnf("Reached threshold of %d concurrent active clients", threshold)
http.Error(w, "429 Too Many Requests", 429)
return
}
h.ServeHTTP(w, r)
})
} | [
"func",
"throttled",
"(",
"threshold",
"int64",
",",
"h",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"var",
"active",
"int64",
"\n",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*... | // throttled wraps an http.Handler with throttling of concurrent active
// clients by responding with an HTTP 429 when the threshold is crossed. | [
"throttled",
"wraps",
"an",
"http",
".",
"Handler",
"with",
"throttling",
"of",
"concurrent",
"active",
"clients",
"by",
"responding",
"with",
"an",
"HTTP",
"429",
"when",
"the",
"threshold",
"is",
"crossed",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/server.go#L320-L335 | train |
btcsuite/btcwallet | rpc/legacyrpc/server.go | sanitizeRequest | func sanitizeRequest(r *btcjson.Request) string {
// These are considered unsafe to log, so sanitize parameters.
switch r.Method {
case "encryptwallet", "importprivkey", "importwallet",
"signrawtransaction", "walletpassphrase",
"walletpassphrasechange":
return fmt.Sprintf(`{"id":%v,"method":"%s","params":SANITIZED %d parameters}`,
r.ID, r.Method, len(r.Params))
}
return fmt.Sprintf(`{"id":%v,"method":"%s","params":%v}`, r.ID,
r.Method, r.Params)
} | go | func sanitizeRequest(r *btcjson.Request) string {
// These are considered unsafe to log, so sanitize parameters.
switch r.Method {
case "encryptwallet", "importprivkey", "importwallet",
"signrawtransaction", "walletpassphrase",
"walletpassphrasechange":
return fmt.Sprintf(`{"id":%v,"method":"%s","params":SANITIZED %d parameters}`,
r.ID, r.Method, len(r.Params))
}
return fmt.Sprintf(`{"id":%v,"method":"%s","params":%v}`, r.ID,
r.Method, r.Params)
} | [
"func",
"sanitizeRequest",
"(",
"r",
"*",
"btcjson",
".",
"Request",
")",
"string",
"{",
"switch",
"r",
".",
"Method",
"{",
"case",
"\"encryptwallet\"",
",",
"\"importprivkey\"",
",",
"\"importwallet\"",
",",
"\"signrawtransaction\"",
",",
"\"walletpassphrase\"",
... | // sanitizeRequest returns a sanitized string for the request which may be
// safely logged. It is intended to strip private keys, passphrases, and any
// other secrets from request parameters before they may be saved to a log file. | [
"sanitizeRequest",
"returns",
"a",
"sanitized",
"string",
"for",
"the",
"request",
"which",
"may",
"be",
"safely",
"logged",
".",
"It",
"is",
"intended",
"to",
"strip",
"private",
"keys",
"passphrases",
"and",
"any",
"other",
"secrets",
"from",
"request",
"par... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/server.go#L340-L353 | train |
btcsuite/btcwallet | rpc/legacyrpc/server.go | websocketClientRPC | func (s *Server) websocketClientRPC(wsc *websocketClient) {
log.Infof("New websocket client %s", wsc.remoteAddr)
// Clear the read deadline set before the websocket hijacked
// the connection.
if err := wsc.conn.SetReadDeadline(time.Time{}); err != nil {
log.Warnf("Cannot remove read deadline: %v", err)
}
// WebsocketClientRead is intentionally not run with the waitgroup
// so it is ignored during shutdown. This is to prevent a hang during
// shutdown where the goroutine is blocked on a read of the
// websocket connection if the client is still connected.
go s.websocketClientRead(wsc)
s.wg.Add(2)
go s.websocketClientRespond(wsc)
go s.websocketClientSend(wsc)
<-wsc.quit
} | go | func (s *Server) websocketClientRPC(wsc *websocketClient) {
log.Infof("New websocket client %s", wsc.remoteAddr)
// Clear the read deadline set before the websocket hijacked
// the connection.
if err := wsc.conn.SetReadDeadline(time.Time{}); err != nil {
log.Warnf("Cannot remove read deadline: %v", err)
}
// WebsocketClientRead is intentionally not run with the waitgroup
// so it is ignored during shutdown. This is to prevent a hang during
// shutdown where the goroutine is blocked on a read of the
// websocket connection if the client is still connected.
go s.websocketClientRead(wsc)
s.wg.Add(2)
go s.websocketClientRespond(wsc)
go s.websocketClientSend(wsc)
<-wsc.quit
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"websocketClientRPC",
"(",
"wsc",
"*",
"websocketClient",
")",
"{",
"log",
".",
"Infof",
"(",
"\"New websocket client %s\"",
",",
"wsc",
".",
"remoteAddr",
")",
"\n",
"if",
"err",
":=",
"wsc",
".",
"conn",
".",
"SetR... | // websocketClientRPC starts the goroutines to serve JSON-RPC requests over a
// websocket connection for a single client. | [
"websocketClientRPC",
"starts",
"the",
"goroutines",
"to",
"serve",
"JSON",
"-",
"RPC",
"requests",
"over",
"a",
"websocket",
"connection",
"for",
"a",
"single",
"client",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/server.go#L539-L559 | train |
btcsuite/btcwallet | rpc/legacyrpc/server.go | postClientRPC | func (s *Server) postClientRPC(w http.ResponseWriter, r *http.Request) {
body := http.MaxBytesReader(w, r.Body, maxRequestSize)
rpcRequest, err := ioutil.ReadAll(body)
if err != nil {
// TODO: what if the underlying reader errored?
http.Error(w, "413 Request Too Large.",
http.StatusRequestEntityTooLarge)
return
}
// First check whether wallet has a handler for this request's method.
// If unfound, the request is sent to the chain server for further
// processing. While checking the methods, disallow authenticate
// requests, as they are invalid for HTTP POST clients.
var req btcjson.Request
err = json.Unmarshal(rpcRequest, &req)
if err != nil {
resp, err := btcjson.MarshalResponse(req.ID, nil, btcjson.ErrRPCInvalidRequest)
if err != nil {
log.Errorf("Unable to marshal response: %v", err)
http.Error(w, "500 Internal Server Error",
http.StatusInternalServerError)
return
}
_, err = w.Write(resp)
if err != nil {
log.Warnf("Cannot write invalid request request to "+
"client: %v", err)
}
return
}
// Create the response and error from the request. Two special cases
// are handled for the authenticate and stop request methods.
var res interface{}
var jsonErr *btcjson.RPCError
var stop bool
switch req.Method {
case "authenticate":
// Drop it.
return
case "stop":
stop = true
res = "btcwallet stopping"
default:
res, jsonErr = s.handlerClosure(&req)()
}
// Marshal and send.
mresp, err := btcjson.MarshalResponse(req.ID, res, jsonErr)
if err != nil {
log.Errorf("Unable to marshal response: %v", err)
http.Error(w, "500 Internal Server Error", http.StatusInternalServerError)
return
}
_, err = w.Write(mresp)
if err != nil {
log.Warnf("Unable to respond to client: %v", err)
}
if stop {
s.requestProcessShutdown()
}
} | go | func (s *Server) postClientRPC(w http.ResponseWriter, r *http.Request) {
body := http.MaxBytesReader(w, r.Body, maxRequestSize)
rpcRequest, err := ioutil.ReadAll(body)
if err != nil {
// TODO: what if the underlying reader errored?
http.Error(w, "413 Request Too Large.",
http.StatusRequestEntityTooLarge)
return
}
// First check whether wallet has a handler for this request's method.
// If unfound, the request is sent to the chain server for further
// processing. While checking the methods, disallow authenticate
// requests, as they are invalid for HTTP POST clients.
var req btcjson.Request
err = json.Unmarshal(rpcRequest, &req)
if err != nil {
resp, err := btcjson.MarshalResponse(req.ID, nil, btcjson.ErrRPCInvalidRequest)
if err != nil {
log.Errorf("Unable to marshal response: %v", err)
http.Error(w, "500 Internal Server Error",
http.StatusInternalServerError)
return
}
_, err = w.Write(resp)
if err != nil {
log.Warnf("Cannot write invalid request request to "+
"client: %v", err)
}
return
}
// Create the response and error from the request. Two special cases
// are handled for the authenticate and stop request methods.
var res interface{}
var jsonErr *btcjson.RPCError
var stop bool
switch req.Method {
case "authenticate":
// Drop it.
return
case "stop":
stop = true
res = "btcwallet stopping"
default:
res, jsonErr = s.handlerClosure(&req)()
}
// Marshal and send.
mresp, err := btcjson.MarshalResponse(req.ID, res, jsonErr)
if err != nil {
log.Errorf("Unable to marshal response: %v", err)
http.Error(w, "500 Internal Server Error", http.StatusInternalServerError)
return
}
_, err = w.Write(mresp)
if err != nil {
log.Warnf("Unable to respond to client: %v", err)
}
if stop {
s.requestProcessShutdown()
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"postClientRPC",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"body",
":=",
"http",
".",
"MaxBytesReader",
"(",
"w",
",",
"r",
".",
"Body",
",",
"maxRequestSize",
")",... | // postClientRPC processes and replies to a JSON-RPC client request. | [
"postClientRPC",
"processes",
"and",
"replies",
"to",
"a",
"JSON",
"-",
"RPC",
"client",
"request",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/server.go#L566-L629 | train |
btcsuite/btcwallet | wallet/multisig.go | MakeMultiSigScript | func (w *Wallet) MakeMultiSigScript(addrs []btcutil.Address, nRequired int) ([]byte, error) {
pubKeys := make([]*btcutil.AddressPubKey, len(addrs))
var dbtx walletdb.ReadTx
var addrmgrNs walletdb.ReadBucket
defer func() {
if dbtx != nil {
dbtx.Rollback()
}
}()
// The address list will made up either of addreseses (pubkey hash), for
// which we need to look up the keys in wallet, straight pubkeys, or a
// mixture of the two.
for i, addr := range addrs {
switch addr := addr.(type) {
default:
return nil, errors.New("cannot make multisig script for " +
"a non-secp256k1 public key or P2PKH address")
case *btcutil.AddressPubKey:
pubKeys[i] = addr
case *btcutil.AddressPubKeyHash:
if dbtx == nil {
var err error
dbtx, err = w.db.BeginReadTx()
if err != nil {
return nil, err
}
addrmgrNs = dbtx.ReadBucket(waddrmgrNamespaceKey)
}
addrInfo, err := w.Manager.Address(addrmgrNs, addr)
if err != nil {
return nil, err
}
serializedPubKey := addrInfo.(waddrmgr.ManagedPubKeyAddress).
PubKey().SerializeCompressed()
pubKeyAddr, err := btcutil.NewAddressPubKey(
serializedPubKey, w.chainParams)
if err != nil {
return nil, err
}
pubKeys[i] = pubKeyAddr
}
}
return txscript.MultiSigScript(pubKeys, nRequired)
} | go | func (w *Wallet) MakeMultiSigScript(addrs []btcutil.Address, nRequired int) ([]byte, error) {
pubKeys := make([]*btcutil.AddressPubKey, len(addrs))
var dbtx walletdb.ReadTx
var addrmgrNs walletdb.ReadBucket
defer func() {
if dbtx != nil {
dbtx.Rollback()
}
}()
// The address list will made up either of addreseses (pubkey hash), for
// which we need to look up the keys in wallet, straight pubkeys, or a
// mixture of the two.
for i, addr := range addrs {
switch addr := addr.(type) {
default:
return nil, errors.New("cannot make multisig script for " +
"a non-secp256k1 public key or P2PKH address")
case *btcutil.AddressPubKey:
pubKeys[i] = addr
case *btcutil.AddressPubKeyHash:
if dbtx == nil {
var err error
dbtx, err = w.db.BeginReadTx()
if err != nil {
return nil, err
}
addrmgrNs = dbtx.ReadBucket(waddrmgrNamespaceKey)
}
addrInfo, err := w.Manager.Address(addrmgrNs, addr)
if err != nil {
return nil, err
}
serializedPubKey := addrInfo.(waddrmgr.ManagedPubKeyAddress).
PubKey().SerializeCompressed()
pubKeyAddr, err := btcutil.NewAddressPubKey(
serializedPubKey, w.chainParams)
if err != nil {
return nil, err
}
pubKeys[i] = pubKeyAddr
}
}
return txscript.MultiSigScript(pubKeys, nRequired)
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"MakeMultiSigScript",
"(",
"addrs",
"[",
"]",
"btcutil",
".",
"Address",
",",
"nRequired",
"int",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"pubKeys",
":=",
"make",
"(",
"[",
"]",
"*",
"btcutil",
".",... | // MakeMultiSigScript creates a multi-signature script that can be redeemed with
// nRequired signatures of the passed keys and addresses. If the address is a
// P2PKH address, the associated pubkey is looked up by the wallet if possible,
// otherwise an error is returned for a missing pubkey.
//
// This function only works with pubkeys and P2PKH addresses derived from them. | [
"MakeMultiSigScript",
"creates",
"a",
"multi",
"-",
"signature",
"script",
"that",
"can",
"be",
"redeemed",
"with",
"nRequired",
"signatures",
"of",
"the",
"passed",
"keys",
"and",
"addresses",
".",
"If",
"the",
"address",
"is",
"a",
"P2PKH",
"address",
"the",... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/multisig.go#L23-L72 | train |
btcsuite/btcwallet | wallet/multisig.go | ImportP2SHRedeemScript | func (w *Wallet) ImportP2SHRedeemScript(script []byte) (*btcutil.AddressScriptHash, error) {
var p2shAddr *btcutil.AddressScriptHash
err := walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
// TODO(oga) blockstamp current block?
bs := &waddrmgr.BlockStamp{
Hash: *w.ChainParams().GenesisHash,
Height: 0,
}
// As this is a regular P2SH script, we'll import this into the
// BIP0044 scope.
bip44Mgr, err := w.Manager.FetchScopedKeyManager(
waddrmgr.KeyScopeBIP0084,
)
if err != nil {
return err
}
addrInfo, err := bip44Mgr.ImportScript(addrmgrNs, script, bs)
if err != nil {
// Don't care if it's already there, but still have to
// set the p2shAddr since the address manager didn't
// return anything useful.
if waddrmgr.IsError(err, waddrmgr.ErrDuplicateAddress) {
// This function will never error as it always
// hashes the script to the correct length.
p2shAddr, _ = btcutil.NewAddressScriptHash(script,
w.chainParams)
return nil
}
return err
}
p2shAddr = addrInfo.Address().(*btcutil.AddressScriptHash)
return nil
})
return p2shAddr, err
} | go | func (w *Wallet) ImportP2SHRedeemScript(script []byte) (*btcutil.AddressScriptHash, error) {
var p2shAddr *btcutil.AddressScriptHash
err := walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
// TODO(oga) blockstamp current block?
bs := &waddrmgr.BlockStamp{
Hash: *w.ChainParams().GenesisHash,
Height: 0,
}
// As this is a regular P2SH script, we'll import this into the
// BIP0044 scope.
bip44Mgr, err := w.Manager.FetchScopedKeyManager(
waddrmgr.KeyScopeBIP0084,
)
if err != nil {
return err
}
addrInfo, err := bip44Mgr.ImportScript(addrmgrNs, script, bs)
if err != nil {
// Don't care if it's already there, but still have to
// set the p2shAddr since the address manager didn't
// return anything useful.
if waddrmgr.IsError(err, waddrmgr.ErrDuplicateAddress) {
// This function will never error as it always
// hashes the script to the correct length.
p2shAddr, _ = btcutil.NewAddressScriptHash(script,
w.chainParams)
return nil
}
return err
}
p2shAddr = addrInfo.Address().(*btcutil.AddressScriptHash)
return nil
})
return p2shAddr, err
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"ImportP2SHRedeemScript",
"(",
"script",
"[",
"]",
"byte",
")",
"(",
"*",
"btcutil",
".",
"AddressScriptHash",
",",
"error",
")",
"{",
"var",
"p2shAddr",
"*",
"btcutil",
".",
"AddressScriptHash",
"\n",
"err",
":=",
"... | // ImportP2SHRedeemScript adds a P2SH redeem script to the wallet. | [
"ImportP2SHRedeemScript",
"adds",
"a",
"P2SH",
"redeem",
"script",
"to",
"the",
"wallet",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/multisig.go#L75-L114 | train |
btcsuite/btcwallet | walletdb/migration/manager.go | VersionsToApply | func VersionsToApply(currentVersion uint32, versions []Version) []Version {
// Assuming the migration versions are in increasing order, we'll apply
// any migrations that have a version number lower than our current one.
var upgradeVersions []Version
for _, version := range versions {
if version.Number > currentVersion {
upgradeVersions = append(upgradeVersions, version)
}
}
// Before returning, we'll sort the slice by its version number to
// ensure the migrations are applied in their intended order.
sort.Slice(upgradeVersions, func(i, j int) bool {
return upgradeVersions[i].Number < upgradeVersions[j].Number
})
return upgradeVersions
} | go | func VersionsToApply(currentVersion uint32, versions []Version) []Version {
// Assuming the migration versions are in increasing order, we'll apply
// any migrations that have a version number lower than our current one.
var upgradeVersions []Version
for _, version := range versions {
if version.Number > currentVersion {
upgradeVersions = append(upgradeVersions, version)
}
}
// Before returning, we'll sort the slice by its version number to
// ensure the migrations are applied in their intended order.
sort.Slice(upgradeVersions, func(i, j int) bool {
return upgradeVersions[i].Number < upgradeVersions[j].Number
})
return upgradeVersions
} | [
"func",
"VersionsToApply",
"(",
"currentVersion",
"uint32",
",",
"versions",
"[",
"]",
"Version",
")",
"[",
"]",
"Version",
"{",
"var",
"upgradeVersions",
"[",
"]",
"Version",
"\n",
"for",
"_",
",",
"version",
":=",
"range",
"versions",
"{",
"if",
"version... | // VersionsToApply determines which versions should be applied as migrations
// based on the current version. | [
"VersionsToApply",
"determines",
"which",
"versions",
"should",
"be",
"applied",
"as",
"migrations",
"based",
"on",
"the",
"current",
"version",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/walletdb/migration/manager.go#L69-L86 | train |
btcsuite/btcwallet | walletdb/migration/manager.go | upgrade | func upgrade(mgr Manager) error {
// We'll start by fetching the service's current and latest version.
ns := mgr.Namespace()
currentVersion, err := mgr.CurrentVersion(ns)
if err != nil {
return err
}
versions := mgr.Versions()
latestVersion := GetLatestVersion(versions)
switch {
// If the current version is greater than the latest, then the service
// is attempting to revert to a previous version that's possibly
// backwards-incompatible. To prevent this, we'll return an error
// indicating so.
case currentVersion > latestVersion:
return ErrReversion
// If the current version is behind the latest version, we'll need to
// apply all of the newer versions in order to catch up to the latest.
case currentVersion < latestVersion:
versions := VersionsToApply(currentVersion, versions)
mgrName := mgr.Name()
ns := mgr.Namespace()
for _, version := range versions {
log.Infof("Applying %v migration #%d", mgrName,
version.Number)
// We'll only run a migration if there is one available
// for this version.
if version.Migration != nil {
err := version.Migration(ns)
if err != nil {
log.Errorf("Unable to apply %v "+
"migration #%d: %v", mgrName,
version.Number, err)
return err
}
}
}
// With all of the versions applied, we can now reflect the
// latest version upon the service.
if err := mgr.SetVersion(ns, latestVersion); err != nil {
return err
}
// If the current version matches the latest one, there's no upgrade
// needed and we can safely exit.
case currentVersion == latestVersion:
}
return nil
} | go | func upgrade(mgr Manager) error {
// We'll start by fetching the service's current and latest version.
ns := mgr.Namespace()
currentVersion, err := mgr.CurrentVersion(ns)
if err != nil {
return err
}
versions := mgr.Versions()
latestVersion := GetLatestVersion(versions)
switch {
// If the current version is greater than the latest, then the service
// is attempting to revert to a previous version that's possibly
// backwards-incompatible. To prevent this, we'll return an error
// indicating so.
case currentVersion > latestVersion:
return ErrReversion
// If the current version is behind the latest version, we'll need to
// apply all of the newer versions in order to catch up to the latest.
case currentVersion < latestVersion:
versions := VersionsToApply(currentVersion, versions)
mgrName := mgr.Name()
ns := mgr.Namespace()
for _, version := range versions {
log.Infof("Applying %v migration #%d", mgrName,
version.Number)
// We'll only run a migration if there is one available
// for this version.
if version.Migration != nil {
err := version.Migration(ns)
if err != nil {
log.Errorf("Unable to apply %v "+
"migration #%d: %v", mgrName,
version.Number, err)
return err
}
}
}
// With all of the versions applied, we can now reflect the
// latest version upon the service.
if err := mgr.SetVersion(ns, latestVersion); err != nil {
return err
}
// If the current version matches the latest one, there's no upgrade
// needed and we can safely exit.
case currentVersion == latestVersion:
}
return nil
} | [
"func",
"upgrade",
"(",
"mgr",
"Manager",
")",
"error",
"{",
"ns",
":=",
"mgr",
".",
"Namespace",
"(",
")",
"\n",
"currentVersion",
",",
"err",
":=",
"mgr",
".",
"CurrentVersion",
"(",
"ns",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
... | // upgrade attempts to upgrade a service expose through its implementation of
// the Manager interface. This function will determine whether any new versions
// need to be applied based on the service's current version and latest
// available one. | [
"upgrade",
"attempts",
"to",
"upgrade",
"a",
"service",
"expose",
"through",
"its",
"implementation",
"of",
"the",
"Manager",
"interface",
".",
"This",
"function",
"will",
"determine",
"whether",
"any",
"new",
"versions",
"need",
"to",
"be",
"applied",
"based",
... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/walletdb/migration/manager.go#L108-L162 | train |
btcsuite/btcwallet | wtxmgr/query.go | minedTxDetails | func (s *Store) minedTxDetails(ns walletdb.ReadBucket, txHash *chainhash.Hash, recKey, recVal []byte) (*TxDetails, error) {
var details TxDetails
// Parse transaction record k/v, lookup the full block record for the
// block time, and read all matching credits, debits.
err := readRawTxRecord(txHash, recVal, &details.TxRecord)
if err != nil {
return nil, err
}
err = readRawTxRecordBlock(recKey, &details.Block.Block)
if err != nil {
return nil, err
}
details.Block.Time, err = fetchBlockTime(ns, details.Block.Height)
if err != nil {
return nil, err
}
credIter := makeReadCreditIterator(ns, recKey)
for credIter.next() {
if int(credIter.elem.Index) >= len(details.MsgTx.TxOut) {
str := "saved credit index exceeds number of outputs"
return nil, storeError(ErrData, str, nil)
}
// The credit iterator does not record whether this credit was
// spent by an unmined transaction, so check that here.
if !credIter.elem.Spent {
k := canonicalOutPoint(txHash, credIter.elem.Index)
spent := existsRawUnminedInput(ns, k) != nil
credIter.elem.Spent = spent
}
details.Credits = append(details.Credits, credIter.elem)
}
if credIter.err != nil {
return nil, credIter.err
}
debIter := makeReadDebitIterator(ns, recKey)
for debIter.next() {
if int(debIter.elem.Index) >= len(details.MsgTx.TxIn) {
str := "saved debit index exceeds number of inputs"
return nil, storeError(ErrData, str, nil)
}
details.Debits = append(details.Debits, debIter.elem)
}
return &details, debIter.err
} | go | func (s *Store) minedTxDetails(ns walletdb.ReadBucket, txHash *chainhash.Hash, recKey, recVal []byte) (*TxDetails, error) {
var details TxDetails
// Parse transaction record k/v, lookup the full block record for the
// block time, and read all matching credits, debits.
err := readRawTxRecord(txHash, recVal, &details.TxRecord)
if err != nil {
return nil, err
}
err = readRawTxRecordBlock(recKey, &details.Block.Block)
if err != nil {
return nil, err
}
details.Block.Time, err = fetchBlockTime(ns, details.Block.Height)
if err != nil {
return nil, err
}
credIter := makeReadCreditIterator(ns, recKey)
for credIter.next() {
if int(credIter.elem.Index) >= len(details.MsgTx.TxOut) {
str := "saved credit index exceeds number of outputs"
return nil, storeError(ErrData, str, nil)
}
// The credit iterator does not record whether this credit was
// spent by an unmined transaction, so check that here.
if !credIter.elem.Spent {
k := canonicalOutPoint(txHash, credIter.elem.Index)
spent := existsRawUnminedInput(ns, k) != nil
credIter.elem.Spent = spent
}
details.Credits = append(details.Credits, credIter.elem)
}
if credIter.err != nil {
return nil, credIter.err
}
debIter := makeReadDebitIterator(ns, recKey)
for debIter.next() {
if int(debIter.elem.Index) >= len(details.MsgTx.TxIn) {
str := "saved debit index exceeds number of inputs"
return nil, storeError(ErrData, str, nil)
}
details.Debits = append(details.Debits, debIter.elem)
}
return &details, debIter.err
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"minedTxDetails",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"txHash",
"*",
"chainhash",
".",
"Hash",
",",
"recKey",
",",
"recVal",
"[",
"]",
"byte",
")",
"(",
"*",
"TxDetails",
",",
"error",
")",
"{",
"var",
... | // minedTxDetails fetches the TxDetails for the mined transaction with hash
// txHash and the passed tx record key and value. | [
"minedTxDetails",
"fetches",
"the",
"TxDetails",
"for",
"the",
"mined",
"transaction",
"with",
"hash",
"txHash",
"and",
"the",
"passed",
"tx",
"record",
"key",
"and",
"value",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/query.go#L46-L94 | train |
btcsuite/btcwallet | wtxmgr/query.go | unminedTxDetails | func (s *Store) unminedTxDetails(ns walletdb.ReadBucket, txHash *chainhash.Hash, v []byte) (*TxDetails, error) {
details := TxDetails{
Block: BlockMeta{Block: Block{Height: -1}},
}
err := readRawTxRecord(txHash, v, &details.TxRecord)
if err != nil {
return nil, err
}
it := makeReadUnminedCreditIterator(ns, txHash)
for it.next() {
if int(it.elem.Index) >= len(details.MsgTx.TxOut) {
str := "saved credit index exceeds number of outputs"
return nil, storeError(ErrData, str, nil)
}
// Set the Spent field since this is not done by the iterator.
it.elem.Spent = existsRawUnminedInput(ns, it.ck) != nil
details.Credits = append(details.Credits, it.elem)
}
if it.err != nil {
return nil, it.err
}
// Debit records are not saved for unmined transactions. Instead, they
// must be looked up for each transaction input manually. There are two
// kinds of previous credits that may be debited by an unmined
// transaction: mined unspent outputs (which remain marked unspent even
// when spent by an unmined transaction), and credits from other unmined
// transactions. Both situations must be considered.
for i, output := range details.MsgTx.TxIn {
opKey := canonicalOutPoint(&output.PreviousOutPoint.Hash,
output.PreviousOutPoint.Index)
credKey := existsRawUnspent(ns, opKey)
if credKey != nil {
v := existsRawCredit(ns, credKey)
amount, err := fetchRawCreditAmount(v)
if err != nil {
return nil, err
}
details.Debits = append(details.Debits, DebitRecord{
Amount: amount,
Index: uint32(i),
})
continue
}
v := existsRawUnminedCredit(ns, opKey)
if v == nil {
continue
}
amount, err := fetchRawCreditAmount(v)
if err != nil {
return nil, err
}
details.Debits = append(details.Debits, DebitRecord{
Amount: amount,
Index: uint32(i),
})
}
return &details, nil
} | go | func (s *Store) unminedTxDetails(ns walletdb.ReadBucket, txHash *chainhash.Hash, v []byte) (*TxDetails, error) {
details := TxDetails{
Block: BlockMeta{Block: Block{Height: -1}},
}
err := readRawTxRecord(txHash, v, &details.TxRecord)
if err != nil {
return nil, err
}
it := makeReadUnminedCreditIterator(ns, txHash)
for it.next() {
if int(it.elem.Index) >= len(details.MsgTx.TxOut) {
str := "saved credit index exceeds number of outputs"
return nil, storeError(ErrData, str, nil)
}
// Set the Spent field since this is not done by the iterator.
it.elem.Spent = existsRawUnminedInput(ns, it.ck) != nil
details.Credits = append(details.Credits, it.elem)
}
if it.err != nil {
return nil, it.err
}
// Debit records are not saved for unmined transactions. Instead, they
// must be looked up for each transaction input manually. There are two
// kinds of previous credits that may be debited by an unmined
// transaction: mined unspent outputs (which remain marked unspent even
// when spent by an unmined transaction), and credits from other unmined
// transactions. Both situations must be considered.
for i, output := range details.MsgTx.TxIn {
opKey := canonicalOutPoint(&output.PreviousOutPoint.Hash,
output.PreviousOutPoint.Index)
credKey := existsRawUnspent(ns, opKey)
if credKey != nil {
v := existsRawCredit(ns, credKey)
amount, err := fetchRawCreditAmount(v)
if err != nil {
return nil, err
}
details.Debits = append(details.Debits, DebitRecord{
Amount: amount,
Index: uint32(i),
})
continue
}
v := existsRawUnminedCredit(ns, opKey)
if v == nil {
continue
}
amount, err := fetchRawCreditAmount(v)
if err != nil {
return nil, err
}
details.Debits = append(details.Debits, DebitRecord{
Amount: amount,
Index: uint32(i),
})
}
return &details, nil
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"unminedTxDetails",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"txHash",
"*",
"chainhash",
".",
"Hash",
",",
"v",
"[",
"]",
"byte",
")",
"(",
"*",
"TxDetails",
",",
"error",
")",
"{",
"details",
":=",
"TxDetai... | // unminedTxDetails fetches the TxDetails for the unmined transaction with the
// hash txHash and the passed unmined record value. | [
"unminedTxDetails",
"fetches",
"the",
"TxDetails",
"for",
"the",
"unmined",
"transaction",
"with",
"the",
"hash",
"txHash",
"and",
"the",
"passed",
"unmined",
"record",
"value",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/query.go#L98-L162 | train |
btcsuite/btcwallet | wtxmgr/query.go | TxDetails | func (s *Store) TxDetails(ns walletdb.ReadBucket, txHash *chainhash.Hash) (*TxDetails, error) {
// First, check whether there exists an unmined transaction with this
// hash. Use it if found.
v := existsRawUnmined(ns, txHash[:])
if v != nil {
return s.unminedTxDetails(ns, txHash, v)
}
// Otherwise, if there exists a mined transaction with this matching
// hash, skip over to the newest and begin fetching all details.
k, v := latestTxRecord(ns, txHash)
if v == nil {
// not found
return nil, nil
}
return s.minedTxDetails(ns, txHash, k, v)
} | go | func (s *Store) TxDetails(ns walletdb.ReadBucket, txHash *chainhash.Hash) (*TxDetails, error) {
// First, check whether there exists an unmined transaction with this
// hash. Use it if found.
v := existsRawUnmined(ns, txHash[:])
if v != nil {
return s.unminedTxDetails(ns, txHash, v)
}
// Otherwise, if there exists a mined transaction with this matching
// hash, skip over to the newest and begin fetching all details.
k, v := latestTxRecord(ns, txHash)
if v == nil {
// not found
return nil, nil
}
return s.minedTxDetails(ns, txHash, k, v)
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"TxDetails",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"txHash",
"*",
"chainhash",
".",
"Hash",
")",
"(",
"*",
"TxDetails",
",",
"error",
")",
"{",
"v",
":=",
"existsRawUnmined",
"(",
"ns",
",",
"txHash",
"["... | // TxDetails looks up all recorded details regarding a transaction with some
// hash. In case of a hash collision, the most recent transaction with a
// matching hash is returned.
//
// Not finding a transaction with this hash is not an error. In this case,
// a nil TxDetails is returned. | [
"TxDetails",
"looks",
"up",
"all",
"recorded",
"details",
"regarding",
"a",
"transaction",
"with",
"some",
"hash",
".",
"In",
"case",
"of",
"a",
"hash",
"collision",
"the",
"most",
"recent",
"transaction",
"with",
"a",
"matching",
"hash",
"is",
"returned",
"... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/query.go#L170-L186 | train |
btcsuite/btcwallet | wtxmgr/query.go | UniqueTxDetails | func (s *Store) UniqueTxDetails(ns walletdb.ReadBucket, txHash *chainhash.Hash,
block *Block) (*TxDetails, error) {
if block == nil {
v := existsRawUnmined(ns, txHash[:])
if v == nil {
return nil, nil
}
return s.unminedTxDetails(ns, txHash, v)
}
k, v := existsTxRecord(ns, txHash, block)
if v == nil {
return nil, nil
}
return s.minedTxDetails(ns, txHash, k, v)
} | go | func (s *Store) UniqueTxDetails(ns walletdb.ReadBucket, txHash *chainhash.Hash,
block *Block) (*TxDetails, error) {
if block == nil {
v := existsRawUnmined(ns, txHash[:])
if v == nil {
return nil, nil
}
return s.unminedTxDetails(ns, txHash, v)
}
k, v := existsTxRecord(ns, txHash, block)
if v == nil {
return nil, nil
}
return s.minedTxDetails(ns, txHash, k, v)
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"UniqueTxDetails",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"txHash",
"*",
"chainhash",
".",
"Hash",
",",
"block",
"*",
"Block",
")",
"(",
"*",
"TxDetails",
",",
"error",
")",
"{",
"if",
"block",
"==",
"nil"... | // UniqueTxDetails looks up all recorded details for a transaction recorded
// mined in some particular block, or an unmined transaction if block is nil.
//
// Not finding a transaction with this hash from this block is not an error. In
// this case, a nil TxDetails is returned. | [
"UniqueTxDetails",
"looks",
"up",
"all",
"recorded",
"details",
"for",
"a",
"transaction",
"recorded",
"mined",
"in",
"some",
"particular",
"block",
"or",
"an",
"unmined",
"transaction",
"if",
"block",
"is",
"nil",
".",
"Not",
"finding",
"a",
"transaction",
"w... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/query.go#L193-L209 | train |
btcsuite/btcwallet | wtxmgr/query.go | PreviousPkScripts | func (s *Store) PreviousPkScripts(ns walletdb.ReadBucket, rec *TxRecord, block *Block) ([][]byte, error) {
var pkScripts [][]byte
if block == nil {
for _, input := range rec.MsgTx.TxIn {
prevOut := &input.PreviousOutPoint
// Input may spend a previous unmined output, a
// mined output (which would still be marked
// unspent), or neither.
v := existsRawUnmined(ns, prevOut.Hash[:])
if v != nil {
// Ensure a credit exists for this
// unmined transaction before including
// the output script.
k := canonicalOutPoint(&prevOut.Hash, prevOut.Index)
if existsRawUnminedCredit(ns, k) == nil {
continue
}
pkScript, err := fetchRawTxRecordPkScript(
prevOut.Hash[:], v, prevOut.Index)
if err != nil {
return nil, err
}
pkScripts = append(pkScripts, pkScript)
continue
}
_, credKey := existsUnspent(ns, prevOut)
if credKey != nil {
k := extractRawCreditTxRecordKey(credKey)
v = existsRawTxRecord(ns, k)
pkScript, err := fetchRawTxRecordPkScript(k, v,
prevOut.Index)
if err != nil {
return nil, err
}
pkScripts = append(pkScripts, pkScript)
continue
}
}
return pkScripts, nil
}
recKey := keyTxRecord(&rec.Hash, block)
it := makeReadDebitIterator(ns, recKey)
for it.next() {
credKey := extractRawDebitCreditKey(it.cv)
index := extractRawCreditIndex(credKey)
k := extractRawCreditTxRecordKey(credKey)
v := existsRawTxRecord(ns, k)
pkScript, err := fetchRawTxRecordPkScript(k, v, index)
if err != nil {
return nil, err
}
pkScripts = append(pkScripts, pkScript)
}
if it.err != nil {
return nil, it.err
}
return pkScripts, nil
} | go | func (s *Store) PreviousPkScripts(ns walletdb.ReadBucket, rec *TxRecord, block *Block) ([][]byte, error) {
var pkScripts [][]byte
if block == nil {
for _, input := range rec.MsgTx.TxIn {
prevOut := &input.PreviousOutPoint
// Input may spend a previous unmined output, a
// mined output (which would still be marked
// unspent), or neither.
v := existsRawUnmined(ns, prevOut.Hash[:])
if v != nil {
// Ensure a credit exists for this
// unmined transaction before including
// the output script.
k := canonicalOutPoint(&prevOut.Hash, prevOut.Index)
if existsRawUnminedCredit(ns, k) == nil {
continue
}
pkScript, err := fetchRawTxRecordPkScript(
prevOut.Hash[:], v, prevOut.Index)
if err != nil {
return nil, err
}
pkScripts = append(pkScripts, pkScript)
continue
}
_, credKey := existsUnspent(ns, prevOut)
if credKey != nil {
k := extractRawCreditTxRecordKey(credKey)
v = existsRawTxRecord(ns, k)
pkScript, err := fetchRawTxRecordPkScript(k, v,
prevOut.Index)
if err != nil {
return nil, err
}
pkScripts = append(pkScripts, pkScript)
continue
}
}
return pkScripts, nil
}
recKey := keyTxRecord(&rec.Hash, block)
it := makeReadDebitIterator(ns, recKey)
for it.next() {
credKey := extractRawDebitCreditKey(it.cv)
index := extractRawCreditIndex(credKey)
k := extractRawCreditTxRecordKey(credKey)
v := existsRawTxRecord(ns, k)
pkScript, err := fetchRawTxRecordPkScript(k, v, index)
if err != nil {
return nil, err
}
pkScripts = append(pkScripts, pkScript)
}
if it.err != nil {
return nil, it.err
}
return pkScripts, nil
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"PreviousPkScripts",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"rec",
"*",
"TxRecord",
",",
"block",
"*",
"Block",
")",
"(",
"[",
"]",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"pkScripts",
"[",
"]",... | // PreviousPkScripts returns a slice of previous output scripts for each credit
// output this transaction record debits from. | [
"PreviousPkScripts",
"returns",
"a",
"slice",
"of",
"previous",
"output",
"scripts",
"for",
"each",
"credit",
"output",
"this",
"transaction",
"record",
"debits",
"from",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/query.go#L391-L455 | train |
btcsuite/btcwallet | wallet/loader.go | NewLoader | func NewLoader(chainParams *chaincfg.Params, dbDirPath string,
recoveryWindow uint32) *Loader {
return &Loader{
chainParams: chainParams,
dbDirPath: dbDirPath,
recoveryWindow: recoveryWindow,
}
} | go | func NewLoader(chainParams *chaincfg.Params, dbDirPath string,
recoveryWindow uint32) *Loader {
return &Loader{
chainParams: chainParams,
dbDirPath: dbDirPath,
recoveryWindow: recoveryWindow,
}
} | [
"func",
"NewLoader",
"(",
"chainParams",
"*",
"chaincfg",
".",
"Params",
",",
"dbDirPath",
"string",
",",
"recoveryWindow",
"uint32",
")",
"*",
"Loader",
"{",
"return",
"&",
"Loader",
"{",
"chainParams",
":",
"chainParams",
",",
"dbDirPath",
":",
"dbDirPath",
... | // NewLoader constructs a Loader with an optional recovery window. If the
// recovery window is non-zero, the wallet will attempt to recovery addresses
// starting from the last SyncedTo height. | [
"NewLoader",
"constructs",
"a",
"Loader",
"with",
"an",
"optional",
"recovery",
"window",
".",
"If",
"the",
"recovery",
"window",
"is",
"non",
"-",
"zero",
"the",
"wallet",
"will",
"attempt",
"to",
"recovery",
"addresses",
"starting",
"from",
"the",
"last",
... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/loader.go#L58-L66 | train |
btcsuite/btcwallet | wallet/loader.go | onLoaded | func (l *Loader) onLoaded(w *Wallet, db walletdb.DB) {
for _, fn := range l.callbacks {
fn(w)
}
l.wallet = w
l.db = db
l.callbacks = nil // not needed anymore
} | go | func (l *Loader) onLoaded(w *Wallet, db walletdb.DB) {
for _, fn := range l.callbacks {
fn(w)
}
l.wallet = w
l.db = db
l.callbacks = nil // not needed anymore
} | [
"func",
"(",
"l",
"*",
"Loader",
")",
"onLoaded",
"(",
"w",
"*",
"Wallet",
",",
"db",
"walletdb",
".",
"DB",
")",
"{",
"for",
"_",
",",
"fn",
":=",
"range",
"l",
".",
"callbacks",
"{",
"fn",
"(",
"w",
")",
"\n",
"}",
"\n",
"l",
".",
"wallet",... | // onLoaded executes each added callback and prevents loader from loading any
// additional wallets. Requires mutex to be locked. | [
"onLoaded",
"executes",
"each",
"added",
"callback",
"and",
"prevents",
"loader",
"from",
"loading",
"any",
"additional",
"wallets",
".",
"Requires",
"mutex",
"to",
"be",
"locked",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/loader.go#L70-L78 | train |
btcsuite/btcwallet | wallet/loader.go | RunAfterLoad | func (l *Loader) RunAfterLoad(fn func(*Wallet)) {
l.mu.Lock()
if l.wallet != nil {
w := l.wallet
l.mu.Unlock()
fn(w)
} else {
l.callbacks = append(l.callbacks, fn)
l.mu.Unlock()
}
} | go | func (l *Loader) RunAfterLoad(fn func(*Wallet)) {
l.mu.Lock()
if l.wallet != nil {
w := l.wallet
l.mu.Unlock()
fn(w)
} else {
l.callbacks = append(l.callbacks, fn)
l.mu.Unlock()
}
} | [
"func",
"(",
"l",
"*",
"Loader",
")",
"RunAfterLoad",
"(",
"fn",
"func",
"(",
"*",
"Wallet",
")",
")",
"{",
"l",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"l",
".",
"wallet",
"!=",
"nil",
"{",
"w",
":=",
"l",
".",
"wallet",
"\n",
"l",
"... | // RunAfterLoad adds a function to be executed when the loader creates or opens
// a wallet. Functions are executed in a single goroutine in the order they are
// added. | [
"RunAfterLoad",
"adds",
"a",
"function",
"to",
"be",
"executed",
"when",
"the",
"loader",
"creates",
"or",
"opens",
"a",
"wallet",
".",
"Functions",
"are",
"executed",
"in",
"a",
"single",
"goroutine",
"in",
"the",
"order",
"they",
"are",
"added",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/loader.go#L83-L93 | train |
btcsuite/btcwallet | wallet/loader.go | CreateNewWallet | func (l *Loader) CreateNewWallet(pubPassphrase, privPassphrase, seed []byte,
bday time.Time) (*Wallet, error) {
defer l.mu.Unlock()
l.mu.Lock()
if l.wallet != nil {
return nil, ErrLoaded
}
dbPath := filepath.Join(l.dbDirPath, walletDbName)
exists, err := fileExists(dbPath)
if err != nil {
return nil, err
}
if exists {
return nil, ErrExists
}
// Create the wallet database backed by bolt db.
err = os.MkdirAll(l.dbDirPath, 0700)
if err != nil {
return nil, err
}
db, err := walletdb.Create("bdb", dbPath)
if err != nil {
return nil, err
}
// Initialize the newly created database for the wallet before opening.
err = Create(
db, pubPassphrase, privPassphrase, seed, l.chainParams, bday,
)
if err != nil {
return nil, err
}
// Open the newly-created wallet.
w, err := Open(db, pubPassphrase, nil, l.chainParams, l.recoveryWindow)
if err != nil {
return nil, err
}
w.Start()
l.onLoaded(w, db)
return w, nil
} | go | func (l *Loader) CreateNewWallet(pubPassphrase, privPassphrase, seed []byte,
bday time.Time) (*Wallet, error) {
defer l.mu.Unlock()
l.mu.Lock()
if l.wallet != nil {
return nil, ErrLoaded
}
dbPath := filepath.Join(l.dbDirPath, walletDbName)
exists, err := fileExists(dbPath)
if err != nil {
return nil, err
}
if exists {
return nil, ErrExists
}
// Create the wallet database backed by bolt db.
err = os.MkdirAll(l.dbDirPath, 0700)
if err != nil {
return nil, err
}
db, err := walletdb.Create("bdb", dbPath)
if err != nil {
return nil, err
}
// Initialize the newly created database for the wallet before opening.
err = Create(
db, pubPassphrase, privPassphrase, seed, l.chainParams, bday,
)
if err != nil {
return nil, err
}
// Open the newly-created wallet.
w, err := Open(db, pubPassphrase, nil, l.chainParams, l.recoveryWindow)
if err != nil {
return nil, err
}
w.Start()
l.onLoaded(w, db)
return w, nil
} | [
"func",
"(",
"l",
"*",
"Loader",
")",
"CreateNewWallet",
"(",
"pubPassphrase",
",",
"privPassphrase",
",",
"seed",
"[",
"]",
"byte",
",",
"bday",
"time",
".",
"Time",
")",
"(",
"*",
"Wallet",
",",
"error",
")",
"{",
"defer",
"l",
".",
"mu",
".",
"U... | // CreateNewWallet creates a new wallet using the provided public and private
// passphrases. The seed is optional. If non-nil, addresses are derived from
// this seed. If nil, a secure random seed is generated. | [
"CreateNewWallet",
"creates",
"a",
"new",
"wallet",
"using",
"the",
"provided",
"public",
"and",
"private",
"passphrases",
".",
"The",
"seed",
"is",
"optional",
".",
"If",
"non",
"-",
"nil",
"addresses",
"are",
"derived",
"from",
"this",
"seed",
".",
"If",
... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/loader.go#L98-L144 | train |
btcsuite/btcwallet | wallet/loader.go | OpenExistingWallet | func (l *Loader) OpenExistingWallet(pubPassphrase []byte, canConsolePrompt bool) (*Wallet, error) {
defer l.mu.Unlock()
l.mu.Lock()
if l.wallet != nil {
return nil, ErrLoaded
}
// Ensure that the network directory exists.
if err := checkCreateDir(l.dbDirPath); err != nil {
return nil, err
}
// Open the database using the boltdb backend.
dbPath := filepath.Join(l.dbDirPath, walletDbName)
db, err := walletdb.Open("bdb", dbPath)
if err != nil {
log.Errorf("Failed to open database: %v", err)
return nil, err
}
var cbs *waddrmgr.OpenCallbacks
if canConsolePrompt {
cbs = &waddrmgr.OpenCallbacks{
ObtainSeed: prompt.ProvideSeed,
ObtainPrivatePass: prompt.ProvidePrivPassphrase,
}
} else {
cbs = &waddrmgr.OpenCallbacks{
ObtainSeed: noConsole,
ObtainPrivatePass: noConsole,
}
}
w, err := Open(db, pubPassphrase, cbs, l.chainParams, l.recoveryWindow)
if err != nil {
// If opening the wallet fails (e.g. because of wrong
// passphrase), we must close the backing database to
// allow future calls to walletdb.Open().
e := db.Close()
if e != nil {
log.Warnf("Error closing database: %v", e)
}
return nil, err
}
w.Start()
l.onLoaded(w, db)
return w, nil
} | go | func (l *Loader) OpenExistingWallet(pubPassphrase []byte, canConsolePrompt bool) (*Wallet, error) {
defer l.mu.Unlock()
l.mu.Lock()
if l.wallet != nil {
return nil, ErrLoaded
}
// Ensure that the network directory exists.
if err := checkCreateDir(l.dbDirPath); err != nil {
return nil, err
}
// Open the database using the boltdb backend.
dbPath := filepath.Join(l.dbDirPath, walletDbName)
db, err := walletdb.Open("bdb", dbPath)
if err != nil {
log.Errorf("Failed to open database: %v", err)
return nil, err
}
var cbs *waddrmgr.OpenCallbacks
if canConsolePrompt {
cbs = &waddrmgr.OpenCallbacks{
ObtainSeed: prompt.ProvideSeed,
ObtainPrivatePass: prompt.ProvidePrivPassphrase,
}
} else {
cbs = &waddrmgr.OpenCallbacks{
ObtainSeed: noConsole,
ObtainPrivatePass: noConsole,
}
}
w, err := Open(db, pubPassphrase, cbs, l.chainParams, l.recoveryWindow)
if err != nil {
// If opening the wallet fails (e.g. because of wrong
// passphrase), we must close the backing database to
// allow future calls to walletdb.Open().
e := db.Close()
if e != nil {
log.Warnf("Error closing database: %v", e)
}
return nil, err
}
w.Start()
l.onLoaded(w, db)
return w, nil
} | [
"func",
"(",
"l",
"*",
"Loader",
")",
"OpenExistingWallet",
"(",
"pubPassphrase",
"[",
"]",
"byte",
",",
"canConsolePrompt",
"bool",
")",
"(",
"*",
"Wallet",
",",
"error",
")",
"{",
"defer",
"l",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"l",
".",
... | // OpenExistingWallet opens the wallet from the loader's wallet database path
// and the public passphrase. If the loader is being called by a context where
// standard input prompts may be used during wallet upgrades, setting
// canConsolePrompt will enables these prompts. | [
"OpenExistingWallet",
"opens",
"the",
"wallet",
"from",
"the",
"loader",
"s",
"wallet",
"database",
"path",
"and",
"the",
"public",
"passphrase",
".",
"If",
"the",
"loader",
"is",
"being",
"called",
"by",
"a",
"context",
"where",
"standard",
"input",
"prompts"... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/loader.go#L156-L204 | train |
btcsuite/btcwallet | wallet/loader.go | LoadedWallet | func (l *Loader) LoadedWallet() (*Wallet, bool) {
l.mu.Lock()
w := l.wallet
l.mu.Unlock()
return w, w != nil
} | go | func (l *Loader) LoadedWallet() (*Wallet, bool) {
l.mu.Lock()
w := l.wallet
l.mu.Unlock()
return w, w != nil
} | [
"func",
"(",
"l",
"*",
"Loader",
")",
"LoadedWallet",
"(",
")",
"(",
"*",
"Wallet",
",",
"bool",
")",
"{",
"l",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"w",
":=",
"l",
".",
"wallet",
"\n",
"l",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"ret... | // LoadedWallet returns the loaded wallet, if any, and a bool for whether the
// wallet has been loaded or not. If true, the wallet pointer should be safe to
// dereference. | [
"LoadedWallet",
"returns",
"the",
"loaded",
"wallet",
"if",
"any",
"and",
"a",
"bool",
"for",
"whether",
"the",
"wallet",
"has",
"been",
"loaded",
"or",
"not",
".",
"If",
"true",
"the",
"wallet",
"pointer",
"should",
"be",
"safe",
"to",
"dereference",
"."
... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/loader.go#L216-L221 | train |
btcsuite/btcwallet | wallet/loader.go | UnloadWallet | func (l *Loader) UnloadWallet() error {
defer l.mu.Unlock()
l.mu.Lock()
if l.wallet == nil {
return ErrNotLoaded
}
l.wallet.Stop()
l.wallet.WaitForShutdown()
err := l.db.Close()
if err != nil {
return err
}
l.wallet = nil
l.db = nil
return nil
} | go | func (l *Loader) UnloadWallet() error {
defer l.mu.Unlock()
l.mu.Lock()
if l.wallet == nil {
return ErrNotLoaded
}
l.wallet.Stop()
l.wallet.WaitForShutdown()
err := l.db.Close()
if err != nil {
return err
}
l.wallet = nil
l.db = nil
return nil
} | [
"func",
"(",
"l",
"*",
"Loader",
")",
"UnloadWallet",
"(",
")",
"error",
"{",
"defer",
"l",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"l",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"l",
".",
"wallet",
"==",
"nil",
"{",
"return",
"ErrNotLoad... | // UnloadWallet stops the loaded wallet, if any, and closes the wallet database.
// This returns ErrNotLoaded if the wallet has not been loaded with
// CreateNewWallet or LoadExistingWallet. The Loader may be reused if this
// function returns without error. | [
"UnloadWallet",
"stops",
"the",
"loaded",
"wallet",
"if",
"any",
"and",
"closes",
"the",
"wallet",
"database",
".",
"This",
"returns",
"ErrNotLoaded",
"if",
"the",
"wallet",
"has",
"not",
"been",
"loaded",
"with",
"CreateNewWallet",
"or",
"LoadExistingWallet",
"... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/loader.go#L227-L245 | train |
btcsuite/btcwallet | wallet/rescan.go | SubmitRescan | func (w *Wallet) SubmitRescan(job *RescanJob) <-chan error {
errChan := make(chan error, 1)
job.err = errChan
w.rescanAddJob <- job
return errChan
} | go | func (w *Wallet) SubmitRescan(job *RescanJob) <-chan error {
errChan := make(chan error, 1)
job.err = errChan
w.rescanAddJob <- job
return errChan
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"SubmitRescan",
"(",
"job",
"*",
"RescanJob",
")",
"<-",
"chan",
"error",
"{",
"errChan",
":=",
"make",
"(",
"chan",
"error",
",",
"1",
")",
"\n",
"job",
".",
"err",
"=",
"errChan",
"\n",
"w",
".",
"rescanAddJo... | // SubmitRescan submits a RescanJob to the RescanManager. A channel is
// returned with the final error of the rescan. The channel is buffered
// and does not need to be read to prevent a deadlock. | [
"SubmitRescan",
"submits",
"a",
"RescanJob",
"to",
"the",
"RescanManager",
".",
"A",
"channel",
"is",
"returned",
"with",
"the",
"final",
"error",
"of",
"the",
"rescan",
".",
"The",
"channel",
"is",
"buffered",
"and",
"does",
"not",
"need",
"to",
"be",
"re... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/rescan.go#L56-L61 | train |
btcsuite/btcwallet | wallet/rescan.go | batch | func (job *RescanJob) batch() *rescanBatch {
return &rescanBatch{
initialSync: job.InitialSync,
addrs: job.Addrs,
outpoints: job.OutPoints,
bs: job.BlockStamp,
errChans: []chan error{job.err},
}
} | go | func (job *RescanJob) batch() *rescanBatch {
return &rescanBatch{
initialSync: job.InitialSync,
addrs: job.Addrs,
outpoints: job.OutPoints,
bs: job.BlockStamp,
errChans: []chan error{job.err},
}
} | [
"func",
"(",
"job",
"*",
"RescanJob",
")",
"batch",
"(",
")",
"*",
"rescanBatch",
"{",
"return",
"&",
"rescanBatch",
"{",
"initialSync",
":",
"job",
".",
"InitialSync",
",",
"addrs",
":",
"job",
".",
"Addrs",
",",
"outpoints",
":",
"job",
".",
"OutPoin... | // batch creates the rescanBatch for a single rescan job. | [
"batch",
"creates",
"the",
"rescanBatch",
"for",
"a",
"single",
"rescan",
"job",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/rescan.go#L64-L72 | train |
btcsuite/btcwallet | wallet/rescan.go | merge | func (b *rescanBatch) merge(job *RescanJob) {
if job.InitialSync {
b.initialSync = true
}
b.addrs = append(b.addrs, job.Addrs...)
for op, addr := range job.OutPoints {
b.outpoints[op] = addr
}
if job.BlockStamp.Height < b.bs.Height {
b.bs = job.BlockStamp
}
b.errChans = append(b.errChans, job.err)
} | go | func (b *rescanBatch) merge(job *RescanJob) {
if job.InitialSync {
b.initialSync = true
}
b.addrs = append(b.addrs, job.Addrs...)
for op, addr := range job.OutPoints {
b.outpoints[op] = addr
}
if job.BlockStamp.Height < b.bs.Height {
b.bs = job.BlockStamp
}
b.errChans = append(b.errChans, job.err)
} | [
"func",
"(",
"b",
"*",
"rescanBatch",
")",
"merge",
"(",
"job",
"*",
"RescanJob",
")",
"{",
"if",
"job",
".",
"InitialSync",
"{",
"b",
".",
"initialSync",
"=",
"true",
"\n",
"}",
"\n",
"b",
".",
"addrs",
"=",
"append",
"(",
"b",
".",
"addrs",
","... | // merge merges the work from k into j, setting the starting height to
// the minimum of the two jobs. This method does not check for
// duplicate addresses or outpoints. | [
"merge",
"merges",
"the",
"work",
"from",
"k",
"into",
"j",
"setting",
"the",
"starting",
"height",
"to",
"the",
"minimum",
"of",
"the",
"two",
"jobs",
".",
"This",
"method",
"does",
"not",
"check",
"for",
"duplicate",
"addresses",
"or",
"outpoints",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/rescan.go#L77-L91 | train |
btcsuite/btcwallet | wallet/rescan.go | rescanBatchHandler | func (w *Wallet) rescanBatchHandler() {
var curBatch, nextBatch *rescanBatch
quit := w.quitChan()
out:
for {
select {
case job := <-w.rescanAddJob:
if curBatch == nil {
// Set current batch as this job and send
// request.
curBatch = job.batch()
w.rescanBatch <- curBatch
} else {
// Create next batch if it doesn't exist, or
// merge the job.
if nextBatch == nil {
nextBatch = job.batch()
} else {
nextBatch.merge(job)
}
}
case n := <-w.rescanNotifications:
switch n := n.(type) {
case *chain.RescanProgress:
if curBatch == nil {
log.Warnf("Received rescan progress " +
"notification but no rescan " +
"currently running")
continue
}
w.rescanProgress <- &RescanProgressMsg{
Addresses: curBatch.addrs,
Notification: n,
}
case *chain.RescanFinished:
if curBatch == nil {
log.Warnf("Received rescan finished " +
"notification but no rescan " +
"currently running")
continue
}
w.rescanFinished <- &RescanFinishedMsg{
Addresses: curBatch.addrs,
Notification: n,
}
curBatch, nextBatch = nextBatch, nil
if curBatch != nil {
w.rescanBatch <- curBatch
}
default:
// Unexpected message
panic(n)
}
case <-quit:
break out
}
}
w.wg.Done()
} | go | func (w *Wallet) rescanBatchHandler() {
var curBatch, nextBatch *rescanBatch
quit := w.quitChan()
out:
for {
select {
case job := <-w.rescanAddJob:
if curBatch == nil {
// Set current batch as this job and send
// request.
curBatch = job.batch()
w.rescanBatch <- curBatch
} else {
// Create next batch if it doesn't exist, or
// merge the job.
if nextBatch == nil {
nextBatch = job.batch()
} else {
nextBatch.merge(job)
}
}
case n := <-w.rescanNotifications:
switch n := n.(type) {
case *chain.RescanProgress:
if curBatch == nil {
log.Warnf("Received rescan progress " +
"notification but no rescan " +
"currently running")
continue
}
w.rescanProgress <- &RescanProgressMsg{
Addresses: curBatch.addrs,
Notification: n,
}
case *chain.RescanFinished:
if curBatch == nil {
log.Warnf("Received rescan finished " +
"notification but no rescan " +
"currently running")
continue
}
w.rescanFinished <- &RescanFinishedMsg{
Addresses: curBatch.addrs,
Notification: n,
}
curBatch, nextBatch = nextBatch, nil
if curBatch != nil {
w.rescanBatch <- curBatch
}
default:
// Unexpected message
panic(n)
}
case <-quit:
break out
}
}
w.wg.Done()
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"rescanBatchHandler",
"(",
")",
"{",
"var",
"curBatch",
",",
"nextBatch",
"*",
"rescanBatch",
"\n",
"quit",
":=",
"w",
".",
"quitChan",
"(",
")",
"\n",
"out",
":",
"for",
"{",
"select",
"{",
"case",
"job",
":=",
... | // rescanBatchHandler handles incoming rescan request, serializing rescan
// submissions, and possibly batching many waiting requests together so they
// can be handled by a single rescan after the current one completes. | [
"rescanBatchHandler",
"handles",
"incoming",
"rescan",
"request",
"serializing",
"rescan",
"submissions",
"and",
"possibly",
"batching",
"many",
"waiting",
"requests",
"together",
"so",
"they",
"can",
"be",
"handled",
"by",
"a",
"single",
"rescan",
"after",
"the",
... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/rescan.go#L105-L171 | train |
btcsuite/btcwallet | wallet/rescan.go | rescanProgressHandler | func (w *Wallet) rescanProgressHandler() {
quit := w.quitChan()
out:
for {
// These can't be processed out of order since both chans are
// unbuffured and are sent from same context (the batch
// handler).
select {
case msg := <-w.rescanProgress:
n := msg.Notification
log.Infof("Rescanned through block %v (height %d)",
n.Hash, n.Height)
case msg := <-w.rescanFinished:
n := msg.Notification
addrs := msg.Addresses
noun := pickNoun(len(addrs), "address", "addresses")
log.Infof("Finished rescan for %d %s (synced to block "+
"%s, height %d)", len(addrs), noun, n.Hash,
n.Height)
go w.resendUnminedTxs()
case <-quit:
break out
}
}
w.wg.Done()
} | go | func (w *Wallet) rescanProgressHandler() {
quit := w.quitChan()
out:
for {
// These can't be processed out of order since both chans are
// unbuffured and are sent from same context (the batch
// handler).
select {
case msg := <-w.rescanProgress:
n := msg.Notification
log.Infof("Rescanned through block %v (height %d)",
n.Hash, n.Height)
case msg := <-w.rescanFinished:
n := msg.Notification
addrs := msg.Addresses
noun := pickNoun(len(addrs), "address", "addresses")
log.Infof("Finished rescan for %d %s (synced to block "+
"%s, height %d)", len(addrs), noun, n.Hash,
n.Height)
go w.resendUnminedTxs()
case <-quit:
break out
}
}
w.wg.Done()
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"rescanProgressHandler",
"(",
")",
"{",
"quit",
":=",
"w",
".",
"quitChan",
"(",
")",
"\n",
"out",
":",
"for",
"{",
"select",
"{",
"case",
"msg",
":=",
"<-",
"w",
".",
"rescanProgress",
":",
"n",
":=",
"msg",
... | // rescanProgressHandler handles notifications for partially and fully completed
// rescans by marking each rescanned address as partially or fully synced. | [
"rescanProgressHandler",
"handles",
"notifications",
"for",
"partially",
"and",
"fully",
"completed",
"rescans",
"by",
"marking",
"each",
"rescanned",
"address",
"as",
"partially",
"or",
"fully",
"synced",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/rescan.go#L175-L203 | train |
btcsuite/btcwallet | wallet/rescan.go | rescanRPCHandler | func (w *Wallet) rescanRPCHandler() {
chainClient, err := w.requireChainClient()
if err != nil {
log.Errorf("rescanRPCHandler called without an RPC client")
w.wg.Done()
return
}
quit := w.quitChan()
out:
for {
select {
case batch := <-w.rescanBatch:
// Log the newly-started rescan.
numAddrs := len(batch.addrs)
noun := pickNoun(numAddrs, "address", "addresses")
log.Infof("Started rescan from block %v (height %d) for %d %s",
batch.bs.Hash, batch.bs.Height, numAddrs, noun)
err := chainClient.Rescan(&batch.bs.Hash, batch.addrs,
batch.outpoints)
if err != nil {
log.Errorf("Rescan for %d %s failed: %v", numAddrs,
noun, err)
}
batch.done(err)
case <-quit:
break out
}
}
w.wg.Done()
} | go | func (w *Wallet) rescanRPCHandler() {
chainClient, err := w.requireChainClient()
if err != nil {
log.Errorf("rescanRPCHandler called without an RPC client")
w.wg.Done()
return
}
quit := w.quitChan()
out:
for {
select {
case batch := <-w.rescanBatch:
// Log the newly-started rescan.
numAddrs := len(batch.addrs)
noun := pickNoun(numAddrs, "address", "addresses")
log.Infof("Started rescan from block %v (height %d) for %d %s",
batch.bs.Hash, batch.bs.Height, numAddrs, noun)
err := chainClient.Rescan(&batch.bs.Hash, batch.addrs,
batch.outpoints)
if err != nil {
log.Errorf("Rescan for %d %s failed: %v", numAddrs,
noun, err)
}
batch.done(err)
case <-quit:
break out
}
}
w.wg.Done()
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"rescanRPCHandler",
"(",
")",
"{",
"chainClient",
",",
"err",
":=",
"w",
".",
"requireChainClient",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"rescanRPCHandler called without an RPC clie... | // rescanRPCHandler reads batch jobs sent by rescanBatchHandler and sends the
// RPC requests to perform a rescan. New jobs are not read until a rescan
// finishes. | [
"rescanRPCHandler",
"reads",
"batch",
"jobs",
"sent",
"by",
"rescanBatchHandler",
"and",
"sends",
"the",
"RPC",
"requests",
"to",
"perform",
"a",
"rescan",
".",
"New",
"jobs",
"are",
"not",
"read",
"until",
"a",
"rescan",
"finishes",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/rescan.go#L208-L241 | train |
btcsuite/btcwallet | wallet/rescan.go | Rescan | func (w *Wallet) Rescan(addrs []btcutil.Address, unspent []wtxmgr.Credit) error {
return w.rescanWithTarget(addrs, unspent, nil)
} | go | func (w *Wallet) Rescan(addrs []btcutil.Address, unspent []wtxmgr.Credit) error {
return w.rescanWithTarget(addrs, unspent, nil)
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"Rescan",
"(",
"addrs",
"[",
"]",
"btcutil",
".",
"Address",
",",
"unspent",
"[",
"]",
"wtxmgr",
".",
"Credit",
")",
"error",
"{",
"return",
"w",
".",
"rescanWithTarget",
"(",
"addrs",
",",
"unspent",
",",
"nil",... | // Rescan begins a rescan for all active addresses and unspent outputs of
// a wallet. This is intended to be used to sync a wallet back up to the
// current best block in the main chain, and is considered an initial sync
// rescan. | [
"Rescan",
"begins",
"a",
"rescan",
"for",
"all",
"active",
"addresses",
"and",
"unspent",
"outputs",
"of",
"a",
"wallet",
".",
"This",
"is",
"intended",
"to",
"be",
"used",
"to",
"sync",
"a",
"wallet",
"back",
"up",
"to",
"the",
"current",
"best",
"block... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/rescan.go#L247-L249 | train |
btcsuite/btcwallet | wallet/rescan.go | rescanWithTarget | func (w *Wallet) rescanWithTarget(addrs []btcutil.Address,
unspent []wtxmgr.Credit, startStamp *waddrmgr.BlockStamp) error {
outpoints := make(map[wire.OutPoint]btcutil.Address, len(unspent))
for _, output := range unspent {
_, outputAddrs, _, err := txscript.ExtractPkScriptAddrs(
output.PkScript, w.chainParams,
)
if err != nil {
return err
}
outpoints[output.OutPoint] = outputAddrs[0]
}
// If a start block stamp was provided, we will use that as the initial
// starting point for the rescan.
if startStamp == nil {
startStamp = &waddrmgr.BlockStamp{}
*startStamp = w.Manager.SyncedTo()
}
job := &RescanJob{
InitialSync: true,
Addrs: addrs,
OutPoints: outpoints,
BlockStamp: *startStamp,
}
// Submit merged job and block until rescan completes.
return <-w.SubmitRescan(job)
} | go | func (w *Wallet) rescanWithTarget(addrs []btcutil.Address,
unspent []wtxmgr.Credit, startStamp *waddrmgr.BlockStamp) error {
outpoints := make(map[wire.OutPoint]btcutil.Address, len(unspent))
for _, output := range unspent {
_, outputAddrs, _, err := txscript.ExtractPkScriptAddrs(
output.PkScript, w.chainParams,
)
if err != nil {
return err
}
outpoints[output.OutPoint] = outputAddrs[0]
}
// If a start block stamp was provided, we will use that as the initial
// starting point for the rescan.
if startStamp == nil {
startStamp = &waddrmgr.BlockStamp{}
*startStamp = w.Manager.SyncedTo()
}
job := &RescanJob{
InitialSync: true,
Addrs: addrs,
OutPoints: outpoints,
BlockStamp: *startStamp,
}
// Submit merged job and block until rescan completes.
return <-w.SubmitRescan(job)
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"rescanWithTarget",
"(",
"addrs",
"[",
"]",
"btcutil",
".",
"Address",
",",
"unspent",
"[",
"]",
"wtxmgr",
".",
"Credit",
",",
"startStamp",
"*",
"waddrmgr",
".",
"BlockStamp",
")",
"error",
"{",
"outpoints",
":=",
... | // rescanWithTarget performs a rescan starting at the optional startStamp. If
// none is provided, the rescan will begin from the manager's sync tip. | [
"rescanWithTarget",
"performs",
"a",
"rescan",
"starting",
"at",
"the",
"optional",
"startStamp",
".",
"If",
"none",
"is",
"provided",
"the",
"rescan",
"will",
"begin",
"from",
"the",
"manager",
"s",
"sync",
"tip",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/rescan.go#L253-L284 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | unimplemented | func unimplemented(interface{}, *wallet.Wallet) (interface{}, error) {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCUnimplemented,
Message: "Method unimplemented",
}
} | go | func unimplemented(interface{}, *wallet.Wallet) (interface{}, error) {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCUnimplemented,
Message: "Method unimplemented",
}
} | [
"func",
"unimplemented",
"(",
"interface",
"{",
"}",
",",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"nil",
",",
"&",
"btcjson",
".",
"RPCError",
"{",
"Code",
":",
"btcjson",
".",
"ErrRPCUnimplement... | // unimplemented handles an unimplemented RPC request with the
// appropiate error. | [
"unimplemented",
"handles",
"an",
"unimplemented",
"RPC",
"request",
"with",
"the",
"appropiate",
"error",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L143-L148 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | makeResponse | func makeResponse(id, result interface{}, err error) btcjson.Response {
idPtr := idPointer(id)
if err != nil {
return btcjson.Response{
ID: idPtr,
Error: jsonError(err),
}
}
resultBytes, err := json.Marshal(result)
if err != nil {
return btcjson.Response{
ID: idPtr,
Error: &btcjson.RPCError{
Code: btcjson.ErrRPCInternal.Code,
Message: "Unexpected error marshalling result",
},
}
}
return btcjson.Response{
ID: idPtr,
Result: json.RawMessage(resultBytes),
}
} | go | func makeResponse(id, result interface{}, err error) btcjson.Response {
idPtr := idPointer(id)
if err != nil {
return btcjson.Response{
ID: idPtr,
Error: jsonError(err),
}
}
resultBytes, err := json.Marshal(result)
if err != nil {
return btcjson.Response{
ID: idPtr,
Error: &btcjson.RPCError{
Code: btcjson.ErrRPCInternal.Code,
Message: "Unexpected error marshalling result",
},
}
}
return btcjson.Response{
ID: idPtr,
Result: json.RawMessage(resultBytes),
}
} | [
"func",
"makeResponse",
"(",
"id",
",",
"result",
"interface",
"{",
"}",
",",
"err",
"error",
")",
"btcjson",
".",
"Response",
"{",
"idPtr",
":=",
"idPointer",
"(",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"btcjson",
".",
"Response",
... | // makeResponse makes the JSON-RPC response struct for the result and error
// returned by a requestHandler. The returned response is not ready for
// marshaling and sending off to a client, but must be | [
"makeResponse",
"makes",
"the",
"JSON",
"-",
"RPC",
"response",
"struct",
"for",
"the",
"result",
"and",
"error",
"returned",
"by",
"a",
"requestHandler",
".",
"The",
"returned",
"response",
"is",
"not",
"ready",
"for",
"marshaling",
"and",
"sending",
"off",
... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L234-L256 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | jsonError | func jsonError(err error) *btcjson.RPCError {
if err == nil {
return nil
}
code := btcjson.ErrRPCWallet
switch e := err.(type) {
case btcjson.RPCError:
return &e
case *btcjson.RPCError:
return e
case DeserializationError:
code = btcjson.ErrRPCDeserialization
case InvalidParameterError:
code = btcjson.ErrRPCInvalidParameter
case ParseError:
code = btcjson.ErrRPCParse.Code
case waddrmgr.ManagerError:
switch e.ErrorCode {
case waddrmgr.ErrWrongPassphrase:
code = btcjson.ErrRPCWalletPassphraseIncorrect
}
}
return &btcjson.RPCError{
Code: code,
Message: err.Error(),
}
} | go | func jsonError(err error) *btcjson.RPCError {
if err == nil {
return nil
}
code := btcjson.ErrRPCWallet
switch e := err.(type) {
case btcjson.RPCError:
return &e
case *btcjson.RPCError:
return e
case DeserializationError:
code = btcjson.ErrRPCDeserialization
case InvalidParameterError:
code = btcjson.ErrRPCInvalidParameter
case ParseError:
code = btcjson.ErrRPCParse.Code
case waddrmgr.ManagerError:
switch e.ErrorCode {
case waddrmgr.ErrWrongPassphrase:
code = btcjson.ErrRPCWalletPassphraseIncorrect
}
}
return &btcjson.RPCError{
Code: code,
Message: err.Error(),
}
} | [
"func",
"jsonError",
"(",
"err",
"error",
")",
"*",
"btcjson",
".",
"RPCError",
"{",
"if",
"err",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"code",
":=",
"btcjson",
".",
"ErrRPCWallet",
"\n",
"switch",
"e",
":=",
"err",
".",
"(",
"type",
... | // jsonError creates a JSON-RPC error from the Go error. | [
"jsonError",
"creates",
"a",
"JSON",
"-",
"RPC",
"error",
"from",
"the",
"Go",
"error",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L259-L286 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | makeMultiSigScript | func makeMultiSigScript(w *wallet.Wallet, keys []string, nRequired int) ([]byte, error) {
keysesPrecious := make([]*btcutil.AddressPubKey, len(keys))
// The address list will made up either of addreseses (pubkey hash), for
// which we need to look up the keys in wallet, straight pubkeys, or a
// mixture of the two.
for i, a := range keys {
// try to parse as pubkey address
a, err := decodeAddress(a, w.ChainParams())
if err != nil {
return nil, err
}
switch addr := a.(type) {
case *btcutil.AddressPubKey:
keysesPrecious[i] = addr
default:
pubKey, err := w.PubKeyForAddress(addr)
if err != nil {
return nil, err
}
pubKeyAddr, err := btcutil.NewAddressPubKey(
pubKey.SerializeCompressed(), w.ChainParams())
if err != nil {
return nil, err
}
keysesPrecious[i] = pubKeyAddr
}
}
return txscript.MultiSigScript(keysesPrecious, nRequired)
} | go | func makeMultiSigScript(w *wallet.Wallet, keys []string, nRequired int) ([]byte, error) {
keysesPrecious := make([]*btcutil.AddressPubKey, len(keys))
// The address list will made up either of addreseses (pubkey hash), for
// which we need to look up the keys in wallet, straight pubkeys, or a
// mixture of the two.
for i, a := range keys {
// try to parse as pubkey address
a, err := decodeAddress(a, w.ChainParams())
if err != nil {
return nil, err
}
switch addr := a.(type) {
case *btcutil.AddressPubKey:
keysesPrecious[i] = addr
default:
pubKey, err := w.PubKeyForAddress(addr)
if err != nil {
return nil, err
}
pubKeyAddr, err := btcutil.NewAddressPubKey(
pubKey.SerializeCompressed(), w.ChainParams())
if err != nil {
return nil, err
}
keysesPrecious[i] = pubKeyAddr
}
}
return txscript.MultiSigScript(keysesPrecious, nRequired)
} | [
"func",
"makeMultiSigScript",
"(",
"w",
"*",
"wallet",
".",
"Wallet",
",",
"keys",
"[",
"]",
"string",
",",
"nRequired",
"int",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"keysesPrecious",
":=",
"make",
"(",
"[",
"]",
"*",
"btcutil",
".",
... | // makeMultiSigScript is a helper function to combine common logic for
// AddMultiSig and CreateMultiSig. | [
"makeMultiSigScript",
"is",
"a",
"helper",
"function",
"to",
"combine",
"common",
"logic",
"for",
"AddMultiSig",
"and",
"CreateMultiSig",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L290-L321 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | addMultiSigAddress | func addMultiSigAddress(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.AddMultisigAddressCmd)
// If an account is specified, ensure that is the imported account.
if cmd.Account != nil && *cmd.Account != waddrmgr.ImportedAddrAccountName {
return nil, &ErrNotImportedAccount
}
secp256k1Addrs := make([]btcutil.Address, len(cmd.Keys))
for i, k := range cmd.Keys {
addr, err := decodeAddress(k, w.ChainParams())
if err != nil {
return nil, ParseError{err}
}
secp256k1Addrs[i] = addr
}
script, err := w.MakeMultiSigScript(secp256k1Addrs, cmd.NRequired)
if err != nil {
return nil, err
}
p2shAddr, err := w.ImportP2SHRedeemScript(script)
if err != nil {
return nil, err
}
return p2shAddr.EncodeAddress(), nil
} | go | func addMultiSigAddress(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.AddMultisigAddressCmd)
// If an account is specified, ensure that is the imported account.
if cmd.Account != nil && *cmd.Account != waddrmgr.ImportedAddrAccountName {
return nil, &ErrNotImportedAccount
}
secp256k1Addrs := make([]btcutil.Address, len(cmd.Keys))
for i, k := range cmd.Keys {
addr, err := decodeAddress(k, w.ChainParams())
if err != nil {
return nil, ParseError{err}
}
secp256k1Addrs[i] = addr
}
script, err := w.MakeMultiSigScript(secp256k1Addrs, cmd.NRequired)
if err != nil {
return nil, err
}
p2shAddr, err := w.ImportP2SHRedeemScript(script)
if err != nil {
return nil, err
}
return p2shAddr.EncodeAddress(), nil
} | [
"func",
"addMultiSigAddress",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"btcjson",
".",
"AddMultisigAddressCmd",
")",
"\n",
... | // addMultiSigAddress handles an addmultisigaddress request by adding a
// multisig address to the given wallet. | [
"addMultiSigAddress",
"handles",
"an",
"addmultisigaddress",
"request",
"by",
"adding",
"a",
"multisig",
"address",
"to",
"the",
"given",
"wallet",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L325-L353 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | createMultiSig | func createMultiSig(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.CreateMultisigCmd)
script, err := makeMultiSigScript(w, cmd.Keys, cmd.NRequired)
if err != nil {
return nil, ParseError{err}
}
address, err := btcutil.NewAddressScriptHash(script, w.ChainParams())
if err != nil {
// above is a valid script, shouldn't happen.
return nil, err
}
return btcjson.CreateMultiSigResult{
Address: address.EncodeAddress(),
RedeemScript: hex.EncodeToString(script),
}, nil
} | go | func createMultiSig(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.CreateMultisigCmd)
script, err := makeMultiSigScript(w, cmd.Keys, cmd.NRequired)
if err != nil {
return nil, ParseError{err}
}
address, err := btcutil.NewAddressScriptHash(script, w.ChainParams())
if err != nil {
// above is a valid script, shouldn't happen.
return nil, err
}
return btcjson.CreateMultiSigResult{
Address: address.EncodeAddress(),
RedeemScript: hex.EncodeToString(script),
}, nil
} | [
"func",
"createMultiSig",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"btcjson",
".",
"CreateMultisigCmd",
")",
"\n",
"script... | // createMultiSig handles an createmultisig request by returning a
// multisig address for the given inputs. | [
"createMultiSig",
"handles",
"an",
"createmultisig",
"request",
"by",
"returning",
"a",
"multisig",
"address",
"for",
"the",
"given",
"inputs",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L357-L375 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | dumpPrivKey | func dumpPrivKey(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.DumpPrivKeyCmd)
addr, err := decodeAddress(cmd.Address, w.ChainParams())
if err != nil {
return nil, err
}
key, err := w.DumpWIFPrivateKey(addr)
if waddrmgr.IsError(err, waddrmgr.ErrLocked) {
// Address was found, but the private key isn't
// accessible.
return nil, &ErrWalletUnlockNeeded
}
return key, err
} | go | func dumpPrivKey(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.DumpPrivKeyCmd)
addr, err := decodeAddress(cmd.Address, w.ChainParams())
if err != nil {
return nil, err
}
key, err := w.DumpWIFPrivateKey(addr)
if waddrmgr.IsError(err, waddrmgr.ErrLocked) {
// Address was found, but the private key isn't
// accessible.
return nil, &ErrWalletUnlockNeeded
}
return key, err
} | [
"func",
"dumpPrivKey",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"btcjson",
".",
"DumpPrivKeyCmd",
")",
"\n",
"addr",
","... | // dumpPrivKey handles a dumpprivkey request with the private key
// for a single address, or an appropiate error if the wallet
// is locked. | [
"dumpPrivKey",
"handles",
"a",
"dumpprivkey",
"request",
"with",
"the",
"private",
"key",
"for",
"a",
"single",
"address",
"or",
"an",
"appropiate",
"error",
"if",
"the",
"wallet",
"is",
"locked",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L380-L395 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | getAddressesByAccount | func getAddressesByAccount(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.GetAddressesByAccountCmd)
account, err := w.AccountNumber(waddrmgr.KeyScopeBIP0044, cmd.Account)
if err != nil {
return nil, err
}
addrs, err := w.AccountAddresses(account)
if err != nil {
return nil, err
}
addrStrs := make([]string, len(addrs))
for i, a := range addrs {
addrStrs[i] = a.EncodeAddress()
}
return addrStrs, nil
} | go | func getAddressesByAccount(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.GetAddressesByAccountCmd)
account, err := w.AccountNumber(waddrmgr.KeyScopeBIP0044, cmd.Account)
if err != nil {
return nil, err
}
addrs, err := w.AccountAddresses(account)
if err != nil {
return nil, err
}
addrStrs := make([]string, len(addrs))
for i, a := range addrs {
addrStrs[i] = a.EncodeAddress()
}
return addrStrs, nil
} | [
"func",
"getAddressesByAccount",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"btcjson",
".",
"GetAddressesByAccountCmd",
")",
"... | // getAddressesByAccount handles a getaddressesbyaccount request by returning
// all addresses for an account, or an error if the requested account does
// not exist. | [
"getAddressesByAccount",
"handles",
"a",
"getaddressesbyaccount",
"request",
"by",
"returning",
"all",
"addresses",
"for",
"an",
"account",
"or",
"an",
"error",
"if",
"the",
"requested",
"account",
"does",
"not",
"exist",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L412-L430 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | getBestBlock | func getBestBlock(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
blk := w.Manager.SyncedTo()
result := &btcjson.GetBestBlockResult{
Hash: blk.Hash.String(),
Height: blk.Height,
}
return result, nil
} | go | func getBestBlock(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
blk := w.Manager.SyncedTo()
result := &btcjson.GetBestBlockResult{
Hash: blk.Hash.String(),
Height: blk.Height,
}
return result, nil
} | [
"func",
"getBestBlock",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"blk",
":=",
"w",
".",
"Manager",
".",
"SyncedTo",
"(",
")",
"\n",
"result",
":=",
"&",
"... | // getBestBlock handles a getbestblock request by returning a JSON object
// with the height and hash of the most recently processed block. | [
"getBestBlock",
"handles",
"a",
"getbestblock",
"request",
"by",
"returning",
"a",
"JSON",
"object",
"with",
"the",
"height",
"and",
"hash",
"of",
"the",
"most",
"recently",
"processed",
"block",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L466-L473 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | getBestBlockHash | func getBestBlockHash(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
blk := w.Manager.SyncedTo()
return blk.Hash.String(), nil
} | go | func getBestBlockHash(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
blk := w.Manager.SyncedTo()
return blk.Hash.String(), nil
} | [
"func",
"getBestBlockHash",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"blk",
":=",
"w",
".",
"Manager",
".",
"SyncedTo",
"(",
")",
"\n",
"return",
"blk",
"."... | // getBestBlockHash handles a getbestblockhash request by returning the hash
// of the most recently processed block. | [
"getBestBlockHash",
"handles",
"a",
"getbestblockhash",
"request",
"by",
"returning",
"the",
"hash",
"of",
"the",
"most",
"recently",
"processed",
"block",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L477-L480 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | getBlockCount | func getBlockCount(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
blk := w.Manager.SyncedTo()
return blk.Height, nil
} | go | func getBlockCount(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
blk := w.Manager.SyncedTo()
return blk.Height, nil
} | [
"func",
"getBlockCount",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"blk",
":=",
"w",
".",
"Manager",
".",
"SyncedTo",
"(",
")",
"\n",
"return",
"blk",
".",
... | // getBlockCount handles a getblockcount request by returning the chain height
// of the most recently processed block. | [
"getBlockCount",
"handles",
"a",
"getblockcount",
"request",
"by",
"returning",
"the",
"chain",
"height",
"of",
"the",
"most",
"recently",
"processed",
"block",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L484-L487 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | getInfo | func getInfo(icmd interface{}, w *wallet.Wallet, chainClient *chain.RPCClient) (interface{}, error) {
// Call down to btcd for all of the information in this command known
// by them.
info, err := chainClient.GetInfo()
if err != nil {
return nil, err
}
bal, err := w.CalculateBalance(1)
if err != nil {
return nil, err
}
// TODO(davec): This should probably have a database version as opposed
// to using the manager version.
info.WalletVersion = int32(waddrmgr.LatestMgrVersion)
info.Balance = bal.ToBTC()
info.PaytxFee = float64(txrules.DefaultRelayFeePerKb)
// We don't set the following since they don't make much sense in the
// wallet architecture:
// - unlocked_until
// - errors
return info, nil
} | go | func getInfo(icmd interface{}, w *wallet.Wallet, chainClient *chain.RPCClient) (interface{}, error) {
// Call down to btcd for all of the information in this command known
// by them.
info, err := chainClient.GetInfo()
if err != nil {
return nil, err
}
bal, err := w.CalculateBalance(1)
if err != nil {
return nil, err
}
// TODO(davec): This should probably have a database version as opposed
// to using the manager version.
info.WalletVersion = int32(waddrmgr.LatestMgrVersion)
info.Balance = bal.ToBTC()
info.PaytxFee = float64(txrules.DefaultRelayFeePerKb)
// We don't set the following since they don't make much sense in the
// wallet architecture:
// - unlocked_until
// - errors
return info, nil
} | [
"func",
"getInfo",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
",",
"chainClient",
"*",
"chain",
".",
"RPCClient",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"info",
",",
"err",
":=",
"chainClient",
".",
... | // getInfo handles a getinfo request by returning the a structure containing
// information about the current state of btcwallet.
// exist. | [
"getInfo",
"handles",
"a",
"getinfo",
"request",
"by",
"returning",
"the",
"a",
"structure",
"containing",
"information",
"about",
"the",
"current",
"state",
"of",
"btcwallet",
".",
"exist",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L492-L516 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | getAccount | func getAccount(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.GetAccountCmd)
addr, err := decodeAddress(cmd.Address, w.ChainParams())
if err != nil {
return nil, err
}
// Fetch the associated account
account, err := w.AccountOfAddress(addr)
if err != nil {
return nil, &ErrAddressNotInWallet
}
acctName, err := w.AccountName(waddrmgr.KeyScopeBIP0044, account)
if err != nil {
return nil, &ErrAccountNameNotFound
}
return acctName, nil
} | go | func getAccount(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.GetAccountCmd)
addr, err := decodeAddress(cmd.Address, w.ChainParams())
if err != nil {
return nil, err
}
// Fetch the associated account
account, err := w.AccountOfAddress(addr)
if err != nil {
return nil, &ErrAddressNotInWallet
}
acctName, err := w.AccountName(waddrmgr.KeyScopeBIP0044, account)
if err != nil {
return nil, &ErrAccountNameNotFound
}
return acctName, nil
} | [
"func",
"getAccount",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"btcjson",
".",
"GetAccountCmd",
")",
"\n",
"addr",
",",
... | // getAccount handles a getaccount request by returning the account name
// associated with a single address. | [
"getAccount",
"handles",
"a",
"getaccount",
"request",
"by",
"returning",
"the",
"account",
"name",
"associated",
"with",
"a",
"single",
"address",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L540-L559 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | getUnconfirmedBalance | func getUnconfirmedBalance(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.GetUnconfirmedBalanceCmd)
acctName := "default"
if cmd.Account != nil {
acctName = *cmd.Account
}
account, err := w.AccountNumber(waddrmgr.KeyScopeBIP0044, acctName)
if err != nil {
return nil, err
}
bals, err := w.CalculateAccountBalances(account, 1)
if err != nil {
return nil, err
}
return (bals.Total - bals.Spendable).ToBTC(), nil
} | go | func getUnconfirmedBalance(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.GetUnconfirmedBalanceCmd)
acctName := "default"
if cmd.Account != nil {
acctName = *cmd.Account
}
account, err := w.AccountNumber(waddrmgr.KeyScopeBIP0044, acctName)
if err != nil {
return nil, err
}
bals, err := w.CalculateAccountBalances(account, 1)
if err != nil {
return nil, err
}
return (bals.Total - bals.Spendable).ToBTC(), nil
} | [
"func",
"getUnconfirmedBalance",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"btcjson",
".",
"GetUnconfirmedBalanceCmd",
")",
"... | // getUnconfirmedBalance handles a getunconfirmedbalance extension request
// by returning the current unconfirmed balance of an account. | [
"getUnconfirmedBalance",
"handles",
"a",
"getunconfirmedbalance",
"extension",
"request",
"by",
"returning",
"the",
"current",
"unconfirmed",
"balance",
"of",
"an",
"account",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L584-L601 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | importPrivKey | func importPrivKey(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.ImportPrivKeyCmd)
// Ensure that private keys are only imported to the correct account.
//
// Yes, Label is the account name.
if cmd.Label != nil && *cmd.Label != waddrmgr.ImportedAddrAccountName {
return nil, &ErrNotImportedAccount
}
wif, err := btcutil.DecodeWIF(cmd.PrivKey)
if err != nil {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidAddressOrKey,
Message: "WIF decode failed: " + err.Error(),
}
}
if !wif.IsForNet(w.ChainParams()) {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidAddressOrKey,
Message: "Key is not intended for " + w.ChainParams().Name,
}
}
// Import the private key, handling any errors.
_, err = w.ImportPrivateKey(waddrmgr.KeyScopeBIP0044, wif, nil, *cmd.Rescan)
switch {
case waddrmgr.IsError(err, waddrmgr.ErrDuplicateAddress):
// Do not return duplicate key errors to the client.
return nil, nil
case waddrmgr.IsError(err, waddrmgr.ErrLocked):
return nil, &ErrWalletUnlockNeeded
}
return nil, err
} | go | func importPrivKey(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.ImportPrivKeyCmd)
// Ensure that private keys are only imported to the correct account.
//
// Yes, Label is the account name.
if cmd.Label != nil && *cmd.Label != waddrmgr.ImportedAddrAccountName {
return nil, &ErrNotImportedAccount
}
wif, err := btcutil.DecodeWIF(cmd.PrivKey)
if err != nil {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidAddressOrKey,
Message: "WIF decode failed: " + err.Error(),
}
}
if !wif.IsForNet(w.ChainParams()) {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidAddressOrKey,
Message: "Key is not intended for " + w.ChainParams().Name,
}
}
// Import the private key, handling any errors.
_, err = w.ImportPrivateKey(waddrmgr.KeyScopeBIP0044, wif, nil, *cmd.Rescan)
switch {
case waddrmgr.IsError(err, waddrmgr.ErrDuplicateAddress):
// Do not return duplicate key errors to the client.
return nil, nil
case waddrmgr.IsError(err, waddrmgr.ErrLocked):
return nil, &ErrWalletUnlockNeeded
}
return nil, err
} | [
"func",
"importPrivKey",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"btcjson",
".",
"ImportPrivKeyCmd",
")",
"\n",
"if",
"... | // importPrivKey handles an importprivkey request by parsing
// a WIF-encoded private key and adding it to an account. | [
"importPrivKey",
"handles",
"an",
"importprivkey",
"request",
"by",
"parsing",
"a",
"WIF",
"-",
"encoded",
"private",
"key",
"and",
"adding",
"it",
"to",
"an",
"account",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L605-L640 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | createNewAccount | func createNewAccount(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.CreateNewAccountCmd)
// The wildcard * is reserved by the rpc server with the special meaning
// of "all accounts", so disallow naming accounts to this string.
if cmd.Account == "*" {
return nil, &ErrReservedAccountName
}
_, err := w.NextAccount(waddrmgr.KeyScopeBIP0044, cmd.Account)
if waddrmgr.IsError(err, waddrmgr.ErrLocked) {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCWalletUnlockNeeded,
Message: "Creating an account requires the wallet to be unlocked. " +
"Enter the wallet passphrase with walletpassphrase to unlock",
}
}
return nil, err
} | go | func createNewAccount(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.CreateNewAccountCmd)
// The wildcard * is reserved by the rpc server with the special meaning
// of "all accounts", so disallow naming accounts to this string.
if cmd.Account == "*" {
return nil, &ErrReservedAccountName
}
_, err := w.NextAccount(waddrmgr.KeyScopeBIP0044, cmd.Account)
if waddrmgr.IsError(err, waddrmgr.ErrLocked) {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCWalletUnlockNeeded,
Message: "Creating an account requires the wallet to be unlocked. " +
"Enter the wallet passphrase with walletpassphrase to unlock",
}
}
return nil, err
} | [
"func",
"createNewAccount",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"btcjson",
".",
"CreateNewAccountCmd",
")",
"\n",
"if... | // createNewAccount handles a createnewaccount request by creating and
// returning a new account. If the last account has no transaction history
// as per BIP 0044 a new account cannot be created so an error will be returned. | [
"createNewAccount",
"handles",
"a",
"createnewaccount",
"request",
"by",
"creating",
"and",
"returning",
"a",
"new",
"account",
".",
"If",
"the",
"last",
"account",
"has",
"no",
"transaction",
"history",
"as",
"per",
"BIP",
"0044",
"a",
"new",
"account",
"cann... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L651-L669 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | renameAccount | func renameAccount(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.RenameAccountCmd)
// The wildcard * is reserved by the rpc server with the special meaning
// of "all accounts", so disallow naming accounts to this string.
if cmd.NewAccount == "*" {
return nil, &ErrReservedAccountName
}
// Check that given account exists
account, err := w.AccountNumber(waddrmgr.KeyScopeBIP0044, cmd.OldAccount)
if err != nil {
return nil, err
}
return nil, w.RenameAccount(waddrmgr.KeyScopeBIP0044, account, cmd.NewAccount)
} | go | func renameAccount(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.RenameAccountCmd)
// The wildcard * is reserved by the rpc server with the special meaning
// of "all accounts", so disallow naming accounts to this string.
if cmd.NewAccount == "*" {
return nil, &ErrReservedAccountName
}
// Check that given account exists
account, err := w.AccountNumber(waddrmgr.KeyScopeBIP0044, cmd.OldAccount)
if err != nil {
return nil, err
}
return nil, w.RenameAccount(waddrmgr.KeyScopeBIP0044, account, cmd.NewAccount)
} | [
"func",
"renameAccount",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"btcjson",
".",
"RenameAccountCmd",
")",
"\n",
"if",
"... | // renameAccount handles a renameaccount request by renaming an account.
// If the account does not exist an appropiate error will be returned. | [
"renameAccount",
"handles",
"a",
"renameaccount",
"request",
"by",
"renaming",
"an",
"account",
".",
"If",
"the",
"account",
"does",
"not",
"exist",
"an",
"appropiate",
"error",
"will",
"be",
"returned",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L673-L688 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | getReceivedByAccount | func getReceivedByAccount(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.GetReceivedByAccountCmd)
account, err := w.AccountNumber(waddrmgr.KeyScopeBIP0044, cmd.Account)
if err != nil {
return nil, err
}
// TODO: This is more inefficient that it could be, but the entire
// algorithm is already dominated by reading every transaction in the
// wallet's history.
results, err := w.TotalReceivedForAccounts(
waddrmgr.KeyScopeBIP0044, int32(*cmd.MinConf),
)
if err != nil {
return nil, err
}
acctIndex := int(account)
if account == waddrmgr.ImportedAddrAccount {
acctIndex = len(results) - 1
}
return results[acctIndex].TotalReceived.ToBTC(), nil
} | go | func getReceivedByAccount(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.GetReceivedByAccountCmd)
account, err := w.AccountNumber(waddrmgr.KeyScopeBIP0044, cmd.Account)
if err != nil {
return nil, err
}
// TODO: This is more inefficient that it could be, but the entire
// algorithm is already dominated by reading every transaction in the
// wallet's history.
results, err := w.TotalReceivedForAccounts(
waddrmgr.KeyScopeBIP0044, int32(*cmd.MinConf),
)
if err != nil {
return nil, err
}
acctIndex := int(account)
if account == waddrmgr.ImportedAddrAccount {
acctIndex = len(results) - 1
}
return results[acctIndex].TotalReceived.ToBTC(), nil
} | [
"func",
"getReceivedByAccount",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"btcjson",
".",
"GetReceivedByAccountCmd",
")",
"\n... | // getReceivedByAccount handles a getreceivedbyaccount request by returning
// the total amount received by addresses of an account. | [
"getReceivedByAccount",
"handles",
"a",
"getreceivedbyaccount",
"request",
"by",
"returning",
"the",
"total",
"amount",
"received",
"by",
"addresses",
"of",
"an",
"account",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L742-L764 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | getReceivedByAddress | func getReceivedByAddress(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.GetReceivedByAddressCmd)
addr, err := decodeAddress(cmd.Address, w.ChainParams())
if err != nil {
return nil, err
}
total, err := w.TotalReceivedForAddr(addr, int32(*cmd.MinConf))
if err != nil {
return nil, err
}
return total.ToBTC(), nil
} | go | func getReceivedByAddress(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.GetReceivedByAddressCmd)
addr, err := decodeAddress(cmd.Address, w.ChainParams())
if err != nil {
return nil, err
}
total, err := w.TotalReceivedForAddr(addr, int32(*cmd.MinConf))
if err != nil {
return nil, err
}
return total.ToBTC(), nil
} | [
"func",
"getReceivedByAddress",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"btcjson",
".",
"GetReceivedByAddressCmd",
")",
"\n... | // getReceivedByAddress handles a getreceivedbyaddress request by returning
// the total amount received by a single address. | [
"getReceivedByAddress",
"handles",
"a",
"getreceivedbyaddress",
"request",
"by",
"returning",
"the",
"total",
"amount",
"received",
"by",
"a",
"single",
"address",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L768-L781 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | helpWithChainRPC | func helpWithChainRPC(icmd interface{}, w *wallet.Wallet, chainClient *chain.RPCClient) (interface{}, error) {
return help(icmd, w, chainClient)
} | go | func helpWithChainRPC(icmd interface{}, w *wallet.Wallet, chainClient *chain.RPCClient) (interface{}, error) {
return help(icmd, w, chainClient)
} | [
"func",
"helpWithChainRPC",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
",",
"chainClient",
"*",
"chain",
".",
"RPCClient",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"help",
"(",
"icmd",
",",
"... | // helpWithChainRPC handles the help request when the RPC server has been
// associated with a consensus RPC client. The additional RPC client is used to
// include help messages for methods implemented by the consensus server via RPC
// passthrough. | [
"helpWithChainRPC",
"handles",
"the",
"help",
"request",
"when",
"the",
"RPC",
"server",
"has",
"been",
"associated",
"with",
"a",
"consensus",
"RPC",
"client",
".",
"The",
"additional",
"RPC",
"client",
"is",
"used",
"to",
"include",
"help",
"messages",
"for"... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L946-L948 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | helpNoChainRPC | func helpNoChainRPC(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
return help(icmd, w, nil)
} | go | func helpNoChainRPC(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
return help(icmd, w, nil)
} | [
"func",
"helpNoChainRPC",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"help",
"(",
"icmd",
",",
"w",
",",
"nil",
")",
"\n",
"}"
] | // helpNoChainRPC handles the help request when the RPC server has not been
// associated with a consensus RPC client. No help messages are included for
// passthrough requests. | [
"helpNoChainRPC",
"handles",
"the",
"help",
"request",
"when",
"the",
"RPC",
"server",
"has",
"not",
"been",
"associated",
"with",
"a",
"consensus",
"RPC",
"client",
".",
"No",
"help",
"messages",
"are",
"included",
"for",
"passthrough",
"requests",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L953-L955 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | help | func help(icmd interface{}, w *wallet.Wallet, chainClient *chain.RPCClient) (interface{}, error) {
cmd := icmd.(*btcjson.HelpCmd)
// btcd returns different help messages depending on the kind of
// connection the client is using. Only methods availble to HTTP POST
// clients are available to be used by wallet clients, even though
// wallet itself is a websocket client to btcd. Therefore, create a
// POST client as needed.
//
// Returns nil if chainClient is currently nil or there is an error
// creating the client.
//
// This is hacky and is probably better handled by exposing help usage
// texts in a non-internal btcd package.
postClient := func() *rpcclient.Client {
if chainClient == nil {
return nil
}
c, err := chainClient.POSTClient()
if err != nil {
return nil
}
return c
}
if cmd.Command == nil || *cmd.Command == "" {
// Prepend chain server usage if it is available.
usages := requestUsages
client := postClient()
if client != nil {
rawChainUsage, err := client.RawRequest("help", nil)
var chainUsage string
if err == nil {
_ = json.Unmarshal([]byte(rawChainUsage), &chainUsage)
}
if chainUsage != "" {
usages = "Chain server usage:\n\n" + chainUsage + "\n\n" +
"Wallet server usage (overrides chain requests):\n\n" +
requestUsages
}
}
return usages, nil
}
defer helpDescsMu.Unlock()
helpDescsMu.Lock()
if helpDescs == nil {
// TODO: Allow other locales to be set via config or detemine
// this from environment variables. For now, hardcode US
// English.
helpDescs = localeHelpDescs["en_US"]()
}
helpText, ok := helpDescs[*cmd.Command]
if ok {
return helpText, nil
}
// Return the chain server's detailed help if possible.
var chainHelp string
client := postClient()
if client != nil {
param := make([]byte, len(*cmd.Command)+2)
param[0] = '"'
copy(param[1:], *cmd.Command)
param[len(param)-1] = '"'
rawChainHelp, err := client.RawRequest("help", []json.RawMessage{param})
if err == nil {
_ = json.Unmarshal([]byte(rawChainHelp), &chainHelp)
}
}
if chainHelp != "" {
return chainHelp, nil
}
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidParameter,
Message: fmt.Sprintf("No help for method '%s'", *cmd.Command),
}
} | go | func help(icmd interface{}, w *wallet.Wallet, chainClient *chain.RPCClient) (interface{}, error) {
cmd := icmd.(*btcjson.HelpCmd)
// btcd returns different help messages depending on the kind of
// connection the client is using. Only methods availble to HTTP POST
// clients are available to be used by wallet clients, even though
// wallet itself is a websocket client to btcd. Therefore, create a
// POST client as needed.
//
// Returns nil if chainClient is currently nil or there is an error
// creating the client.
//
// This is hacky and is probably better handled by exposing help usage
// texts in a non-internal btcd package.
postClient := func() *rpcclient.Client {
if chainClient == nil {
return nil
}
c, err := chainClient.POSTClient()
if err != nil {
return nil
}
return c
}
if cmd.Command == nil || *cmd.Command == "" {
// Prepend chain server usage if it is available.
usages := requestUsages
client := postClient()
if client != nil {
rawChainUsage, err := client.RawRequest("help", nil)
var chainUsage string
if err == nil {
_ = json.Unmarshal([]byte(rawChainUsage), &chainUsage)
}
if chainUsage != "" {
usages = "Chain server usage:\n\n" + chainUsage + "\n\n" +
"Wallet server usage (overrides chain requests):\n\n" +
requestUsages
}
}
return usages, nil
}
defer helpDescsMu.Unlock()
helpDescsMu.Lock()
if helpDescs == nil {
// TODO: Allow other locales to be set via config or detemine
// this from environment variables. For now, hardcode US
// English.
helpDescs = localeHelpDescs["en_US"]()
}
helpText, ok := helpDescs[*cmd.Command]
if ok {
return helpText, nil
}
// Return the chain server's detailed help if possible.
var chainHelp string
client := postClient()
if client != nil {
param := make([]byte, len(*cmd.Command)+2)
param[0] = '"'
copy(param[1:], *cmd.Command)
param[len(param)-1] = '"'
rawChainHelp, err := client.RawRequest("help", []json.RawMessage{param})
if err == nil {
_ = json.Unmarshal([]byte(rawChainHelp), &chainHelp)
}
}
if chainHelp != "" {
return chainHelp, nil
}
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidParameter,
Message: fmt.Sprintf("No help for method '%s'", *cmd.Command),
}
} | [
"func",
"help",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
",",
"chainClient",
"*",
"chain",
".",
"RPCClient",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"btcjson",
... | // help handles the help request by returning one line usage of all available
// methods, or full help for a specific method. The chainClient is optional,
// and this is simply a helper function for the HelpNoChainRPC and
// HelpWithChainRPC handlers. | [
"help",
"handles",
"the",
"help",
"request",
"by",
"returning",
"one",
"line",
"usage",
"of",
"all",
"available",
"methods",
"or",
"full",
"help",
"for",
"a",
"specific",
"method",
".",
"The",
"chainClient",
"is",
"optional",
"and",
"this",
"is",
"simply",
... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L961-L1039 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | listAccounts | func listAccounts(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.ListAccountsCmd)
accountBalances := map[string]float64{}
results, err := w.AccountBalances(waddrmgr.KeyScopeBIP0044, int32(*cmd.MinConf))
if err != nil {
return nil, err
}
for _, result := range results {
accountBalances[result.AccountName] = result.AccountBalance.ToBTC()
}
// Return the map. This will be marshaled into a JSON object.
return accountBalances, nil
} | go | func listAccounts(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.ListAccountsCmd)
accountBalances := map[string]float64{}
results, err := w.AccountBalances(waddrmgr.KeyScopeBIP0044, int32(*cmd.MinConf))
if err != nil {
return nil, err
}
for _, result := range results {
accountBalances[result.AccountName] = result.AccountBalance.ToBTC()
}
// Return the map. This will be marshaled into a JSON object.
return accountBalances, nil
} | [
"func",
"listAccounts",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"btcjson",
".",
"ListAccountsCmd",
")",
"\n",
"accountBal... | // listAccounts handles a listaccounts request by returning a map of account
// names to their balances. | [
"listAccounts",
"handles",
"a",
"listaccounts",
"request",
"by",
"returning",
"a",
"map",
"of",
"account",
"names",
"to",
"their",
"balances",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1043-L1056 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | listSinceBlock | func listSinceBlock(icmd interface{}, w *wallet.Wallet, chainClient *chain.RPCClient) (interface{}, error) {
cmd := icmd.(*btcjson.ListSinceBlockCmd)
syncBlock := w.Manager.SyncedTo()
targetConf := int64(*cmd.TargetConfirmations)
// For the result we need the block hash for the last block counted
// in the blockchain due to confirmations. We send this off now so that
// it can arrive asynchronously while we figure out the rest.
gbh := chainClient.GetBlockHashAsync(int64(syncBlock.Height) + 1 - targetConf)
var start int32
if cmd.BlockHash != nil {
hash, err := chainhash.NewHashFromStr(*cmd.BlockHash)
if err != nil {
return nil, DeserializationError{err}
}
block, err := chainClient.GetBlockVerboseTx(hash)
if err != nil {
return nil, err
}
start = int32(block.Height) + 1
}
txInfoList, err := w.ListSinceBlock(start, -1, syncBlock.Height)
if err != nil {
return nil, err
}
// Done with work, get the response.
blockHash, err := gbh.Receive()
if err != nil {
return nil, err
}
res := btcjson.ListSinceBlockResult{
Transactions: txInfoList,
LastBlock: blockHash.String(),
}
return res, nil
} | go | func listSinceBlock(icmd interface{}, w *wallet.Wallet, chainClient *chain.RPCClient) (interface{}, error) {
cmd := icmd.(*btcjson.ListSinceBlockCmd)
syncBlock := w.Manager.SyncedTo()
targetConf := int64(*cmd.TargetConfirmations)
// For the result we need the block hash for the last block counted
// in the blockchain due to confirmations. We send this off now so that
// it can arrive asynchronously while we figure out the rest.
gbh := chainClient.GetBlockHashAsync(int64(syncBlock.Height) + 1 - targetConf)
var start int32
if cmd.BlockHash != nil {
hash, err := chainhash.NewHashFromStr(*cmd.BlockHash)
if err != nil {
return nil, DeserializationError{err}
}
block, err := chainClient.GetBlockVerboseTx(hash)
if err != nil {
return nil, err
}
start = int32(block.Height) + 1
}
txInfoList, err := w.ListSinceBlock(start, -1, syncBlock.Height)
if err != nil {
return nil, err
}
// Done with work, get the response.
blockHash, err := gbh.Receive()
if err != nil {
return nil, err
}
res := btcjson.ListSinceBlockResult{
Transactions: txInfoList,
LastBlock: blockHash.String(),
}
return res, nil
} | [
"func",
"listSinceBlock",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
",",
"chainClient",
"*",
"chain",
".",
"RPCClient",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"... | // listSinceBlock handles a listsinceblock request by returning an array of maps
// with details of sent and received wallet transactions since the given block. | [
"listSinceBlock",
"handles",
"a",
"listsinceblock",
"request",
"by",
"returning",
"an",
"array",
"of",
"maps",
"with",
"details",
"of",
"sent",
"and",
"received",
"wallet",
"transactions",
"since",
"the",
"given",
"block",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1196-L1236 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | listTransactions | func listTransactions(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.ListTransactionsCmd)
// TODO: ListTransactions does not currently understand the difference
// between transactions pertaining to one account from another. This
// will be resolved when wtxmgr is combined with the waddrmgr namespace.
if cmd.Account != nil && *cmd.Account != "*" {
// For now, don't bother trying to continue if the user
// specified an account, since this can't be (easily or
// efficiently) calculated.
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCWallet,
Message: "Transactions are not yet grouped by account",
}
}
return w.ListTransactions(*cmd.From, *cmd.Count)
} | go | func listTransactions(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.ListTransactionsCmd)
// TODO: ListTransactions does not currently understand the difference
// between transactions pertaining to one account from another. This
// will be resolved when wtxmgr is combined with the waddrmgr namespace.
if cmd.Account != nil && *cmd.Account != "*" {
// For now, don't bother trying to continue if the user
// specified an account, since this can't be (easily or
// efficiently) calculated.
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCWallet,
Message: "Transactions are not yet grouped by account",
}
}
return w.ListTransactions(*cmd.From, *cmd.Count)
} | [
"func",
"listTransactions",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"btcjson",
".",
"ListTransactionsCmd",
")",
"\n",
"if... | // listTransactions handles a listtransactions request by returning an
// array of maps with details of sent and recevied wallet transactions. | [
"listTransactions",
"handles",
"a",
"listtransactions",
"request",
"by",
"returning",
"an",
"array",
"of",
"maps",
"with",
"details",
"of",
"sent",
"and",
"recevied",
"wallet",
"transactions",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1240-L1258 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | listAddressTransactions | func listAddressTransactions(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.ListAddressTransactionsCmd)
if cmd.Account != nil && *cmd.Account != "*" {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidParameter,
Message: "Listing transactions for addresses may only be done for all accounts",
}
}
// Decode addresses.
hash160Map := make(map[string]struct{})
for _, addrStr := range cmd.Addresses {
addr, err := decodeAddress(addrStr, w.ChainParams())
if err != nil {
return nil, err
}
hash160Map[string(addr.ScriptAddress())] = struct{}{}
}
return w.ListAddressTransactions(hash160Map)
} | go | func listAddressTransactions(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.ListAddressTransactionsCmd)
if cmd.Account != nil && *cmd.Account != "*" {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidParameter,
Message: "Listing transactions for addresses may only be done for all accounts",
}
}
// Decode addresses.
hash160Map := make(map[string]struct{})
for _, addrStr := range cmd.Addresses {
addr, err := decodeAddress(addrStr, w.ChainParams())
if err != nil {
return nil, err
}
hash160Map[string(addr.ScriptAddress())] = struct{}{}
}
return w.ListAddressTransactions(hash160Map)
} | [
"func",
"listAddressTransactions",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"btcjson",
".",
"ListAddressTransactionsCmd",
")",... | // listAddressTransactions handles a listaddresstransactions request by
// returning an array of maps with details of spent and received wallet
// transactions. The form of the reply is identical to listtransactions,
// but the array elements are limited to transaction details which are
// about the addresess included in the request. | [
"listAddressTransactions",
"handles",
"a",
"listaddresstransactions",
"request",
"by",
"returning",
"an",
"array",
"of",
"maps",
"with",
"details",
"of",
"spent",
"and",
"received",
"wallet",
"transactions",
".",
"The",
"form",
"of",
"the",
"reply",
"is",
"identic... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1265-L1286 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | listAllTransactions | func listAllTransactions(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.ListAllTransactionsCmd)
if cmd.Account != nil && *cmd.Account != "*" {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidParameter,
Message: "Listing all transactions may only be done for all accounts",
}
}
return w.ListAllTransactions()
} | go | func listAllTransactions(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.ListAllTransactionsCmd)
if cmd.Account != nil && *cmd.Account != "*" {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidParameter,
Message: "Listing all transactions may only be done for all accounts",
}
}
return w.ListAllTransactions()
} | [
"func",
"listAllTransactions",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"btcjson",
".",
"ListAllTransactionsCmd",
")",
"\n",... | // listAllTransactions handles a listalltransactions request by returning
// a map with details of sent and recevied wallet transactions. This is
// similar to ListTransactions, except it takes only a single optional
// argument for the account name and replies with all transactions. | [
"listAllTransactions",
"handles",
"a",
"listalltransactions",
"request",
"by",
"returning",
"a",
"map",
"with",
"details",
"of",
"sent",
"and",
"recevied",
"wallet",
"transactions",
".",
"This",
"is",
"similar",
"to",
"ListTransactions",
"except",
"it",
"takes",
"... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1292-L1303 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | listUnspent | func listUnspent(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.ListUnspentCmd)
var addresses map[string]struct{}
if cmd.Addresses != nil {
addresses = make(map[string]struct{})
// confirm that all of them are good:
for _, as := range *cmd.Addresses {
a, err := decodeAddress(as, w.ChainParams())
if err != nil {
return nil, err
}
addresses[a.EncodeAddress()] = struct{}{}
}
}
return w.ListUnspent(int32(*cmd.MinConf), int32(*cmd.MaxConf), addresses)
} | go | func listUnspent(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.ListUnspentCmd)
var addresses map[string]struct{}
if cmd.Addresses != nil {
addresses = make(map[string]struct{})
// confirm that all of them are good:
for _, as := range *cmd.Addresses {
a, err := decodeAddress(as, w.ChainParams())
if err != nil {
return nil, err
}
addresses[a.EncodeAddress()] = struct{}{}
}
}
return w.ListUnspent(int32(*cmd.MinConf), int32(*cmd.MaxConf), addresses)
} | [
"func",
"listUnspent",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"btcjson",
".",
"ListUnspentCmd",
")",
"\n",
"var",
"add... | // listUnspent handles the listunspent command. | [
"listUnspent",
"handles",
"the",
"listunspent",
"command",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1306-L1323 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | lockUnspent | func lockUnspent(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.LockUnspentCmd)
switch {
case cmd.Unlock && len(cmd.Transactions) == 0:
w.ResetLockedOutpoints()
default:
for _, input := range cmd.Transactions {
txHash, err := chainhash.NewHashFromStr(input.Txid)
if err != nil {
return nil, ParseError{err}
}
op := wire.OutPoint{Hash: *txHash, Index: input.Vout}
if cmd.Unlock {
w.UnlockOutpoint(op)
} else {
w.LockOutpoint(op)
}
}
}
return true, nil
} | go | func lockUnspent(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.LockUnspentCmd)
switch {
case cmd.Unlock && len(cmd.Transactions) == 0:
w.ResetLockedOutpoints()
default:
for _, input := range cmd.Transactions {
txHash, err := chainhash.NewHashFromStr(input.Txid)
if err != nil {
return nil, ParseError{err}
}
op := wire.OutPoint{Hash: *txHash, Index: input.Vout}
if cmd.Unlock {
w.UnlockOutpoint(op)
} else {
w.LockOutpoint(op)
}
}
}
return true, nil
} | [
"func",
"lockUnspent",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"btcjson",
".",
"LockUnspentCmd",
")",
"\n",
"switch",
"... | // lockUnspent handles the lockunspent command. | [
"lockUnspent",
"handles",
"the",
"lockunspent",
"command",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1326-L1347 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | makeOutputs | func makeOutputs(pairs map[string]btcutil.Amount, chainParams *chaincfg.Params) ([]*wire.TxOut, error) {
outputs := make([]*wire.TxOut, 0, len(pairs))
for addrStr, amt := range pairs {
addr, err := btcutil.DecodeAddress(addrStr, chainParams)
if err != nil {
return nil, fmt.Errorf("cannot decode address: %s", err)
}
pkScript, err := txscript.PayToAddrScript(addr)
if err != nil {
return nil, fmt.Errorf("cannot create txout script: %s", err)
}
outputs = append(outputs, wire.NewTxOut(int64(amt), pkScript))
}
return outputs, nil
} | go | func makeOutputs(pairs map[string]btcutil.Amount, chainParams *chaincfg.Params) ([]*wire.TxOut, error) {
outputs := make([]*wire.TxOut, 0, len(pairs))
for addrStr, amt := range pairs {
addr, err := btcutil.DecodeAddress(addrStr, chainParams)
if err != nil {
return nil, fmt.Errorf("cannot decode address: %s", err)
}
pkScript, err := txscript.PayToAddrScript(addr)
if err != nil {
return nil, fmt.Errorf("cannot create txout script: %s", err)
}
outputs = append(outputs, wire.NewTxOut(int64(amt), pkScript))
}
return outputs, nil
} | [
"func",
"makeOutputs",
"(",
"pairs",
"map",
"[",
"string",
"]",
"btcutil",
".",
"Amount",
",",
"chainParams",
"*",
"chaincfg",
".",
"Params",
")",
"(",
"[",
"]",
"*",
"wire",
".",
"TxOut",
",",
"error",
")",
"{",
"outputs",
":=",
"make",
"(",
"[",
... | // makeOutputs creates a slice of transaction outputs from a pair of address
// strings to amounts. This is used to create the outputs to include in newly
// created transactions from a JSON object describing the output destinations
// and amounts. | [
"makeOutputs",
"creates",
"a",
"slice",
"of",
"transaction",
"outputs",
"from",
"a",
"pair",
"of",
"address",
"strings",
"to",
"amounts",
".",
"This",
"is",
"used",
"to",
"create",
"the",
"outputs",
"to",
"include",
"in",
"newly",
"created",
"transactions",
... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1353-L1369 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | sendPairs | func sendPairs(w *wallet.Wallet, amounts map[string]btcutil.Amount,
account uint32, minconf int32, feeSatPerKb btcutil.Amount) (string, error) {
outputs, err := makeOutputs(amounts, w.ChainParams())
if err != nil {
return "", err
}
tx, err := w.SendOutputs(outputs, account, minconf, feeSatPerKb)
if err != nil {
if err == txrules.ErrAmountNegative {
return "", ErrNeedPositiveAmount
}
if waddrmgr.IsError(err, waddrmgr.ErrLocked) {
return "", &ErrWalletUnlockNeeded
}
switch err.(type) {
case btcjson.RPCError:
return "", err
}
return "", &btcjson.RPCError{
Code: btcjson.ErrRPCInternal.Code,
Message: err.Error(),
}
}
txHashStr := tx.TxHash().String()
log.Infof("Successfully sent transaction %v", txHashStr)
return txHashStr, nil
} | go | func sendPairs(w *wallet.Wallet, amounts map[string]btcutil.Amount,
account uint32, minconf int32, feeSatPerKb btcutil.Amount) (string, error) {
outputs, err := makeOutputs(amounts, w.ChainParams())
if err != nil {
return "", err
}
tx, err := w.SendOutputs(outputs, account, minconf, feeSatPerKb)
if err != nil {
if err == txrules.ErrAmountNegative {
return "", ErrNeedPositiveAmount
}
if waddrmgr.IsError(err, waddrmgr.ErrLocked) {
return "", &ErrWalletUnlockNeeded
}
switch err.(type) {
case btcjson.RPCError:
return "", err
}
return "", &btcjson.RPCError{
Code: btcjson.ErrRPCInternal.Code,
Message: err.Error(),
}
}
txHashStr := tx.TxHash().String()
log.Infof("Successfully sent transaction %v", txHashStr)
return txHashStr, nil
} | [
"func",
"sendPairs",
"(",
"w",
"*",
"wallet",
".",
"Wallet",
",",
"amounts",
"map",
"[",
"string",
"]",
"btcutil",
".",
"Amount",
",",
"account",
"uint32",
",",
"minconf",
"int32",
",",
"feeSatPerKb",
"btcutil",
".",
"Amount",
")",
"(",
"string",
",",
... | // sendPairs creates and sends payment transactions.
// It returns the transaction hash in string format upon success
// All errors are returned in btcjson.RPCError format | [
"sendPairs",
"creates",
"and",
"sends",
"payment",
"transactions",
".",
"It",
"returns",
"the",
"transaction",
"hash",
"in",
"string",
"format",
"upon",
"success",
"All",
"errors",
"are",
"returned",
"in",
"btcjson",
".",
"RPCError",
"format"
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1374-L1403 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | sendFrom | func sendFrom(icmd interface{}, w *wallet.Wallet, chainClient *chain.RPCClient) (interface{}, error) {
cmd := icmd.(*btcjson.SendFromCmd)
// Transaction comments are not yet supported. Error instead of
// pretending to save them.
if !isNilOrEmpty(cmd.Comment) || !isNilOrEmpty(cmd.CommentTo) {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCUnimplemented,
Message: "Transaction comments are not yet supported",
}
}
account, err := w.AccountNumber(
waddrmgr.KeyScopeBIP0044, cmd.FromAccount,
)
if err != nil {
return nil, err
}
// Check that signed integer parameters are positive.
if cmd.Amount < 0 {
return nil, ErrNeedPositiveAmount
}
minConf := int32(*cmd.MinConf)
if minConf < 0 {
return nil, ErrNeedPositiveMinconf
}
// Create map of address and amount pairs.
amt, err := btcutil.NewAmount(cmd.Amount)
if err != nil {
return nil, err
}
pairs := map[string]btcutil.Amount{
cmd.ToAddress: amt,
}
return sendPairs(w, pairs, account, minConf,
txrules.DefaultRelayFeePerKb)
} | go | func sendFrom(icmd interface{}, w *wallet.Wallet, chainClient *chain.RPCClient) (interface{}, error) {
cmd := icmd.(*btcjson.SendFromCmd)
// Transaction comments are not yet supported. Error instead of
// pretending to save them.
if !isNilOrEmpty(cmd.Comment) || !isNilOrEmpty(cmd.CommentTo) {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCUnimplemented,
Message: "Transaction comments are not yet supported",
}
}
account, err := w.AccountNumber(
waddrmgr.KeyScopeBIP0044, cmd.FromAccount,
)
if err != nil {
return nil, err
}
// Check that signed integer parameters are positive.
if cmd.Amount < 0 {
return nil, ErrNeedPositiveAmount
}
minConf := int32(*cmd.MinConf)
if minConf < 0 {
return nil, ErrNeedPositiveMinconf
}
// Create map of address and amount pairs.
amt, err := btcutil.NewAmount(cmd.Amount)
if err != nil {
return nil, err
}
pairs := map[string]btcutil.Amount{
cmd.ToAddress: amt,
}
return sendPairs(w, pairs, account, minConf,
txrules.DefaultRelayFeePerKb)
} | [
"func",
"sendFrom",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
",",
"chainClient",
"*",
"chain",
".",
"RPCClient",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"btcjso... | // sendFrom handles a sendfrom RPC request by creating a new transaction
// spending unspent transaction outputs for a wallet to another payment
// address. Leftover inputs not sent to the payment address or a fee for
// the miner are sent back to a new address in the wallet. Upon success,
// the TxID for the created transaction is returned. | [
"sendFrom",
"handles",
"a",
"sendfrom",
"RPC",
"request",
"by",
"creating",
"a",
"new",
"transaction",
"spending",
"unspent",
"transaction",
"outputs",
"for",
"a",
"wallet",
"to",
"another",
"payment",
"address",
".",
"Leftover",
"inputs",
"not",
"sent",
"to",
... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1414-L1452 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | sendMany | func sendMany(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.SendManyCmd)
// Transaction comments are not yet supported. Error instead of
// pretending to save them.
if !isNilOrEmpty(cmd.Comment) {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCUnimplemented,
Message: "Transaction comments are not yet supported",
}
}
account, err := w.AccountNumber(waddrmgr.KeyScopeBIP0044, cmd.FromAccount)
if err != nil {
return nil, err
}
// Check that minconf is positive.
minConf := int32(*cmd.MinConf)
if minConf < 0 {
return nil, ErrNeedPositiveMinconf
}
// Recreate address/amount pairs, using dcrutil.Amount.
pairs := make(map[string]btcutil.Amount, len(cmd.Amounts))
for k, v := range cmd.Amounts {
amt, err := btcutil.NewAmount(v)
if err != nil {
return nil, err
}
pairs[k] = amt
}
return sendPairs(w, pairs, account, minConf, txrules.DefaultRelayFeePerKb)
} | go | func sendMany(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.SendManyCmd)
// Transaction comments are not yet supported. Error instead of
// pretending to save them.
if !isNilOrEmpty(cmd.Comment) {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCUnimplemented,
Message: "Transaction comments are not yet supported",
}
}
account, err := w.AccountNumber(waddrmgr.KeyScopeBIP0044, cmd.FromAccount)
if err != nil {
return nil, err
}
// Check that minconf is positive.
minConf := int32(*cmd.MinConf)
if minConf < 0 {
return nil, ErrNeedPositiveMinconf
}
// Recreate address/amount pairs, using dcrutil.Amount.
pairs := make(map[string]btcutil.Amount, len(cmd.Amounts))
for k, v := range cmd.Amounts {
amt, err := btcutil.NewAmount(v)
if err != nil {
return nil, err
}
pairs[k] = amt
}
return sendPairs(w, pairs, account, minConf, txrules.DefaultRelayFeePerKb)
} | [
"func",
"sendMany",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"btcjson",
".",
"SendManyCmd",
")",
"\n",
"if",
"!",
"isN... | // sendMany handles a sendmany RPC request by creating a new transaction
// spending unspent transaction outputs for a wallet to any number of
// payment addresses. Leftover inputs not sent to the payment address
// or a fee for the miner are sent back to a new address in the wallet.
// Upon success, the TxID for the created transaction is returned. | [
"sendMany",
"handles",
"a",
"sendmany",
"RPC",
"request",
"by",
"creating",
"a",
"new",
"transaction",
"spending",
"unspent",
"transaction",
"outputs",
"for",
"a",
"wallet",
"to",
"any",
"number",
"of",
"payment",
"addresses",
".",
"Leftover",
"inputs",
"not",
... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1459-L1493 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | sendToAddress | func sendToAddress(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.SendToAddressCmd)
// Transaction comments are not yet supported. Error instead of
// pretending to save them.
if !isNilOrEmpty(cmd.Comment) || !isNilOrEmpty(cmd.CommentTo) {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCUnimplemented,
Message: "Transaction comments are not yet supported",
}
}
amt, err := btcutil.NewAmount(cmd.Amount)
if err != nil {
return nil, err
}
// Check that signed integer parameters are positive.
if amt < 0 {
return nil, ErrNeedPositiveAmount
}
// Mock up map of address and amount pairs.
pairs := map[string]btcutil.Amount{
cmd.Address: amt,
}
// sendtoaddress always spends from the default account, this matches bitcoind
return sendPairs(w, pairs, waddrmgr.DefaultAccountNum, 1,
txrules.DefaultRelayFeePerKb)
} | go | func sendToAddress(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.SendToAddressCmd)
// Transaction comments are not yet supported. Error instead of
// pretending to save them.
if !isNilOrEmpty(cmd.Comment) || !isNilOrEmpty(cmd.CommentTo) {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCUnimplemented,
Message: "Transaction comments are not yet supported",
}
}
amt, err := btcutil.NewAmount(cmd.Amount)
if err != nil {
return nil, err
}
// Check that signed integer parameters are positive.
if amt < 0 {
return nil, ErrNeedPositiveAmount
}
// Mock up map of address and amount pairs.
pairs := map[string]btcutil.Amount{
cmd.Address: amt,
}
// sendtoaddress always spends from the default account, this matches bitcoind
return sendPairs(w, pairs, waddrmgr.DefaultAccountNum, 1,
txrules.DefaultRelayFeePerKb)
} | [
"func",
"sendToAddress",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"btcjson",
".",
"SendToAddressCmd",
")",
"\n",
"if",
"... | // sendToAddress handles a sendtoaddress RPC request by creating a new
// transaction spending unspent transaction outputs for a wallet to another
// payment address. Leftover inputs not sent to the payment address or a fee
// for the miner are sent back to a new address in the wallet. Upon success,
// the TxID for the created transaction is returned. | [
"sendToAddress",
"handles",
"a",
"sendtoaddress",
"RPC",
"request",
"by",
"creating",
"a",
"new",
"transaction",
"spending",
"unspent",
"transaction",
"outputs",
"for",
"a",
"wallet",
"to",
"another",
"payment",
"address",
".",
"Leftover",
"inputs",
"not",
"sent",... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1500-L1530 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | setTxFee | func setTxFee(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.SetTxFeeCmd)
// Check that amount is not negative.
if cmd.Amount < 0 {
return nil, ErrNeedPositiveAmount
}
// A boolean true result is returned upon success.
return true, nil
} | go | func setTxFee(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.SetTxFeeCmd)
// Check that amount is not negative.
if cmd.Amount < 0 {
return nil, ErrNeedPositiveAmount
}
// A boolean true result is returned upon success.
return true, nil
} | [
"func",
"setTxFee",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"btcjson",
".",
"SetTxFeeCmd",
")",
"\n",
"if",
"cmd",
".... | // setTxFee sets the transaction fee per kilobyte added to transactions. | [
"setTxFee",
"sets",
"the",
"transaction",
"fee",
"per",
"kilobyte",
"added",
"to",
"transactions",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1533-L1543 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | signMessage | func signMessage(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.SignMessageCmd)
addr, err := decodeAddress(cmd.Address, w.ChainParams())
if err != nil {
return nil, err
}
privKey, err := w.PrivKeyForAddress(addr)
if err != nil {
return nil, err
}
var buf bytes.Buffer
wire.WriteVarString(&buf, 0, "Bitcoin Signed Message:\n")
wire.WriteVarString(&buf, 0, cmd.Message)
messageHash := chainhash.DoubleHashB(buf.Bytes())
sigbytes, err := btcec.SignCompact(btcec.S256(), privKey,
messageHash, true)
if err != nil {
return nil, err
}
return base64.StdEncoding.EncodeToString(sigbytes), nil
} | go | func signMessage(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.SignMessageCmd)
addr, err := decodeAddress(cmd.Address, w.ChainParams())
if err != nil {
return nil, err
}
privKey, err := w.PrivKeyForAddress(addr)
if err != nil {
return nil, err
}
var buf bytes.Buffer
wire.WriteVarString(&buf, 0, "Bitcoin Signed Message:\n")
wire.WriteVarString(&buf, 0, cmd.Message)
messageHash := chainhash.DoubleHashB(buf.Bytes())
sigbytes, err := btcec.SignCompact(btcec.S256(), privKey,
messageHash, true)
if err != nil {
return nil, err
}
return base64.StdEncoding.EncodeToString(sigbytes), nil
} | [
"func",
"signMessage",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"btcjson",
".",
"SignMessageCmd",
")",
"\n",
"addr",
","... | // signMessage signs the given message with the private key for the given
// address | [
"signMessage",
"signs",
"the",
"given",
"message",
"with",
"the",
"private",
"key",
"for",
"the",
"given",
"address"
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1547-L1571 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | validateAddress | func validateAddress(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.ValidateAddressCmd)
result := btcjson.ValidateAddressWalletResult{}
addr, err := decodeAddress(cmd.Address, w.ChainParams())
if err != nil {
// Use result zero value (IsValid=false).
return result, nil
}
// We could put whether or not the address is a script here,
// by checking the type of "addr", however, the reference
// implementation only puts that information if the script is
// "ismine", and we follow that behaviour.
result.Address = addr.EncodeAddress()
result.IsValid = true
ainfo, err := w.AddressInfo(addr)
if err != nil {
if waddrmgr.IsError(err, waddrmgr.ErrAddressNotFound) {
// No additional information available about the address.
return result, nil
}
return nil, err
}
// The address lookup was successful which means there is further
// information about it available and it is "mine".
result.IsMine = true
acctName, err := w.AccountName(waddrmgr.KeyScopeBIP0044, ainfo.Account())
if err != nil {
return nil, &ErrAccountNameNotFound
}
result.Account = acctName
switch ma := ainfo.(type) {
case waddrmgr.ManagedPubKeyAddress:
result.IsCompressed = ma.Compressed()
result.PubKey = ma.ExportPubKey()
case waddrmgr.ManagedScriptAddress:
result.IsScript = true
// The script is only available if the manager is unlocked, so
// just break out now if there is an error.
script, err := ma.Script()
if err != nil {
break
}
result.Hex = hex.EncodeToString(script)
// This typically shouldn't fail unless an invalid script was
// imported. However, if it fails for any reason, there is no
// further information available, so just set the script type
// a non-standard and break out now.
class, addrs, reqSigs, err := txscript.ExtractPkScriptAddrs(
script, w.ChainParams())
if err != nil {
result.Script = txscript.NonStandardTy.String()
break
}
addrStrings := make([]string, len(addrs))
for i, a := range addrs {
addrStrings[i] = a.EncodeAddress()
}
result.Addresses = addrStrings
// Multi-signature scripts also provide the number of required
// signatures.
result.Script = class.String()
if class == txscript.MultiSigTy {
result.SigsRequired = int32(reqSigs)
}
}
return result, nil
} | go | func validateAddress(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.ValidateAddressCmd)
result := btcjson.ValidateAddressWalletResult{}
addr, err := decodeAddress(cmd.Address, w.ChainParams())
if err != nil {
// Use result zero value (IsValid=false).
return result, nil
}
// We could put whether or not the address is a script here,
// by checking the type of "addr", however, the reference
// implementation only puts that information if the script is
// "ismine", and we follow that behaviour.
result.Address = addr.EncodeAddress()
result.IsValid = true
ainfo, err := w.AddressInfo(addr)
if err != nil {
if waddrmgr.IsError(err, waddrmgr.ErrAddressNotFound) {
// No additional information available about the address.
return result, nil
}
return nil, err
}
// The address lookup was successful which means there is further
// information about it available and it is "mine".
result.IsMine = true
acctName, err := w.AccountName(waddrmgr.KeyScopeBIP0044, ainfo.Account())
if err != nil {
return nil, &ErrAccountNameNotFound
}
result.Account = acctName
switch ma := ainfo.(type) {
case waddrmgr.ManagedPubKeyAddress:
result.IsCompressed = ma.Compressed()
result.PubKey = ma.ExportPubKey()
case waddrmgr.ManagedScriptAddress:
result.IsScript = true
// The script is only available if the manager is unlocked, so
// just break out now if there is an error.
script, err := ma.Script()
if err != nil {
break
}
result.Hex = hex.EncodeToString(script)
// This typically shouldn't fail unless an invalid script was
// imported. However, if it fails for any reason, there is no
// further information available, so just set the script type
// a non-standard and break out now.
class, addrs, reqSigs, err := txscript.ExtractPkScriptAddrs(
script, w.ChainParams())
if err != nil {
result.Script = txscript.NonStandardTy.String()
break
}
addrStrings := make([]string, len(addrs))
for i, a := range addrs {
addrStrings[i] = a.EncodeAddress()
}
result.Addresses = addrStrings
// Multi-signature scripts also provide the number of required
// signatures.
result.Script = class.String()
if class == txscript.MultiSigTy {
result.SigsRequired = int32(reqSigs)
}
}
return result, nil
} | [
"func",
"validateAddress",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"btcjson",
".",
"ValidateAddressCmd",
")",
"\n",
"resu... | // validateAddress handles the validateaddress command. | [
"validateAddress",
"handles",
"the",
"validateaddress",
"command",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1748-L1825 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | verifyMessage | func verifyMessage(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.VerifyMessageCmd)
addr, err := decodeAddress(cmd.Address, w.ChainParams())
if err != nil {
return nil, err
}
// decode base64 signature
sig, err := base64.StdEncoding.DecodeString(cmd.Signature)
if err != nil {
return nil, err
}
// Validate the signature - this just shows that it was valid at all.
// we will compare it with the key next.
var buf bytes.Buffer
wire.WriteVarString(&buf, 0, "Bitcoin Signed Message:\n")
wire.WriteVarString(&buf, 0, cmd.Message)
expectedMessageHash := chainhash.DoubleHashB(buf.Bytes())
pk, wasCompressed, err := btcec.RecoverCompact(btcec.S256(), sig,
expectedMessageHash)
if err != nil {
return nil, err
}
var serializedPubKey []byte
if wasCompressed {
serializedPubKey = pk.SerializeCompressed()
} else {
serializedPubKey = pk.SerializeUncompressed()
}
// Verify that the signed-by address matches the given address
switch checkAddr := addr.(type) {
case *btcutil.AddressPubKeyHash: // ok
return bytes.Equal(btcutil.Hash160(serializedPubKey), checkAddr.Hash160()[:]), nil
case *btcutil.AddressPubKey: // ok
return string(serializedPubKey) == checkAddr.String(), nil
default:
return nil, errors.New("address type not supported")
}
} | go | func verifyMessage(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.VerifyMessageCmd)
addr, err := decodeAddress(cmd.Address, w.ChainParams())
if err != nil {
return nil, err
}
// decode base64 signature
sig, err := base64.StdEncoding.DecodeString(cmd.Signature)
if err != nil {
return nil, err
}
// Validate the signature - this just shows that it was valid at all.
// we will compare it with the key next.
var buf bytes.Buffer
wire.WriteVarString(&buf, 0, "Bitcoin Signed Message:\n")
wire.WriteVarString(&buf, 0, cmd.Message)
expectedMessageHash := chainhash.DoubleHashB(buf.Bytes())
pk, wasCompressed, err := btcec.RecoverCompact(btcec.S256(), sig,
expectedMessageHash)
if err != nil {
return nil, err
}
var serializedPubKey []byte
if wasCompressed {
serializedPubKey = pk.SerializeCompressed()
} else {
serializedPubKey = pk.SerializeUncompressed()
}
// Verify that the signed-by address matches the given address
switch checkAddr := addr.(type) {
case *btcutil.AddressPubKeyHash: // ok
return bytes.Equal(btcutil.Hash160(serializedPubKey), checkAddr.Hash160()[:]), nil
case *btcutil.AddressPubKey: // ok
return string(serializedPubKey) == checkAddr.String(), nil
default:
return nil, errors.New("address type not supported")
}
} | [
"func",
"verifyMessage",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"btcjson",
".",
"VerifyMessageCmd",
")",
"\n",
"addr",
... | // verifyMessage handles the verifymessage command by verifying the provided
// compact signature for the given address and message. | [
"verifyMessage",
"handles",
"the",
"verifymessage",
"command",
"by",
"verifying",
"the",
"provided",
"compact",
"signature",
"for",
"the",
"given",
"address",
"and",
"message",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1829-L1870 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | walletPassphrase | func walletPassphrase(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.WalletPassphraseCmd)
timeout := time.Second * time.Duration(cmd.Timeout)
var unlockAfter <-chan time.Time
if timeout != 0 {
unlockAfter = time.After(timeout)
}
err := w.Unlock([]byte(cmd.Passphrase), unlockAfter)
return nil, err
} | go | func walletPassphrase(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.WalletPassphraseCmd)
timeout := time.Second * time.Duration(cmd.Timeout)
var unlockAfter <-chan time.Time
if timeout != 0 {
unlockAfter = time.After(timeout)
}
err := w.Unlock([]byte(cmd.Passphrase), unlockAfter)
return nil, err
} | [
"func",
"walletPassphrase",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"btcjson",
".",
"WalletPassphraseCmd",
")",
"\n",
"ti... | // walletPassphrase responds to the walletpassphrase request by unlocking
// the wallet. The decryption key is saved in the wallet until timeout
// seconds expires, after which the wallet is locked. | [
"walletPassphrase",
"responds",
"to",
"the",
"walletpassphrase",
"request",
"by",
"unlocking",
"the",
"wallet",
".",
"The",
"decryption",
"key",
"is",
"saved",
"in",
"the",
"wallet",
"until",
"timeout",
"seconds",
"expires",
"after",
"which",
"the",
"wallet",
"i... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1890-L1900 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | walletPassphraseChange | func walletPassphraseChange(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.WalletPassphraseChangeCmd)
err := w.ChangePrivatePassphrase([]byte(cmd.OldPassphrase),
[]byte(cmd.NewPassphrase))
if waddrmgr.IsError(err, waddrmgr.ErrWrongPassphrase) {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCWalletPassphraseIncorrect,
Message: "Incorrect passphrase",
}
}
return nil, err
} | go | func walletPassphraseChange(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.WalletPassphraseChangeCmd)
err := w.ChangePrivatePassphrase([]byte(cmd.OldPassphrase),
[]byte(cmd.NewPassphrase))
if waddrmgr.IsError(err, waddrmgr.ErrWrongPassphrase) {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCWalletPassphraseIncorrect,
Message: "Incorrect passphrase",
}
}
return nil, err
} | [
"func",
"walletPassphraseChange",
"(",
"icmd",
"interface",
"{",
"}",
",",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"cmd",
":=",
"icmd",
".",
"(",
"*",
"btcjson",
".",
"WalletPassphraseChangeCmd",
")",
... | // walletPassphraseChange responds to the walletpassphrasechange request
// by unlocking all accounts with the provided old passphrase, and
// re-encrypting each private key with an AES key derived from the new
// passphrase.
//
// If the old passphrase is correct and the passphrase is changed, all
// wallets will be immediately locked. | [
"walletPassphraseChange",
"responds",
"to",
"the",
"walletpassphrasechange",
"request",
"by",
"unlocking",
"all",
"accounts",
"with",
"the",
"provided",
"old",
"passphrase",
"and",
"re",
"-",
"encrypting",
"each",
"private",
"key",
"with",
"an",
"AES",
"key",
"der... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1909-L1921 | train |
btcsuite/btcwallet | rpc/legacyrpc/methods.go | decodeHexStr | func decodeHexStr(hexStr string) ([]byte, error) {
if len(hexStr)%2 != 0 {
hexStr = "0" + hexStr
}
decoded, err := hex.DecodeString(hexStr)
if err != nil {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCDecodeHexString,
Message: "Hex string decode failed: " + err.Error(),
}
}
return decoded, nil
} | go | func decodeHexStr(hexStr string) ([]byte, error) {
if len(hexStr)%2 != 0 {
hexStr = "0" + hexStr
}
decoded, err := hex.DecodeString(hexStr)
if err != nil {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCDecodeHexString,
Message: "Hex string decode failed: " + err.Error(),
}
}
return decoded, nil
} | [
"func",
"decodeHexStr",
"(",
"hexStr",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"len",
"(",
"hexStr",
")",
"%",
"2",
"!=",
"0",
"{",
"hexStr",
"=",
"\"0\"",
"+",
"hexStr",
"\n",
"}",
"\n",
"decoded",
",",
"err",
":=",
... | // decodeHexStr decodes the hex encoding of a string, possibly prepending a
// leading '0' character if there is an odd number of bytes in the hex string.
// This is to prevent an error for an invalid hex string when using an odd
// number of bytes when calling hex.Decode. | [
"decodeHexStr",
"decodes",
"the",
"hex",
"encoding",
"of",
"a",
"string",
"possibly",
"prepending",
"a",
"leading",
"0",
"character",
"if",
"there",
"is",
"an",
"odd",
"number",
"of",
"bytes",
"in",
"the",
"hex",
"string",
".",
"This",
"is",
"to",
"prevent... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/methods.go#L1927-L1939 | train |
btcsuite/btcwallet | internal/cfgutil/normalization.go | NormalizeAddress | func NormalizeAddress(addr string, defaultPort string) (hostport string, err error) {
// If the first SplitHostPort errors because of a missing port and not
// for an invalid host, add the port. If the second SplitHostPort
// fails, then a port is not missing and the original error should be
// returned.
host, port, origErr := net.SplitHostPort(addr)
if origErr == nil {
return net.JoinHostPort(host, port), nil
}
addr = net.JoinHostPort(addr, defaultPort)
_, _, err = net.SplitHostPort(addr)
if err != nil {
return "", origErr
}
return addr, nil
} | go | func NormalizeAddress(addr string, defaultPort string) (hostport string, err error) {
// If the first SplitHostPort errors because of a missing port and not
// for an invalid host, add the port. If the second SplitHostPort
// fails, then a port is not missing and the original error should be
// returned.
host, port, origErr := net.SplitHostPort(addr)
if origErr == nil {
return net.JoinHostPort(host, port), nil
}
addr = net.JoinHostPort(addr, defaultPort)
_, _, err = net.SplitHostPort(addr)
if err != nil {
return "", origErr
}
return addr, nil
} | [
"func",
"NormalizeAddress",
"(",
"addr",
"string",
",",
"defaultPort",
"string",
")",
"(",
"hostport",
"string",
",",
"err",
"error",
")",
"{",
"host",
",",
"port",
",",
"origErr",
":=",
"net",
".",
"SplitHostPort",
"(",
"addr",
")",
"\n",
"if",
"origErr... | // NormalizeAddress returns the normalized form of the address, adding a default
// port if necessary. An error is returned if the address, even without a port,
// is not valid. | [
"NormalizeAddress",
"returns",
"the",
"normalized",
"form",
"of",
"the",
"address",
"adding",
"a",
"default",
"port",
"if",
"necessary",
".",
"An",
"error",
"is",
"returned",
"if",
"the",
"address",
"even",
"without",
"a",
"port",
"is",
"not",
"valid",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/cfgutil/normalization.go#L12-L27 | train |
btcsuite/btcwallet | internal/cfgutil/normalization.go | NormalizeAddresses | func NormalizeAddresses(addrs []string, defaultPort string) ([]string, error) {
var (
normalized = make([]string, 0, len(addrs))
seenSet = make(map[string]struct{})
)
for _, addr := range addrs {
normalizedAddr, err := NormalizeAddress(addr, defaultPort)
if err != nil {
return nil, err
}
_, seen := seenSet[normalizedAddr]
if !seen {
normalized = append(normalized, normalizedAddr)
seenSet[normalizedAddr] = struct{}{}
}
}
return normalized, nil
} | go | func NormalizeAddresses(addrs []string, defaultPort string) ([]string, error) {
var (
normalized = make([]string, 0, len(addrs))
seenSet = make(map[string]struct{})
)
for _, addr := range addrs {
normalizedAddr, err := NormalizeAddress(addr, defaultPort)
if err != nil {
return nil, err
}
_, seen := seenSet[normalizedAddr]
if !seen {
normalized = append(normalized, normalizedAddr)
seenSet[normalizedAddr] = struct{}{}
}
}
return normalized, nil
} | [
"func",
"NormalizeAddresses",
"(",
"addrs",
"[",
"]",
"string",
",",
"defaultPort",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"var",
"(",
"normalized",
"=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"addrs",
... | // NormalizeAddresses returns a new slice with all the passed peer addresses
// normalized with the given default port, and all duplicates removed. | [
"NormalizeAddresses",
"returns",
"a",
"new",
"slice",
"with",
"all",
"the",
"passed",
"peer",
"addresses",
"normalized",
"with",
"the",
"given",
"default",
"port",
"and",
"all",
"duplicates",
"removed",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/cfgutil/normalization.go#L31-L50 | train |
btcsuite/btcwallet | chain/bitcoind_client.go | GetBestBlock | func (c *BitcoindClient) GetBestBlock() (*chainhash.Hash, int32, error) {
bcinfo, err := c.chainConn.client.GetBlockChainInfo()
if err != nil {
return nil, 0, err
}
hash, err := chainhash.NewHashFromStr(bcinfo.BestBlockHash)
if err != nil {
return nil, 0, err
}
return hash, bcinfo.Blocks, nil
} | go | func (c *BitcoindClient) GetBestBlock() (*chainhash.Hash, int32, error) {
bcinfo, err := c.chainConn.client.GetBlockChainInfo()
if err != nil {
return nil, 0, err
}
hash, err := chainhash.NewHashFromStr(bcinfo.BestBlockHash)
if err != nil {
return nil, 0, err
}
return hash, bcinfo.Blocks, nil
} | [
"func",
"(",
"c",
"*",
"BitcoindClient",
")",
"GetBestBlock",
"(",
")",
"(",
"*",
"chainhash",
".",
"Hash",
",",
"int32",
",",
"error",
")",
"{",
"bcinfo",
",",
"err",
":=",
"c",
".",
"chainConn",
".",
"client",
".",
"GetBlockChainInfo",
"(",
")",
"\... | // GetBestBlock returns the highest block known to bitcoind. | [
"GetBestBlock",
"returns",
"the",
"highest",
"block",
"known",
"to",
"bitcoind",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L121-L133 | train |
btcsuite/btcwallet | chain/bitcoind_client.go | GetBlockHeight | func (c *BitcoindClient) GetBlockHeight(hash *chainhash.Hash) (int32, error) {
header, err := c.chainConn.client.GetBlockHeaderVerbose(hash)
if err != nil {
return 0, err
}
return header.Height, nil
} | go | func (c *BitcoindClient) GetBlockHeight(hash *chainhash.Hash) (int32, error) {
header, err := c.chainConn.client.GetBlockHeaderVerbose(hash)
if err != nil {
return 0, err
}
return header.Height, nil
} | [
"func",
"(",
"c",
"*",
"BitcoindClient",
")",
"GetBlockHeight",
"(",
"hash",
"*",
"chainhash",
".",
"Hash",
")",
"(",
"int32",
",",
"error",
")",
"{",
"header",
",",
"err",
":=",
"c",
".",
"chainConn",
".",
"client",
".",
"GetBlockHeaderVerbose",
"(",
... | // GetBlockHeight returns the height for the hash, if known, or returns an
// error. | [
"GetBlockHeight",
"returns",
"the",
"height",
"for",
"the",
"hash",
"if",
"known",
"or",
"returns",
"an",
"error",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L137-L144 | train |
btcsuite/btcwallet | chain/bitcoind_client.go | GetBlock | func (c *BitcoindClient) GetBlock(hash *chainhash.Hash) (*wire.MsgBlock, error) {
return c.chainConn.client.GetBlock(hash)
} | go | func (c *BitcoindClient) GetBlock(hash *chainhash.Hash) (*wire.MsgBlock, error) {
return c.chainConn.client.GetBlock(hash)
} | [
"func",
"(",
"c",
"*",
"BitcoindClient",
")",
"GetBlock",
"(",
"hash",
"*",
"chainhash",
".",
"Hash",
")",
"(",
"*",
"wire",
".",
"MsgBlock",
",",
"error",
")",
"{",
"return",
"c",
".",
"chainConn",
".",
"client",
".",
"GetBlock",
"(",
"hash",
")",
... | // GetBlock returns a block from the hash. | [
"GetBlock",
"returns",
"a",
"block",
"from",
"the",
"hash",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L147-L149 | train |
btcsuite/btcwallet | chain/bitcoind_client.go | GetBlockVerbose | func (c *BitcoindClient) GetBlockVerbose(
hash *chainhash.Hash) (*btcjson.GetBlockVerboseResult, error) {
return c.chainConn.client.GetBlockVerbose(hash)
} | go | func (c *BitcoindClient) GetBlockVerbose(
hash *chainhash.Hash) (*btcjson.GetBlockVerboseResult, error) {
return c.chainConn.client.GetBlockVerbose(hash)
} | [
"func",
"(",
"c",
"*",
"BitcoindClient",
")",
"GetBlockVerbose",
"(",
"hash",
"*",
"chainhash",
".",
"Hash",
")",
"(",
"*",
"btcjson",
".",
"GetBlockVerboseResult",
",",
"error",
")",
"{",
"return",
"c",
".",
"chainConn",
".",
"client",
".",
"GetBlockVerbo... | // GetBlockVerbose returns a verbose block from the hash. | [
"GetBlockVerbose",
"returns",
"a",
"verbose",
"block",
"from",
"the",
"hash",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L152-L156 | train |
btcsuite/btcwallet | chain/bitcoind_client.go | GetBlockHash | func (c *BitcoindClient) GetBlockHash(height int64) (*chainhash.Hash, error) {
return c.chainConn.client.GetBlockHash(height)
} | go | func (c *BitcoindClient) GetBlockHash(height int64) (*chainhash.Hash, error) {
return c.chainConn.client.GetBlockHash(height)
} | [
"func",
"(",
"c",
"*",
"BitcoindClient",
")",
"GetBlockHash",
"(",
"height",
"int64",
")",
"(",
"*",
"chainhash",
".",
"Hash",
",",
"error",
")",
"{",
"return",
"c",
".",
"chainConn",
".",
"client",
".",
"GetBlockHash",
"(",
"height",
")",
"\n",
"}"
] | // GetBlockHash returns a block hash from the height. | [
"GetBlockHash",
"returns",
"a",
"block",
"hash",
"from",
"the",
"height",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L159-L161 | train |
btcsuite/btcwallet | chain/bitcoind_client.go | GetBlockHeader | func (c *BitcoindClient) GetBlockHeader(
hash *chainhash.Hash) (*wire.BlockHeader, error) {
return c.chainConn.client.GetBlockHeader(hash)
} | go | func (c *BitcoindClient) GetBlockHeader(
hash *chainhash.Hash) (*wire.BlockHeader, error) {
return c.chainConn.client.GetBlockHeader(hash)
} | [
"func",
"(",
"c",
"*",
"BitcoindClient",
")",
"GetBlockHeader",
"(",
"hash",
"*",
"chainhash",
".",
"Hash",
")",
"(",
"*",
"wire",
".",
"BlockHeader",
",",
"error",
")",
"{",
"return",
"c",
".",
"chainConn",
".",
"client",
".",
"GetBlockHeader",
"(",
"... | // GetBlockHeader returns a block header from the hash. | [
"GetBlockHeader",
"returns",
"a",
"block",
"header",
"from",
"the",
"hash",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L164-L168 | train |
btcsuite/btcwallet | chain/bitcoind_client.go | GetBlockHeaderVerbose | func (c *BitcoindClient) GetBlockHeaderVerbose(
hash *chainhash.Hash) (*btcjson.GetBlockHeaderVerboseResult, error) {
return c.chainConn.client.GetBlockHeaderVerbose(hash)
} | go | func (c *BitcoindClient) GetBlockHeaderVerbose(
hash *chainhash.Hash) (*btcjson.GetBlockHeaderVerboseResult, error) {
return c.chainConn.client.GetBlockHeaderVerbose(hash)
} | [
"func",
"(",
"c",
"*",
"BitcoindClient",
")",
"GetBlockHeaderVerbose",
"(",
"hash",
"*",
"chainhash",
".",
"Hash",
")",
"(",
"*",
"btcjson",
".",
"GetBlockHeaderVerboseResult",
",",
"error",
")",
"{",
"return",
"c",
".",
"chainConn",
".",
"client",
".",
"G... | // GetBlockHeaderVerbose returns a block header from the hash. | [
"GetBlockHeaderVerbose",
"returns",
"a",
"block",
"header",
"from",
"the",
"hash",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L171-L175 | train |
btcsuite/btcwallet | chain/bitcoind_client.go | GetRawTransactionVerbose | func (c *BitcoindClient) GetRawTransactionVerbose(
hash *chainhash.Hash) (*btcjson.TxRawResult, error) {
return c.chainConn.client.GetRawTransactionVerbose(hash)
} | go | func (c *BitcoindClient) GetRawTransactionVerbose(
hash *chainhash.Hash) (*btcjson.TxRawResult, error) {
return c.chainConn.client.GetRawTransactionVerbose(hash)
} | [
"func",
"(",
"c",
"*",
"BitcoindClient",
")",
"GetRawTransactionVerbose",
"(",
"hash",
"*",
"chainhash",
".",
"Hash",
")",
"(",
"*",
"btcjson",
".",
"TxRawResult",
",",
"error",
")",
"{",
"return",
"c",
".",
"chainConn",
".",
"client",
".",
"GetRawTransact... | // GetRawTransactionVerbose returns a transaction from the tx hash. | [
"GetRawTransactionVerbose",
"returns",
"a",
"transaction",
"from",
"the",
"tx",
"hash",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L178-L182 | train |
btcsuite/btcwallet | chain/bitcoind_client.go | GetTxOut | func (c *BitcoindClient) GetTxOut(txHash *chainhash.Hash, index uint32,
mempool bool) (*btcjson.GetTxOutResult, error) {
return c.chainConn.client.GetTxOut(txHash, index, mempool)
} | go | func (c *BitcoindClient) GetTxOut(txHash *chainhash.Hash, index uint32,
mempool bool) (*btcjson.GetTxOutResult, error) {
return c.chainConn.client.GetTxOut(txHash, index, mempool)
} | [
"func",
"(",
"c",
"*",
"BitcoindClient",
")",
"GetTxOut",
"(",
"txHash",
"*",
"chainhash",
".",
"Hash",
",",
"index",
"uint32",
",",
"mempool",
"bool",
")",
"(",
"*",
"btcjson",
".",
"GetTxOutResult",
",",
"error",
")",
"{",
"return",
"c",
".",
"chainC... | // GetTxOut returns a txout from the outpoint info provided. | [
"GetTxOut",
"returns",
"a",
"txout",
"from",
"the",
"outpoint",
"info",
"provided",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L185-L189 | train |
btcsuite/btcwallet | chain/bitcoind_client.go | SendRawTransaction | func (c *BitcoindClient) SendRawTransaction(tx *wire.MsgTx,
allowHighFees bool) (*chainhash.Hash, error) {
return c.chainConn.client.SendRawTransaction(tx, allowHighFees)
} | go | func (c *BitcoindClient) SendRawTransaction(tx *wire.MsgTx,
allowHighFees bool) (*chainhash.Hash, error) {
return c.chainConn.client.SendRawTransaction(tx, allowHighFees)
} | [
"func",
"(",
"c",
"*",
"BitcoindClient",
")",
"SendRawTransaction",
"(",
"tx",
"*",
"wire",
".",
"MsgTx",
",",
"allowHighFees",
"bool",
")",
"(",
"*",
"chainhash",
".",
"Hash",
",",
"error",
")",
"{",
"return",
"c",
".",
"chainConn",
".",
"client",
"."... | // SendRawTransaction sends a raw transaction via bitcoind. | [
"SendRawTransaction",
"sends",
"a",
"raw",
"transaction",
"via",
"bitcoind",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L192-L196 | train |
btcsuite/btcwallet | chain/bitcoind_client.go | NotifySpent | func (c *BitcoindClient) NotifySpent(outPoints []*wire.OutPoint) error {
c.NotifyBlocks()
select {
case c.rescanUpdate <- outPoints:
case <-c.quit:
return ErrBitcoindClientShuttingDown
}
return nil
} | go | func (c *BitcoindClient) NotifySpent(outPoints []*wire.OutPoint) error {
c.NotifyBlocks()
select {
case c.rescanUpdate <- outPoints:
case <-c.quit:
return ErrBitcoindClientShuttingDown
}
return nil
} | [
"func",
"(",
"c",
"*",
"BitcoindClient",
")",
"NotifySpent",
"(",
"outPoints",
"[",
"]",
"*",
"wire",
".",
"OutPoint",
")",
"error",
"{",
"c",
".",
"NotifyBlocks",
"(",
")",
"\n",
"select",
"{",
"case",
"c",
".",
"rescanUpdate",
"<-",
"outPoints",
":",... | // NotifySpent allows the chain backend to notify the caller whenever a
// transaction spends any of the given outpoints. | [
"NotifySpent",
"allows",
"the",
"chain",
"backend",
"to",
"notify",
"the",
"caller",
"whenever",
"a",
"transaction",
"spends",
"any",
"of",
"the",
"given",
"outpoints",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L223-L233 | train |
btcsuite/btcwallet | chain/bitcoind_client.go | NotifyTx | func (c *BitcoindClient) NotifyTx(txids []chainhash.Hash) error {
c.NotifyBlocks()
select {
case c.rescanUpdate <- txids:
case <-c.quit:
return ErrBitcoindClientShuttingDown
}
return nil
} | go | func (c *BitcoindClient) NotifyTx(txids []chainhash.Hash) error {
c.NotifyBlocks()
select {
case c.rescanUpdate <- txids:
case <-c.quit:
return ErrBitcoindClientShuttingDown
}
return nil
} | [
"func",
"(",
"c",
"*",
"BitcoindClient",
")",
"NotifyTx",
"(",
"txids",
"[",
"]",
"chainhash",
".",
"Hash",
")",
"error",
"{",
"c",
".",
"NotifyBlocks",
"(",
")",
"\n",
"select",
"{",
"case",
"c",
".",
"rescanUpdate",
"<-",
"txids",
":",
"case",
"<-"... | // NotifyTx allows the chain backend to notify the caller whenever any of the
// given transactions confirm within the chain. | [
"NotifyTx",
"allows",
"the",
"chain",
"backend",
"to",
"notify",
"the",
"caller",
"whenever",
"any",
"of",
"the",
"given",
"transactions",
"confirm",
"within",
"the",
"chain",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L237-L247 | train |
btcsuite/btcwallet | chain/bitcoind_client.go | Rescan | func (c *BitcoindClient) Rescan(blockHash *chainhash.Hash,
addresses []btcutil.Address, outPoints map[wire.OutPoint]btcutil.Address) error {
// A block hash is required to use as the starting point of the rescan.
if blockHash == nil {
return errors.New("rescan requires a starting block hash")
}
// We'll then update our filters with the given outpoints and addresses.
select {
case c.rescanUpdate <- addresses:
case <-c.quit:
return ErrBitcoindClientShuttingDown
}
select {
case c.rescanUpdate <- outPoints:
case <-c.quit:
return ErrBitcoindClientShuttingDown
}
// Once the filters have been updated, we can begin the rescan.
select {
case c.rescanUpdate <- *blockHash:
case <-c.quit:
return ErrBitcoindClientShuttingDown
}
return nil
} | go | func (c *BitcoindClient) Rescan(blockHash *chainhash.Hash,
addresses []btcutil.Address, outPoints map[wire.OutPoint]btcutil.Address) error {
// A block hash is required to use as the starting point of the rescan.
if blockHash == nil {
return errors.New("rescan requires a starting block hash")
}
// We'll then update our filters with the given outpoints and addresses.
select {
case c.rescanUpdate <- addresses:
case <-c.quit:
return ErrBitcoindClientShuttingDown
}
select {
case c.rescanUpdate <- outPoints:
case <-c.quit:
return ErrBitcoindClientShuttingDown
}
// Once the filters have been updated, we can begin the rescan.
select {
case c.rescanUpdate <- *blockHash:
case <-c.quit:
return ErrBitcoindClientShuttingDown
}
return nil
} | [
"func",
"(",
"c",
"*",
"BitcoindClient",
")",
"Rescan",
"(",
"blockHash",
"*",
"chainhash",
".",
"Hash",
",",
"addresses",
"[",
"]",
"btcutil",
".",
"Address",
",",
"outPoints",
"map",
"[",
"wire",
".",
"OutPoint",
"]",
"btcutil",
".",
"Address",
")",
... | // Rescan rescans from the block with the given hash until the current block,
// after adding the passed addresses and outpoints to the client's watch list. | [
"Rescan",
"rescans",
"from",
"the",
"block",
"with",
"the",
"given",
"hash",
"until",
"the",
"current",
"block",
"after",
"adding",
"the",
"passed",
"addresses",
"and",
"outpoints",
"to",
"the",
"client",
"s",
"watch",
"list",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L360-L389 | train |
btcsuite/btcwallet | chain/bitcoind_client.go | onBlockConnected | func (c *BitcoindClient) onBlockConnected(hash *chainhash.Hash, height int32,
timestamp time.Time) {
if c.shouldNotifyBlocks() {
select {
case c.notificationQueue.ChanIn() <- BlockConnected{
Block: wtxmgr.Block{
Hash: *hash,
Height: height,
},
Time: timestamp,
}:
case <-c.quit:
}
}
} | go | func (c *BitcoindClient) onBlockConnected(hash *chainhash.Hash, height int32,
timestamp time.Time) {
if c.shouldNotifyBlocks() {
select {
case c.notificationQueue.ChanIn() <- BlockConnected{
Block: wtxmgr.Block{
Hash: *hash,
Height: height,
},
Time: timestamp,
}:
case <-c.quit:
}
}
} | [
"func",
"(",
"c",
"*",
"BitcoindClient",
")",
"onBlockConnected",
"(",
"hash",
"*",
"chainhash",
".",
"Hash",
",",
"height",
"int32",
",",
"timestamp",
"time",
".",
"Time",
")",
"{",
"if",
"c",
".",
"shouldNotifyBlocks",
"(",
")",
"{",
"select",
"{",
"... | // onBlockConnected is a callback that's executed whenever a new block has been
// detected. This will queue a BlockConnected notification to the caller. | [
"onBlockConnected",
"is",
"a",
"callback",
"that",
"s",
"executed",
"whenever",
"a",
"new",
"block",
"has",
"been",
"detected",
".",
"This",
"will",
"queue",
"a",
"BlockConnected",
"notification",
"to",
"the",
"caller",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L623-L638 | train |
btcsuite/btcwallet | chain/bitcoind_client.go | onFilteredBlockConnected | func (c *BitcoindClient) onFilteredBlockConnected(height int32,
header *wire.BlockHeader, relevantTxs []*wtxmgr.TxRecord) {
if c.shouldNotifyBlocks() {
select {
case c.notificationQueue.ChanIn() <- FilteredBlockConnected{
Block: &wtxmgr.BlockMeta{
Block: wtxmgr.Block{
Hash: header.BlockHash(),
Height: height,
},
Time: header.Timestamp,
},
RelevantTxs: relevantTxs,
}:
case <-c.quit:
}
}
} | go | func (c *BitcoindClient) onFilteredBlockConnected(height int32,
header *wire.BlockHeader, relevantTxs []*wtxmgr.TxRecord) {
if c.shouldNotifyBlocks() {
select {
case c.notificationQueue.ChanIn() <- FilteredBlockConnected{
Block: &wtxmgr.BlockMeta{
Block: wtxmgr.Block{
Hash: header.BlockHash(),
Height: height,
},
Time: header.Timestamp,
},
RelevantTxs: relevantTxs,
}:
case <-c.quit:
}
}
} | [
"func",
"(",
"c",
"*",
"BitcoindClient",
")",
"onFilteredBlockConnected",
"(",
"height",
"int32",
",",
"header",
"*",
"wire",
".",
"BlockHeader",
",",
"relevantTxs",
"[",
"]",
"*",
"wtxmgr",
".",
"TxRecord",
")",
"{",
"if",
"c",
".",
"shouldNotifyBlocks",
... | // onFilteredBlockConnected is an alternative callback that's executed whenever
// a new block has been detected. It serves the same purpose as
// onBlockConnected, but it also includes a list of the relevant transactions
// found within the block being connected. This will queue a
// FilteredBlockConnected notification to the caller. | [
"onFilteredBlockConnected",
"is",
"an",
"alternative",
"callback",
"that",
"s",
"executed",
"whenever",
"a",
"new",
"block",
"has",
"been",
"detected",
".",
"It",
"serves",
"the",
"same",
"purpose",
"as",
"onBlockConnected",
"but",
"it",
"also",
"includes",
"a",... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L645-L663 | train |
btcsuite/btcwallet | chain/bitcoind_client.go | onRelevantTx | func (c *BitcoindClient) onRelevantTx(tx *wtxmgr.TxRecord,
blockDetails *btcjson.BlockDetails) {
block, err := parseBlock(blockDetails)
if err != nil {
log.Errorf("Unable to send onRelevantTx notification, failed "+
"parse block: %v", err)
return
}
select {
case c.notificationQueue.ChanIn() <- RelevantTx{
TxRecord: tx,
Block: block,
}:
case <-c.quit:
}
} | go | func (c *BitcoindClient) onRelevantTx(tx *wtxmgr.TxRecord,
blockDetails *btcjson.BlockDetails) {
block, err := parseBlock(blockDetails)
if err != nil {
log.Errorf("Unable to send onRelevantTx notification, failed "+
"parse block: %v", err)
return
}
select {
case c.notificationQueue.ChanIn() <- RelevantTx{
TxRecord: tx,
Block: block,
}:
case <-c.quit:
}
} | [
"func",
"(",
"c",
"*",
"BitcoindClient",
")",
"onRelevantTx",
"(",
"tx",
"*",
"wtxmgr",
".",
"TxRecord",
",",
"blockDetails",
"*",
"btcjson",
".",
"BlockDetails",
")",
"{",
"block",
",",
"err",
":=",
"parseBlock",
"(",
"blockDetails",
")",
"\n",
"if",
"e... | // onRelevantTx is a callback that's executed whenever a transaction is relevant
// to the caller. This means that the transaction matched a specific item in the
// client's different filters. This will queue a RelevantTx notification to the
// caller. | [
"onRelevantTx",
"is",
"a",
"callback",
"that",
"s",
"executed",
"whenever",
"a",
"transaction",
"is",
"relevant",
"to",
"the",
"caller",
".",
"This",
"means",
"that",
"the",
"transaction",
"matched",
"a",
"specific",
"item",
"in",
"the",
"client",
"s",
"diff... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_client.go#L689-L706 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.