repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
bradfitz/gomemcache
memcache/selector.go
SetServers
func (ss *ServerList) SetServers(servers ...string) error { naddr := make([]net.Addr, len(servers)) for i, server := range servers { if strings.Contains(server, "/") { addr, err := net.ResolveUnixAddr("unix", server) if err != nil { return err } naddr[i] = newStaticAddr(addr) } else { tcpaddr, err := net.ResolveTCPAddr("tcp", server) if err != nil { return err } naddr[i] = newStaticAddr(tcpaddr) } } ss.mu.Lock() defer ss.mu.Unlock() ss.addrs = naddr return nil }
go
func (ss *ServerList) SetServers(servers ...string) error { naddr := make([]net.Addr, len(servers)) for i, server := range servers { if strings.Contains(server, "/") { addr, err := net.ResolveUnixAddr("unix", server) if err != nil { return err } naddr[i] = newStaticAddr(addr) } else { tcpaddr, err := net.ResolveTCPAddr("tcp", server) if err != nil { return err } naddr[i] = newStaticAddr(tcpaddr) } } ss.mu.Lock() defer ss.mu.Unlock() ss.addrs = naddr return nil }
[ "func", "(", "ss", "*", "ServerList", ")", "SetServers", "(", "servers", "...", "string", ")", "error", "{", "naddr", ":=", "make", "(", "[", "]", "net", ".", "Addr", ",", "len", "(", "servers", ")", ")", "\n", "for", "i", ",", "server", ":=", "range", "servers", "{", "if", "strings", ".", "Contains", "(", "server", ",", "\"", "\"", ")", "{", "addr", ",", "err", ":=", "net", ".", "ResolveUnixAddr", "(", "\"", "\"", ",", "server", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "naddr", "[", "i", "]", "=", "newStaticAddr", "(", "addr", ")", "\n", "}", "else", "{", "tcpaddr", ",", "err", ":=", "net", ".", "ResolveTCPAddr", "(", "\"", "\"", ",", "server", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "naddr", "[", "i", "]", "=", "newStaticAddr", "(", "tcpaddr", ")", "\n", "}", "\n", "}", "\n\n", "ss", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "ss", ".", "mu", ".", "Unlock", "(", ")", "\n", "ss", ".", "addrs", "=", "naddr", "\n", "return", "nil", "\n", "}" ]
// SetServers changes a ServerList's set of servers at runtime and is // safe for concurrent use by multiple goroutines. // // Each server is given equal weight. A server is given more weight // if it's listed multiple times. // // SetServers returns an error if any of the server names fail to // resolve. No attempt is made to connect to the server. If any error // is returned, no changes are made to the ServerList.
[ "SetServers", "changes", "a", "ServerList", "s", "set", "of", "servers", "at", "runtime", "and", "is", "safe", "for", "concurrent", "use", "by", "multiple", "goroutines", ".", "Each", "server", "is", "given", "equal", "weight", ".", "A", "server", "is", "given", "more", "weight", "if", "it", "s", "listed", "multiple", "times", ".", "SetServers", "returns", "an", "error", "if", "any", "of", "the", "server", "names", "fail", "to", "resolve", ".", "No", "attempt", "is", "made", "to", "connect", "to", "the", "server", ".", "If", "any", "error", "is", "returned", "no", "changes", "are", "made", "to", "the", "ServerList", "." ]
551aad21a6682b95329c1f5bd62ee5060d64f7e8
https://github.com/bradfitz/gomemcache/blob/551aad21a6682b95329c1f5bd62ee5060d64f7e8/memcache/selector.go#L68-L90
train
bradfitz/gomemcache
memcache/selector.go
Each
func (ss *ServerList) Each(f func(net.Addr) error) error { ss.mu.RLock() defer ss.mu.RUnlock() for _, a := range ss.addrs { if err := f(a); nil != err { return err } } return nil }
go
func (ss *ServerList) Each(f func(net.Addr) error) error { ss.mu.RLock() defer ss.mu.RUnlock() for _, a := range ss.addrs { if err := f(a); nil != err { return err } } return nil }
[ "func", "(", "ss", "*", "ServerList", ")", "Each", "(", "f", "func", "(", "net", ".", "Addr", ")", "error", ")", "error", "{", "ss", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "ss", ".", "mu", ".", "RUnlock", "(", ")", "\n", "for", "_", ",", "a", ":=", "range", "ss", ".", "addrs", "{", "if", "err", ":=", "f", "(", "a", ")", ";", "nil", "!=", "err", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Each iterates over each server calling the given function
[ "Each", "iterates", "over", "each", "server", "calling", "the", "given", "function" ]
551aad21a6682b95329c1f5bd62ee5060d64f7e8
https://github.com/bradfitz/gomemcache/blob/551aad21a6682b95329c1f5bd62ee5060d64f7e8/memcache/selector.go#L93-L102
train
bradfitz/gomemcache
memcache/memcache.go
resumableError
func resumableError(err error) bool { switch err { case ErrCacheMiss, ErrCASConflict, ErrNotStored, ErrMalformedKey: return true } return false }
go
func resumableError(err error) bool { switch err { case ErrCacheMiss, ErrCASConflict, ErrNotStored, ErrMalformedKey: return true } return false }
[ "func", "resumableError", "(", "err", "error", ")", "bool", "{", "switch", "err", "{", "case", "ErrCacheMiss", ",", "ErrCASConflict", ",", "ErrNotStored", ",", "ErrMalformedKey", ":", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// resumableError returns true if err is only a protocol-level cache error. // This is used to determine whether or not a server connection should // be re-used or not. If an error occurs, by default we don't reuse the // connection, unless it was just a cache error.
[ "resumableError", "returns", "true", "if", "err", "is", "only", "a", "protocol", "-", "level", "cache", "error", ".", "This", "is", "used", "to", "determine", "whether", "or", "not", "a", "server", "connection", "should", "be", "re", "-", "used", "or", "not", ".", "If", "an", "error", "occurs", "by", "default", "we", "don", "t", "reuse", "the", "connection", "unless", "it", "was", "just", "a", "cache", "error", "." ]
551aad21a6682b95329c1f5bd62ee5060d64f7e8
https://github.com/bradfitz/gomemcache/blob/551aad21a6682b95329c1f5bd62ee5060d64f7e8/memcache/memcache.go#L81-L87
train
bradfitz/gomemcache
memcache/memcache.go
Get
func (c *Client) Get(key string) (item *Item, err error) { err = c.withKeyAddr(key, func(addr net.Addr) error { return c.getFromAddr(addr, []string{key}, func(it *Item) { item = it }) }) if err == nil && item == nil { err = ErrCacheMiss } return }
go
func (c *Client) Get(key string) (item *Item, err error) { err = c.withKeyAddr(key, func(addr net.Addr) error { return c.getFromAddr(addr, []string{key}, func(it *Item) { item = it }) }) if err == nil && item == nil { err = ErrCacheMiss } return }
[ "func", "(", "c", "*", "Client", ")", "Get", "(", "key", "string", ")", "(", "item", "*", "Item", ",", "err", "error", ")", "{", "err", "=", "c", ".", "withKeyAddr", "(", "key", ",", "func", "(", "addr", "net", ".", "Addr", ")", "error", "{", "return", "c", ".", "getFromAddr", "(", "addr", ",", "[", "]", "string", "{", "key", "}", ",", "func", "(", "it", "*", "Item", ")", "{", "item", "=", "it", "}", ")", "\n", "}", ")", "\n", "if", "err", "==", "nil", "&&", "item", "==", "nil", "{", "err", "=", "ErrCacheMiss", "\n", "}", "\n", "return", "\n", "}" ]
// Get gets the item for the given key. ErrCacheMiss is returned for a // memcache cache miss. The key must be at most 250 bytes in length.
[ "Get", "gets", "the", "item", "for", "the", "given", "key", ".", "ErrCacheMiss", "is", "returned", "for", "a", "memcache", "cache", "miss", ".", "The", "key", "must", "be", "at", "most", "250", "bytes", "in", "length", "." ]
551aad21a6682b95329c1f5bd62ee5060d64f7e8
https://github.com/bradfitz/gomemcache/blob/551aad21a6682b95329c1f5bd62ee5060d64f7e8/memcache/memcache.go#L316-L324
train
bradfitz/gomemcache
memcache/memcache.go
Touch
func (c *Client) Touch(key string, seconds int32) (err error) { return c.withKeyAddr(key, func(addr net.Addr) error { return c.touchFromAddr(addr, []string{key}, seconds) }) }
go
func (c *Client) Touch(key string, seconds int32) (err error) { return c.withKeyAddr(key, func(addr net.Addr) error { return c.touchFromAddr(addr, []string{key}, seconds) }) }
[ "func", "(", "c", "*", "Client", ")", "Touch", "(", "key", "string", ",", "seconds", "int32", ")", "(", "err", "error", ")", "{", "return", "c", ".", "withKeyAddr", "(", "key", ",", "func", "(", "addr", "net", ".", "Addr", ")", "error", "{", "return", "c", ".", "touchFromAddr", "(", "addr", ",", "[", "]", "string", "{", "key", "}", ",", "seconds", ")", "\n", "}", ")", "\n", "}" ]
// Touch updates the expiry for the given key. The seconds parameter is either // a Unix timestamp or, if seconds is less than 1 month, the number of seconds // into the future at which time the item will expire. Zero means the item has // no expiration time. ErrCacheMiss is returned if the key is not in the cache. // The key must be at most 250 bytes in length.
[ "Touch", "updates", "the", "expiry", "for", "the", "given", "key", ".", "The", "seconds", "parameter", "is", "either", "a", "Unix", "timestamp", "or", "if", "seconds", "is", "less", "than", "1", "month", "the", "number", "of", "seconds", "into", "the", "future", "at", "which", "time", "the", "item", "will", "expire", ".", "Zero", "means", "the", "item", "has", "no", "expiration", "time", ".", "ErrCacheMiss", "is", "returned", "if", "the", "key", "is", "not", "in", "the", "cache", ".", "The", "key", "must", "be", "at", "most", "250", "bytes", "in", "length", "." ]
551aad21a6682b95329c1f5bd62ee5060d64f7e8
https://github.com/bradfitz/gomemcache/blob/551aad21a6682b95329c1f5bd62ee5060d64f7e8/memcache/memcache.go#L331-L335
train
bradfitz/gomemcache
memcache/memcache.go
flushAllFromAddr
func (c *Client) flushAllFromAddr(addr net.Addr) error { return c.withAddrRw(addr, func(rw *bufio.ReadWriter) error { if _, err := fmt.Fprintf(rw, "flush_all\r\n"); err != nil { return err } if err := rw.Flush(); err != nil { return err } line, err := rw.ReadSlice('\n') if err != nil { return err } switch { case bytes.Equal(line, resultOk): break default: return fmt.Errorf("memcache: unexpected response line from flush_all: %q", string(line)) } return nil }) }
go
func (c *Client) flushAllFromAddr(addr net.Addr) error { return c.withAddrRw(addr, func(rw *bufio.ReadWriter) error { if _, err := fmt.Fprintf(rw, "flush_all\r\n"); err != nil { return err } if err := rw.Flush(); err != nil { return err } line, err := rw.ReadSlice('\n') if err != nil { return err } switch { case bytes.Equal(line, resultOk): break default: return fmt.Errorf("memcache: unexpected response line from flush_all: %q", string(line)) } return nil }) }
[ "func", "(", "c", "*", "Client", ")", "flushAllFromAddr", "(", "addr", "net", ".", "Addr", ")", "error", "{", "return", "c", ".", "withAddrRw", "(", "addr", ",", "func", "(", "rw", "*", "bufio", ".", "ReadWriter", ")", "error", "{", "if", "_", ",", "err", ":=", "fmt", ".", "Fprintf", "(", "rw", ",", "\"", "\\r", "\\n", "\"", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "rw", ".", "Flush", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "line", ",", "err", ":=", "rw", ".", "ReadSlice", "(", "'\\n'", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "switch", "{", "case", "bytes", ".", "Equal", "(", "line", ",", "resultOk", ")", ":", "break", "\n", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "string", "(", "line", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "}" ]
// flushAllFromAddr send the flush_all command to the given addr
[ "flushAllFromAddr", "send", "the", "flush_all", "command", "to", "the", "given", "addr" ]
551aad21a6682b95329c1f5bd62ee5060d64f7e8
https://github.com/bradfitz/gomemcache/blob/551aad21a6682b95329c1f5bd62ee5060d64f7e8/memcache/memcache.go#L379-L399
train
bradfitz/gomemcache
memcache/memcache.go
GetMulti
func (c *Client) GetMulti(keys []string) (map[string]*Item, error) { var lk sync.Mutex m := make(map[string]*Item) addItemToMap := func(it *Item) { lk.Lock() defer lk.Unlock() m[it.Key] = it } keyMap := make(map[net.Addr][]string) for _, key := range keys { if !legalKey(key) { return nil, ErrMalformedKey } addr, err := c.selector.PickServer(key) if err != nil { return nil, err } keyMap[addr] = append(keyMap[addr], key) } ch := make(chan error, buffered) for addr, keys := range keyMap { go func(addr net.Addr, keys []string) { ch <- c.getFromAddr(addr, keys, addItemToMap) }(addr, keys) } var err error for _ = range keyMap { if ge := <-ch; ge != nil { err = ge } } return m, err }
go
func (c *Client) GetMulti(keys []string) (map[string]*Item, error) { var lk sync.Mutex m := make(map[string]*Item) addItemToMap := func(it *Item) { lk.Lock() defer lk.Unlock() m[it.Key] = it } keyMap := make(map[net.Addr][]string) for _, key := range keys { if !legalKey(key) { return nil, ErrMalformedKey } addr, err := c.selector.PickServer(key) if err != nil { return nil, err } keyMap[addr] = append(keyMap[addr], key) } ch := make(chan error, buffered) for addr, keys := range keyMap { go func(addr net.Addr, keys []string) { ch <- c.getFromAddr(addr, keys, addItemToMap) }(addr, keys) } var err error for _ = range keyMap { if ge := <-ch; ge != nil { err = ge } } return m, err }
[ "func", "(", "c", "*", "Client", ")", "GetMulti", "(", "keys", "[", "]", "string", ")", "(", "map", "[", "string", "]", "*", "Item", ",", "error", ")", "{", "var", "lk", "sync", ".", "Mutex", "\n", "m", ":=", "make", "(", "map", "[", "string", "]", "*", "Item", ")", "\n", "addItemToMap", ":=", "func", "(", "it", "*", "Item", ")", "{", "lk", ".", "Lock", "(", ")", "\n", "defer", "lk", ".", "Unlock", "(", ")", "\n", "m", "[", "it", ".", "Key", "]", "=", "it", "\n", "}", "\n\n", "keyMap", ":=", "make", "(", "map", "[", "net", ".", "Addr", "]", "[", "]", "string", ")", "\n", "for", "_", ",", "key", ":=", "range", "keys", "{", "if", "!", "legalKey", "(", "key", ")", "{", "return", "nil", ",", "ErrMalformedKey", "\n", "}", "\n", "addr", ",", "err", ":=", "c", ".", "selector", ".", "PickServer", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "keyMap", "[", "addr", "]", "=", "append", "(", "keyMap", "[", "addr", "]", ",", "key", ")", "\n", "}", "\n\n", "ch", ":=", "make", "(", "chan", "error", ",", "buffered", ")", "\n", "for", "addr", ",", "keys", ":=", "range", "keyMap", "{", "go", "func", "(", "addr", "net", ".", "Addr", ",", "keys", "[", "]", "string", ")", "{", "ch", "<-", "c", ".", "getFromAddr", "(", "addr", ",", "keys", ",", "addItemToMap", ")", "\n", "}", "(", "addr", ",", "keys", ")", "\n", "}", "\n\n", "var", "err", "error", "\n", "for", "_", "=", "range", "keyMap", "{", "if", "ge", ":=", "<-", "ch", ";", "ge", "!=", "nil", "{", "err", "=", "ge", "\n", "}", "\n", "}", "\n", "return", "m", ",", "err", "\n", "}" ]
// GetMulti is a batch version of Get. The returned map from keys to // items may have fewer elements than the input slice, due to memcache // cache misses. Each key must be at most 250 bytes in length. // If no error is returned, the returned map will also be non-nil.
[ "GetMulti", "is", "a", "batch", "version", "of", "Get", ".", "The", "returned", "map", "from", "keys", "to", "items", "may", "have", "fewer", "elements", "than", "the", "input", "slice", "due", "to", "memcache", "cache", "misses", ".", "Each", "key", "must", "be", "at", "most", "250", "bytes", "in", "length", ".", "If", "no", "error", "is", "returned", "the", "returned", "map", "will", "also", "be", "non", "-", "nil", "." ]
551aad21a6682b95329c1f5bd62ee5060d64f7e8
https://github.com/bradfitz/gomemcache/blob/551aad21a6682b95329c1f5bd62ee5060d64f7e8/memcache/memcache.go#L431-L466
train
bradfitz/gomemcache
memcache/memcache.go
parseGetResponse
func parseGetResponse(r *bufio.Reader, cb func(*Item)) error { for { line, err := r.ReadSlice('\n') if err != nil { return err } if bytes.Equal(line, resultEnd) { return nil } it := new(Item) size, err := scanGetResponseLine(line, it) if err != nil { return err } it.Value = make([]byte, size+2) _, err = io.ReadFull(r, it.Value) if err != nil { it.Value = nil return err } if !bytes.HasSuffix(it.Value, crlf) { it.Value = nil return fmt.Errorf("memcache: corrupt get result read") } it.Value = it.Value[:size] cb(it) } }
go
func parseGetResponse(r *bufio.Reader, cb func(*Item)) error { for { line, err := r.ReadSlice('\n') if err != nil { return err } if bytes.Equal(line, resultEnd) { return nil } it := new(Item) size, err := scanGetResponseLine(line, it) if err != nil { return err } it.Value = make([]byte, size+2) _, err = io.ReadFull(r, it.Value) if err != nil { it.Value = nil return err } if !bytes.HasSuffix(it.Value, crlf) { it.Value = nil return fmt.Errorf("memcache: corrupt get result read") } it.Value = it.Value[:size] cb(it) } }
[ "func", "parseGetResponse", "(", "r", "*", "bufio", ".", "Reader", ",", "cb", "func", "(", "*", "Item", ")", ")", "error", "{", "for", "{", "line", ",", "err", ":=", "r", ".", "ReadSlice", "(", "'\\n'", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "bytes", ".", "Equal", "(", "line", ",", "resultEnd", ")", "{", "return", "nil", "\n", "}", "\n", "it", ":=", "new", "(", "Item", ")", "\n", "size", ",", "err", ":=", "scanGetResponseLine", "(", "line", ",", "it", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "it", ".", "Value", "=", "make", "(", "[", "]", "byte", ",", "size", "+", "2", ")", "\n", "_", ",", "err", "=", "io", ".", "ReadFull", "(", "r", ",", "it", ".", "Value", ")", "\n", "if", "err", "!=", "nil", "{", "it", ".", "Value", "=", "nil", "\n", "return", "err", "\n", "}", "\n", "if", "!", "bytes", ".", "HasSuffix", "(", "it", ".", "Value", ",", "crlf", ")", "{", "it", ".", "Value", "=", "nil", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "it", ".", "Value", "=", "it", ".", "Value", "[", ":", "size", "]", "\n", "cb", "(", "it", ")", "\n", "}", "\n", "}" ]
// parseGetResponse reads a GET response from r and calls cb for each // read and allocated Item
[ "parseGetResponse", "reads", "a", "GET", "response", "from", "r", "and", "calls", "cb", "for", "each", "read", "and", "allocated", "Item" ]
551aad21a6682b95329c1f5bd62ee5060d64f7e8
https://github.com/bradfitz/gomemcache/blob/551aad21a6682b95329c1f5bd62ee5060d64f7e8/memcache/memcache.go#L470-L497
train
bradfitz/gomemcache
memcache/memcache.go
scanGetResponseLine
func scanGetResponseLine(line []byte, it *Item) (size int, err error) { pattern := "VALUE %s %d %d %d\r\n" dest := []interface{}{&it.Key, &it.Flags, &size, &it.casid} if bytes.Count(line, space) == 3 { pattern = "VALUE %s %d %d\r\n" dest = dest[:3] } n, err := fmt.Sscanf(string(line), pattern, dest...) if err != nil || n != len(dest) { return -1, fmt.Errorf("memcache: unexpected line in get response: %q", line) } return size, nil }
go
func scanGetResponseLine(line []byte, it *Item) (size int, err error) { pattern := "VALUE %s %d %d %d\r\n" dest := []interface{}{&it.Key, &it.Flags, &size, &it.casid} if bytes.Count(line, space) == 3 { pattern = "VALUE %s %d %d\r\n" dest = dest[:3] } n, err := fmt.Sscanf(string(line), pattern, dest...) if err != nil || n != len(dest) { return -1, fmt.Errorf("memcache: unexpected line in get response: %q", line) } return size, nil }
[ "func", "scanGetResponseLine", "(", "line", "[", "]", "byte", ",", "it", "*", "Item", ")", "(", "size", "int", ",", "err", "error", ")", "{", "pattern", ":=", "\"", "\\r", "\\n", "\"", "\n", "dest", ":=", "[", "]", "interface", "{", "}", "{", "&", "it", ".", "Key", ",", "&", "it", ".", "Flags", ",", "&", "size", ",", "&", "it", ".", "casid", "}", "\n", "if", "bytes", ".", "Count", "(", "line", ",", "space", ")", "==", "3", "{", "pattern", "=", "\"", "\\r", "\\n", "\"", "\n", "dest", "=", "dest", "[", ":", "3", "]", "\n", "}", "\n", "n", ",", "err", ":=", "fmt", ".", "Sscanf", "(", "string", "(", "line", ")", ",", "pattern", ",", "dest", "...", ")", "\n", "if", "err", "!=", "nil", "||", "n", "!=", "len", "(", "dest", ")", "{", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "line", ")", "\n", "}", "\n", "return", "size", ",", "nil", "\n", "}" ]
// scanGetResponseLine populates it and returns the declared size of the item. // It does not read the bytes of the item.
[ "scanGetResponseLine", "populates", "it", "and", "returns", "the", "declared", "size", "of", "the", "item", ".", "It", "does", "not", "read", "the", "bytes", "of", "the", "item", "." ]
551aad21a6682b95329c1f5bd62ee5060d64f7e8
https://github.com/bradfitz/gomemcache/blob/551aad21a6682b95329c1f5bd62ee5060d64f7e8/memcache/memcache.go#L501-L513
train
bradfitz/gomemcache
memcache/memcache.go
Set
func (c *Client) Set(item *Item) error { return c.onItem(item, (*Client).set) }
go
func (c *Client) Set(item *Item) error { return c.onItem(item, (*Client).set) }
[ "func", "(", "c", "*", "Client", ")", "Set", "(", "item", "*", "Item", ")", "error", "{", "return", "c", ".", "onItem", "(", "item", ",", "(", "*", "Client", ")", ".", "set", ")", "\n", "}" ]
// Set writes the given item, unconditionally.
[ "Set", "writes", "the", "given", "item", "unconditionally", "." ]
551aad21a6682b95329c1f5bd62ee5060d64f7e8
https://github.com/bradfitz/gomemcache/blob/551aad21a6682b95329c1f5bd62ee5060d64f7e8/memcache/memcache.go#L516-L518
train
bradfitz/gomemcache
memcache/memcache.go
Add
func (c *Client) Add(item *Item) error { return c.onItem(item, (*Client).add) }
go
func (c *Client) Add(item *Item) error { return c.onItem(item, (*Client).add) }
[ "func", "(", "c", "*", "Client", ")", "Add", "(", "item", "*", "Item", ")", "error", "{", "return", "c", ".", "onItem", "(", "item", ",", "(", "*", "Client", ")", ".", "add", ")", "\n", "}" ]
// Add writes the given item, if no value already exists for its // key. ErrNotStored is returned if that condition is not met.
[ "Add", "writes", "the", "given", "item", "if", "no", "value", "already", "exists", "for", "its", "key", ".", "ErrNotStored", "is", "returned", "if", "that", "condition", "is", "not", "met", "." ]
551aad21a6682b95329c1f5bd62ee5060d64f7e8
https://github.com/bradfitz/gomemcache/blob/551aad21a6682b95329c1f5bd62ee5060d64f7e8/memcache/memcache.go#L526-L528
train
bradfitz/gomemcache
memcache/memcache.go
CompareAndSwap
func (c *Client) CompareAndSwap(item *Item) error { return c.onItem(item, (*Client).cas) }
go
func (c *Client) CompareAndSwap(item *Item) error { return c.onItem(item, (*Client).cas) }
[ "func", "(", "c", "*", "Client", ")", "CompareAndSwap", "(", "item", "*", "Item", ")", "error", "{", "return", "c", ".", "onItem", "(", "item", ",", "(", "*", "Client", ")", ".", "cas", ")", "\n", "}" ]
// CompareAndSwap writes the given item that was previously returned // by Get, if the value was neither modified or evicted between the // Get and the CompareAndSwap calls. The item's Key should not change // between calls but all other item fields may differ. ErrCASConflict // is returned if the value was modified in between the // calls. ErrNotStored is returned if the value was evicted in between // the calls.
[ "CompareAndSwap", "writes", "the", "given", "item", "that", "was", "previously", "returned", "by", "Get", "if", "the", "value", "was", "neither", "modified", "or", "evicted", "between", "the", "Get", "and", "the", "CompareAndSwap", "calls", ".", "The", "item", "s", "Key", "should", "not", "change", "between", "calls", "but", "all", "other", "item", "fields", "may", "differ", ".", "ErrCASConflict", "is", "returned", "if", "the", "value", "was", "modified", "in", "between", "the", "calls", ".", "ErrNotStored", "is", "returned", "if", "the", "value", "was", "evicted", "in", "between", "the", "calls", "." ]
551aad21a6682b95329c1f5bd62ee5060d64f7e8
https://github.com/bradfitz/gomemcache/blob/551aad21a6682b95329c1f5bd62ee5060d64f7e8/memcache/memcache.go#L551-L553
train
bradfitz/gomemcache
memcache/memcache.go
Delete
func (c *Client) Delete(key string) error { return c.withKeyRw(key, func(rw *bufio.ReadWriter) error { return writeExpectf(rw, resultDeleted, "delete %s\r\n", key) }) }
go
func (c *Client) Delete(key string) error { return c.withKeyRw(key, func(rw *bufio.ReadWriter) error { return writeExpectf(rw, resultDeleted, "delete %s\r\n", key) }) }
[ "func", "(", "c", "*", "Client", ")", "Delete", "(", "key", "string", ")", "error", "{", "return", "c", ".", "withKeyRw", "(", "key", ",", "func", "(", "rw", "*", "bufio", ".", "ReadWriter", ")", "error", "{", "return", "writeExpectf", "(", "rw", ",", "resultDeleted", ",", "\"", "\\r", "\\n", "\"", ",", "key", ")", "\n", "}", ")", "\n", "}" ]
// Delete deletes the item with the provided key. The error ErrCacheMiss is // returned if the item didn't already exist in the cache.
[ "Delete", "deletes", "the", "item", "with", "the", "provided", "key", ".", "The", "error", "ErrCacheMiss", "is", "returned", "if", "the", "item", "didn", "t", "already", "exist", "in", "the", "cache", "." ]
551aad21a6682b95329c1f5bd62ee5060d64f7e8
https://github.com/bradfitz/gomemcache/blob/551aad21a6682b95329c1f5bd62ee5060d64f7e8/memcache/memcache.go#L634-L638
train
bradfitz/gomemcache
memcache/memcache.go
DeleteAll
func (c *Client) DeleteAll() error { return c.withKeyRw("", func(rw *bufio.ReadWriter) error { return writeExpectf(rw, resultDeleted, "flush_all\r\n") }) }
go
func (c *Client) DeleteAll() error { return c.withKeyRw("", func(rw *bufio.ReadWriter) error { return writeExpectf(rw, resultDeleted, "flush_all\r\n") }) }
[ "func", "(", "c", "*", "Client", ")", "DeleteAll", "(", ")", "error", "{", "return", "c", ".", "withKeyRw", "(", "\"", "\"", ",", "func", "(", "rw", "*", "bufio", ".", "ReadWriter", ")", "error", "{", "return", "writeExpectf", "(", "rw", ",", "resultDeleted", ",", "\"", "\\r", "\\n", "\"", ")", "\n", "}", ")", "\n", "}" ]
// DeleteAll deletes all items in the cache.
[ "DeleteAll", "deletes", "all", "items", "in", "the", "cache", "." ]
551aad21a6682b95329c1f5bd62ee5060d64f7e8
https://github.com/bradfitz/gomemcache/blob/551aad21a6682b95329c1f5bd62ee5060d64f7e8/memcache/memcache.go#L641-L645
train
segmentio/ksuid
set.go
String
func (set CompressedSet) String() string { b := bytes.Buffer{} b.WriteByte('[') set.writeTo(&b) b.WriteByte(']') return b.String() }
go
func (set CompressedSet) String() string { b := bytes.Buffer{} b.WriteByte('[') set.writeTo(&b) b.WriteByte(']') return b.String() }
[ "func", "(", "set", "CompressedSet", ")", "String", "(", ")", "string", "{", "b", ":=", "bytes", ".", "Buffer", "{", "}", "\n", "b", ".", "WriteByte", "(", "'['", ")", "\n", "set", ".", "writeTo", "(", "&", "b", ")", "\n", "b", ".", "WriteByte", "(", "']'", ")", "\n", "return", "b", ".", "String", "(", ")", "\n", "}" ]
// String satisfies the fmt.Stringer interface, returns a human-readable string // representation of the set.
[ "String", "satisfies", "the", "fmt", ".", "Stringer", "interface", "returns", "a", "human", "-", "readable", "string", "representation", "of", "the", "set", "." ]
7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8
https://github.com/segmentio/ksuid/blob/7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8/set.go#L20-L26
train
segmentio/ksuid
set.go
Compress
func Compress(ids ...KSUID) CompressedSet { c := 1 + byteLength + (len(ids) / 5) b := make([]byte, 0, c) return AppendCompressed(b, ids...) }
go
func Compress(ids ...KSUID) CompressedSet { c := 1 + byteLength + (len(ids) / 5) b := make([]byte, 0, c) return AppendCompressed(b, ids...) }
[ "func", "Compress", "(", "ids", "...", "KSUID", ")", "CompressedSet", "{", "c", ":=", "1", "+", "byteLength", "+", "(", "len", "(", "ids", ")", "/", "5", ")", "\n", "b", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "c", ")", "\n", "return", "AppendCompressed", "(", "b", ",", "ids", "...", ")", "\n", "}" ]
// Compress creates and returns a compressed set of KSUIDs from the list given // as arguments.
[ "Compress", "creates", "and", "returns", "a", "compressed", "set", "of", "KSUIDs", "from", "the", "list", "given", "as", "arguments", "." ]
7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8
https://github.com/segmentio/ksuid/blob/7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8/set.go#L54-L58
train
segmentio/ksuid
set.go
Next
func (it *CompressedSetIter) Next() bool { if it.seqlength != 0 { value := incr128(it.lastValue) it.KSUID = value.ksuid(it.timestamp) it.seqlength-- it.lastValue = value return true } if it.offset == len(it.content) { return false } b := it.content[it.offset] it.offset++ const mask = rawKSUID | timeDelta | payloadDelta | payloadRange tag := int(b) & mask cnt := int(b) & ^mask switch tag { case rawKSUID: off0 := it.offset off1 := off0 + byteLength copy(it.KSUID[:], it.content[off0:off1]) it.offset = off1 it.timestamp = it.KSUID.Timestamp() it.lastValue = uint128Payload(it.KSUID) case timeDelta: off0 := it.offset off1 := off0 + cnt off2 := off1 + payloadLengthInBytes it.timestamp += varint32(it.content[off0:off1]) binary.BigEndian.PutUint32(it.KSUID[:timestampLengthInBytes], it.timestamp) copy(it.KSUID[timestampLengthInBytes:], it.content[off1:off2]) it.offset = off2 it.lastValue = uint128Payload(it.KSUID) case payloadDelta: off0 := it.offset off1 := off0 + cnt delta := varint128(it.content[off0:off1]) value := add128(it.lastValue, delta) it.KSUID = value.ksuid(it.timestamp) it.offset = off1 it.lastValue = value case payloadRange: off0 := it.offset off1 := off0 + cnt value := incr128(it.lastValue) it.KSUID = value.ksuid(it.timestamp) it.seqlength = varint64(it.content[off0:off1]) it.offset = off1 it.seqlength-- it.lastValue = value default: panic("KSUID set iterator is reading malformed data") } return true }
go
func (it *CompressedSetIter) Next() bool { if it.seqlength != 0 { value := incr128(it.lastValue) it.KSUID = value.ksuid(it.timestamp) it.seqlength-- it.lastValue = value return true } if it.offset == len(it.content) { return false } b := it.content[it.offset] it.offset++ const mask = rawKSUID | timeDelta | payloadDelta | payloadRange tag := int(b) & mask cnt := int(b) & ^mask switch tag { case rawKSUID: off0 := it.offset off1 := off0 + byteLength copy(it.KSUID[:], it.content[off0:off1]) it.offset = off1 it.timestamp = it.KSUID.Timestamp() it.lastValue = uint128Payload(it.KSUID) case timeDelta: off0 := it.offset off1 := off0 + cnt off2 := off1 + payloadLengthInBytes it.timestamp += varint32(it.content[off0:off1]) binary.BigEndian.PutUint32(it.KSUID[:timestampLengthInBytes], it.timestamp) copy(it.KSUID[timestampLengthInBytes:], it.content[off1:off2]) it.offset = off2 it.lastValue = uint128Payload(it.KSUID) case payloadDelta: off0 := it.offset off1 := off0 + cnt delta := varint128(it.content[off0:off1]) value := add128(it.lastValue, delta) it.KSUID = value.ksuid(it.timestamp) it.offset = off1 it.lastValue = value case payloadRange: off0 := it.offset off1 := off0 + cnt value := incr128(it.lastValue) it.KSUID = value.ksuid(it.timestamp) it.seqlength = varint64(it.content[off0:off1]) it.offset = off1 it.seqlength-- it.lastValue = value default: panic("KSUID set iterator is reading malformed data") } return true }
[ "func", "(", "it", "*", "CompressedSetIter", ")", "Next", "(", ")", "bool", "{", "if", "it", ".", "seqlength", "!=", "0", "{", "value", ":=", "incr128", "(", "it", ".", "lastValue", ")", "\n", "it", ".", "KSUID", "=", "value", ".", "ksuid", "(", "it", ".", "timestamp", ")", "\n", "it", ".", "seqlength", "--", "\n", "it", ".", "lastValue", "=", "value", "\n", "return", "true", "\n", "}", "\n\n", "if", "it", ".", "offset", "==", "len", "(", "it", ".", "content", ")", "{", "return", "false", "\n", "}", "\n\n", "b", ":=", "it", ".", "content", "[", "it", ".", "offset", "]", "\n", "it", ".", "offset", "++", "\n\n", "const", "mask", "=", "rawKSUID", "|", "timeDelta", "|", "payloadDelta", "|", "payloadRange", "\n", "tag", ":=", "int", "(", "b", ")", "&", "mask", "\n", "cnt", ":=", "int", "(", "b", ")", "&", "^", "mask", "\n\n", "switch", "tag", "{", "case", "rawKSUID", ":", "off0", ":=", "it", ".", "offset", "\n", "off1", ":=", "off0", "+", "byteLength", "\n\n", "copy", "(", "it", ".", "KSUID", "[", ":", "]", ",", "it", ".", "content", "[", "off0", ":", "off1", "]", ")", "\n\n", "it", ".", "offset", "=", "off1", "\n", "it", ".", "timestamp", "=", "it", ".", "KSUID", ".", "Timestamp", "(", ")", "\n", "it", ".", "lastValue", "=", "uint128Payload", "(", "it", ".", "KSUID", ")", "\n\n", "case", "timeDelta", ":", "off0", ":=", "it", ".", "offset", "\n", "off1", ":=", "off0", "+", "cnt", "\n", "off2", ":=", "off1", "+", "payloadLengthInBytes", "\n\n", "it", ".", "timestamp", "+=", "varint32", "(", "it", ".", "content", "[", "off0", ":", "off1", "]", ")", "\n\n", "binary", ".", "BigEndian", ".", "PutUint32", "(", "it", ".", "KSUID", "[", ":", "timestampLengthInBytes", "]", ",", "it", ".", "timestamp", ")", "\n", "copy", "(", "it", ".", "KSUID", "[", "timestampLengthInBytes", ":", "]", ",", "it", ".", "content", "[", "off1", ":", "off2", "]", ")", "\n\n", "it", ".", "offset", "=", "off2", "\n", "it", ".", "lastValue", "=", "uint128Payload", "(", "it", ".", "KSUID", ")", "\n\n", "case", "payloadDelta", ":", "off0", ":=", "it", ".", "offset", "\n", "off1", ":=", "off0", "+", "cnt", "\n\n", "delta", ":=", "varint128", "(", "it", ".", "content", "[", "off0", ":", "off1", "]", ")", "\n", "value", ":=", "add128", "(", "it", ".", "lastValue", ",", "delta", ")", "\n\n", "it", ".", "KSUID", "=", "value", ".", "ksuid", "(", "it", ".", "timestamp", ")", "\n", "it", ".", "offset", "=", "off1", "\n", "it", ".", "lastValue", "=", "value", "\n\n", "case", "payloadRange", ":", "off0", ":=", "it", ".", "offset", "\n", "off1", ":=", "off0", "+", "cnt", "\n\n", "value", ":=", "incr128", "(", "it", ".", "lastValue", ")", "\n", "it", ".", "KSUID", "=", "value", ".", "ksuid", "(", "it", ".", "timestamp", ")", "\n", "it", ".", "seqlength", "=", "varint64", "(", "it", ".", "content", "[", "off0", ":", "off1", "]", ")", "\n", "it", ".", "offset", "=", "off1", "\n", "it", ".", "seqlength", "--", "\n", "it", ".", "lastValue", "=", "value", "\n\n", "default", ":", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "true", "\n", "}" ]
// Next moves the iterator forward, returning true if there a KSUID was found, // or false if the iterator as reached the end of the set it was created from.
[ "Next", "moves", "the", "iterator", "forward", "returning", "true", "if", "there", "a", "KSUID", "was", "found", "or", "false", "if", "the", "iterator", "as", "reached", "the", "end", "of", "the", "set", "it", "was", "created", "from", "." ]
7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8
https://github.com/segmentio/ksuid/blob/7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8/set.go#L272-L343
train
segmentio/ksuid
base62.go
base62Value
func base62Value(digit byte) byte { switch { case digit >= '0' && digit <= '9': return digit - '0' case digit >= 'A' && digit <= 'Z': return offsetUppercase + (digit - 'A') default: return offsetLowercase + (digit - 'a') } }
go
func base62Value(digit byte) byte { switch { case digit >= '0' && digit <= '9': return digit - '0' case digit >= 'A' && digit <= 'Z': return offsetUppercase + (digit - 'A') default: return offsetLowercase + (digit - 'a') } }
[ "func", "base62Value", "(", "digit", "byte", ")", "byte", "{", "switch", "{", "case", "digit", ">=", "'0'", "&&", "digit", "<=", "'9'", ":", "return", "digit", "-", "'0'", "\n", "case", "digit", ">=", "'A'", "&&", "digit", "<=", "'Z'", ":", "return", "offsetUppercase", "+", "(", "digit", "-", "'A'", ")", "\n", "default", ":", "return", "offsetLowercase", "+", "(", "digit", "-", "'a'", ")", "\n", "}", "\n", "}" ]
// Converts a base 62 byte into the number value that it represents.
[ "Converts", "a", "base", "62", "byte", "into", "the", "number", "value", "that", "it", "represents", "." ]
7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8
https://github.com/segmentio/ksuid/blob/7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8/base62.go#L18-L27
train
segmentio/ksuid
base62.go
fastEncodeBase62
func fastEncodeBase62(dst []byte, src []byte) { const srcBase = 4294967296 const dstBase = 62 // Split src into 5 4-byte words, this is where most of the efficiency comes // from because this is a O(N^2) algorithm, and we make N = N / 4 by working // on 32 bits at a time. parts := [5]uint32{ /* These is an inlined version of: binary.BigEndian.Uint32(src[0:4]), binary.BigEndian.Uint32(src[4:8]), binary.BigEndian.Uint32(src[8:12]), binary.BigEndian.Uint32(src[12:16]), binary.BigEndian.Uint32(src[16:20]), For some reason it gave better performance, may be caused by the bound check that the Uint32 function does. */ uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3]), uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7]), uint32(src[8])<<24 | uint32(src[9])<<16 | uint32(src[10])<<8 | uint32(src[11]), uint32(src[12])<<24 | uint32(src[13])<<16 | uint32(src[14])<<8 | uint32(src[15]), uint32(src[16])<<24 | uint32(src[17])<<16 | uint32(src[18])<<8 | uint32(src[19]), } n := len(dst) bp := parts[:] bq := [5]uint32{} for len(bp) != 0 { quotient := bq[:0] remainder := uint64(0) for _, c := range bp { value := uint64(c) + uint64(remainder)*srcBase digit := value / dstBase remainder = value % dstBase if len(quotient) != 0 || digit != 0 { quotient = append(quotient, uint32(digit)) } } // Writes at the end of the destination buffer because we computed the // lowest bits first. n-- dst[n] = base62Characters[remainder] bp = quotient } // Add padding at the head of the destination buffer for all bytes that were // not set. copy(dst[:n], zeroString) }
go
func fastEncodeBase62(dst []byte, src []byte) { const srcBase = 4294967296 const dstBase = 62 // Split src into 5 4-byte words, this is where most of the efficiency comes // from because this is a O(N^2) algorithm, and we make N = N / 4 by working // on 32 bits at a time. parts := [5]uint32{ /* These is an inlined version of: binary.BigEndian.Uint32(src[0:4]), binary.BigEndian.Uint32(src[4:8]), binary.BigEndian.Uint32(src[8:12]), binary.BigEndian.Uint32(src[12:16]), binary.BigEndian.Uint32(src[16:20]), For some reason it gave better performance, may be caused by the bound check that the Uint32 function does. */ uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3]), uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7]), uint32(src[8])<<24 | uint32(src[9])<<16 | uint32(src[10])<<8 | uint32(src[11]), uint32(src[12])<<24 | uint32(src[13])<<16 | uint32(src[14])<<8 | uint32(src[15]), uint32(src[16])<<24 | uint32(src[17])<<16 | uint32(src[18])<<8 | uint32(src[19]), } n := len(dst) bp := parts[:] bq := [5]uint32{} for len(bp) != 0 { quotient := bq[:0] remainder := uint64(0) for _, c := range bp { value := uint64(c) + uint64(remainder)*srcBase digit := value / dstBase remainder = value % dstBase if len(quotient) != 0 || digit != 0 { quotient = append(quotient, uint32(digit)) } } // Writes at the end of the destination buffer because we computed the // lowest bits first. n-- dst[n] = base62Characters[remainder] bp = quotient } // Add padding at the head of the destination buffer for all bytes that were // not set. copy(dst[:n], zeroString) }
[ "func", "fastEncodeBase62", "(", "dst", "[", "]", "byte", ",", "src", "[", "]", "byte", ")", "{", "const", "srcBase", "=", "4294967296", "\n", "const", "dstBase", "=", "62", "\n\n", "// Split src into 5 4-byte words, this is where most of the efficiency comes", "// from because this is a O(N^2) algorithm, and we make N = N / 4 by working", "// on 32 bits at a time.", "parts", ":=", "[", "5", "]", "uint32", "{", "/*\n\t\t\tThese is an inlined version of:\n\n\t\t\t binary.BigEndian.Uint32(src[0:4]),\n\t\t\t binary.BigEndian.Uint32(src[4:8]),\n\t\t\t binary.BigEndian.Uint32(src[8:12]),\n\t\t\t binary.BigEndian.Uint32(src[12:16]),\n\t\t\t binary.BigEndian.Uint32(src[16:20]),\n\n\t\t\tFor some reason it gave better performance, may be caused by the\n\t\t\tbound check that the Uint32 function does.\n\t\t*/", "uint32", "(", "src", "[", "0", "]", ")", "<<", "24", "|", "uint32", "(", "src", "[", "1", "]", ")", "<<", "16", "|", "uint32", "(", "src", "[", "2", "]", ")", "<<", "8", "|", "uint32", "(", "src", "[", "3", "]", ")", ",", "uint32", "(", "src", "[", "4", "]", ")", "<<", "24", "|", "uint32", "(", "src", "[", "5", "]", ")", "<<", "16", "|", "uint32", "(", "src", "[", "6", "]", ")", "<<", "8", "|", "uint32", "(", "src", "[", "7", "]", ")", ",", "uint32", "(", "src", "[", "8", "]", ")", "<<", "24", "|", "uint32", "(", "src", "[", "9", "]", ")", "<<", "16", "|", "uint32", "(", "src", "[", "10", "]", ")", "<<", "8", "|", "uint32", "(", "src", "[", "11", "]", ")", ",", "uint32", "(", "src", "[", "12", "]", ")", "<<", "24", "|", "uint32", "(", "src", "[", "13", "]", ")", "<<", "16", "|", "uint32", "(", "src", "[", "14", "]", ")", "<<", "8", "|", "uint32", "(", "src", "[", "15", "]", ")", ",", "uint32", "(", "src", "[", "16", "]", ")", "<<", "24", "|", "uint32", "(", "src", "[", "17", "]", ")", "<<", "16", "|", "uint32", "(", "src", "[", "18", "]", ")", "<<", "8", "|", "uint32", "(", "src", "[", "19", "]", ")", ",", "}", "\n\n", "n", ":=", "len", "(", "dst", ")", "\n", "bp", ":=", "parts", "[", ":", "]", "\n", "bq", ":=", "[", "5", "]", "uint32", "{", "}", "\n\n", "for", "len", "(", "bp", ")", "!=", "0", "{", "quotient", ":=", "bq", "[", ":", "0", "]", "\n", "remainder", ":=", "uint64", "(", "0", ")", "\n\n", "for", "_", ",", "c", ":=", "range", "bp", "{", "value", ":=", "uint64", "(", "c", ")", "+", "uint64", "(", "remainder", ")", "*", "srcBase", "\n", "digit", ":=", "value", "/", "dstBase", "\n", "remainder", "=", "value", "%", "dstBase", "\n\n", "if", "len", "(", "quotient", ")", "!=", "0", "||", "digit", "!=", "0", "{", "quotient", "=", "append", "(", "quotient", ",", "uint32", "(", "digit", ")", ")", "\n", "}", "\n", "}", "\n\n", "// Writes at the end of the destination buffer because we computed the", "// lowest bits first.", "n", "--", "\n", "dst", "[", "n", "]", "=", "base62Characters", "[", "remainder", "]", "\n", "bp", "=", "quotient", "\n", "}", "\n\n", "// Add padding at the head of the destination buffer for all bytes that were", "// not set.", "copy", "(", "dst", "[", ":", "n", "]", ",", "zeroString", ")", "\n", "}" ]
// This function encodes the base 62 representation of the src KSUID in binary // form into dst. // // In order to support a couple of optimizations the function assumes that src // is 20 bytes long and dst is 27 bytes long. // // Any unused bytes in dst will be set to the padding '0' byte.
[ "This", "function", "encodes", "the", "base", "62", "representation", "of", "the", "src", "KSUID", "in", "binary", "form", "into", "dst", ".", "In", "order", "to", "support", "a", "couple", "of", "optimizations", "the", "function", "assumes", "that", "src", "is", "20", "bytes", "long", "and", "dst", "is", "27", "bytes", "long", ".", "Any", "unused", "bytes", "in", "dst", "will", "be", "set", "to", "the", "padding", "0", "byte", "." ]
7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8
https://github.com/segmentio/ksuid/blob/7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8/base62.go#L36-L91
train
segmentio/ksuid
base62.go
fastAppendEncodeBase62
func fastAppendEncodeBase62(dst []byte, src []byte) []byte { dst = reserve(dst, stringEncodedLength) n := len(dst) fastEncodeBase62(dst[n:n+stringEncodedLength], src) return dst[:n+stringEncodedLength] }
go
func fastAppendEncodeBase62(dst []byte, src []byte) []byte { dst = reserve(dst, stringEncodedLength) n := len(dst) fastEncodeBase62(dst[n:n+stringEncodedLength], src) return dst[:n+stringEncodedLength] }
[ "func", "fastAppendEncodeBase62", "(", "dst", "[", "]", "byte", ",", "src", "[", "]", "byte", ")", "[", "]", "byte", "{", "dst", "=", "reserve", "(", "dst", ",", "stringEncodedLength", ")", "\n", "n", ":=", "len", "(", "dst", ")", "\n", "fastEncodeBase62", "(", "dst", "[", "n", ":", "n", "+", "stringEncodedLength", "]", ",", "src", ")", "\n", "return", "dst", "[", ":", "n", "+", "stringEncodedLength", "]", "\n", "}" ]
// This function appends the base 62 representation of the KSUID in src to dst, // and returns the extended byte slice. // The result is left-padded with '0' bytes to always append 27 bytes to the // destination buffer.
[ "This", "function", "appends", "the", "base", "62", "representation", "of", "the", "KSUID", "in", "src", "to", "dst", "and", "returns", "the", "extended", "byte", "slice", ".", "The", "result", "is", "left", "-", "padded", "with", "0", "bytes", "to", "always", "append", "27", "bytes", "to", "the", "destination", "buffer", "." ]
7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8
https://github.com/segmentio/ksuid/blob/7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8/base62.go#L97-L102
train
segmentio/ksuid
base62.go
fastDecodeBase62
func fastDecodeBase62(dst []byte, src []byte) error { const srcBase = 62 const dstBase = 4294967296 // This line helps BCE (Bounds Check Elimination). // It may be safely removed. _ = src[26] parts := [27]byte{ base62Value(src[0]), base62Value(src[1]), base62Value(src[2]), base62Value(src[3]), base62Value(src[4]), base62Value(src[5]), base62Value(src[6]), base62Value(src[7]), base62Value(src[8]), base62Value(src[9]), base62Value(src[10]), base62Value(src[11]), base62Value(src[12]), base62Value(src[13]), base62Value(src[14]), base62Value(src[15]), base62Value(src[16]), base62Value(src[17]), base62Value(src[18]), base62Value(src[19]), base62Value(src[20]), base62Value(src[21]), base62Value(src[22]), base62Value(src[23]), base62Value(src[24]), base62Value(src[25]), base62Value(src[26]), } n := len(dst) bp := parts[:] bq := [stringEncodedLength]byte{} for len(bp) > 0 { quotient := bq[:0] remainder := uint64(0) for _, c := range bp { value := uint64(c) + uint64(remainder)*srcBase digit := value / dstBase remainder = value % dstBase if len(quotient) != 0 || digit != 0 { quotient = append(quotient, byte(digit)) } } if n < 4 { return errShortBuffer } dst[n-4] = byte(remainder >> 24) dst[n-3] = byte(remainder >> 16) dst[n-2] = byte(remainder >> 8) dst[n-1] = byte(remainder) n -= 4 bp = quotient } var zero [20]byte copy(dst[:n], zero[:]) return nil }
go
func fastDecodeBase62(dst []byte, src []byte) error { const srcBase = 62 const dstBase = 4294967296 // This line helps BCE (Bounds Check Elimination). // It may be safely removed. _ = src[26] parts := [27]byte{ base62Value(src[0]), base62Value(src[1]), base62Value(src[2]), base62Value(src[3]), base62Value(src[4]), base62Value(src[5]), base62Value(src[6]), base62Value(src[7]), base62Value(src[8]), base62Value(src[9]), base62Value(src[10]), base62Value(src[11]), base62Value(src[12]), base62Value(src[13]), base62Value(src[14]), base62Value(src[15]), base62Value(src[16]), base62Value(src[17]), base62Value(src[18]), base62Value(src[19]), base62Value(src[20]), base62Value(src[21]), base62Value(src[22]), base62Value(src[23]), base62Value(src[24]), base62Value(src[25]), base62Value(src[26]), } n := len(dst) bp := parts[:] bq := [stringEncodedLength]byte{} for len(bp) > 0 { quotient := bq[:0] remainder := uint64(0) for _, c := range bp { value := uint64(c) + uint64(remainder)*srcBase digit := value / dstBase remainder = value % dstBase if len(quotient) != 0 || digit != 0 { quotient = append(quotient, byte(digit)) } } if n < 4 { return errShortBuffer } dst[n-4] = byte(remainder >> 24) dst[n-3] = byte(remainder >> 16) dst[n-2] = byte(remainder >> 8) dst[n-1] = byte(remainder) n -= 4 bp = quotient } var zero [20]byte copy(dst[:n], zero[:]) return nil }
[ "func", "fastDecodeBase62", "(", "dst", "[", "]", "byte", ",", "src", "[", "]", "byte", ")", "error", "{", "const", "srcBase", "=", "62", "\n", "const", "dstBase", "=", "4294967296", "\n\n", "// This line helps BCE (Bounds Check Elimination).", "// It may be safely removed.", "_", "=", "src", "[", "26", "]", "\n\n", "parts", ":=", "[", "27", "]", "byte", "{", "base62Value", "(", "src", "[", "0", "]", ")", ",", "base62Value", "(", "src", "[", "1", "]", ")", ",", "base62Value", "(", "src", "[", "2", "]", ")", ",", "base62Value", "(", "src", "[", "3", "]", ")", ",", "base62Value", "(", "src", "[", "4", "]", ")", ",", "base62Value", "(", "src", "[", "5", "]", ")", ",", "base62Value", "(", "src", "[", "6", "]", ")", ",", "base62Value", "(", "src", "[", "7", "]", ")", ",", "base62Value", "(", "src", "[", "8", "]", ")", ",", "base62Value", "(", "src", "[", "9", "]", ")", ",", "base62Value", "(", "src", "[", "10", "]", ")", ",", "base62Value", "(", "src", "[", "11", "]", ")", ",", "base62Value", "(", "src", "[", "12", "]", ")", ",", "base62Value", "(", "src", "[", "13", "]", ")", ",", "base62Value", "(", "src", "[", "14", "]", ")", ",", "base62Value", "(", "src", "[", "15", "]", ")", ",", "base62Value", "(", "src", "[", "16", "]", ")", ",", "base62Value", "(", "src", "[", "17", "]", ")", ",", "base62Value", "(", "src", "[", "18", "]", ")", ",", "base62Value", "(", "src", "[", "19", "]", ")", ",", "base62Value", "(", "src", "[", "20", "]", ")", ",", "base62Value", "(", "src", "[", "21", "]", ")", ",", "base62Value", "(", "src", "[", "22", "]", ")", ",", "base62Value", "(", "src", "[", "23", "]", ")", ",", "base62Value", "(", "src", "[", "24", "]", ")", ",", "base62Value", "(", "src", "[", "25", "]", ")", ",", "base62Value", "(", "src", "[", "26", "]", ")", ",", "}", "\n\n", "n", ":=", "len", "(", "dst", ")", "\n", "bp", ":=", "parts", "[", ":", "]", "\n", "bq", ":=", "[", "stringEncodedLength", "]", "byte", "{", "}", "\n\n", "for", "len", "(", "bp", ")", ">", "0", "{", "quotient", ":=", "bq", "[", ":", "0", "]", "\n", "remainder", ":=", "uint64", "(", "0", ")", "\n\n", "for", "_", ",", "c", ":=", "range", "bp", "{", "value", ":=", "uint64", "(", "c", ")", "+", "uint64", "(", "remainder", ")", "*", "srcBase", "\n", "digit", ":=", "value", "/", "dstBase", "\n", "remainder", "=", "value", "%", "dstBase", "\n\n", "if", "len", "(", "quotient", ")", "!=", "0", "||", "digit", "!=", "0", "{", "quotient", "=", "append", "(", "quotient", ",", "byte", "(", "digit", ")", ")", "\n", "}", "\n", "}", "\n\n", "if", "n", "<", "4", "{", "return", "errShortBuffer", "\n", "}", "\n\n", "dst", "[", "n", "-", "4", "]", "=", "byte", "(", "remainder", ">>", "24", ")", "\n", "dst", "[", "n", "-", "3", "]", "=", "byte", "(", "remainder", ">>", "16", ")", "\n", "dst", "[", "n", "-", "2", "]", "=", "byte", "(", "remainder", ">>", "8", ")", "\n", "dst", "[", "n", "-", "1", "]", "=", "byte", "(", "remainder", ")", "\n", "n", "-=", "4", "\n", "bp", "=", "quotient", "\n", "}", "\n\n", "var", "zero", "[", "20", "]", "byte", "\n", "copy", "(", "dst", "[", ":", "n", "]", ",", "zero", "[", ":", "]", ")", "\n", "return", "nil", "\n", "}" ]
// This function decodes the base 62 representation of the src KSUID to the // binary form into dst. // // In order to support a couple of optimizations the function assumes that src // is 27 bytes long and dst is 20 bytes long. // // Any unused bytes in dst will be set to zero.
[ "This", "function", "decodes", "the", "base", "62", "representation", "of", "the", "src", "KSUID", "to", "the", "binary", "form", "into", "dst", ".", "In", "order", "to", "support", "a", "couple", "of", "optimizations", "the", "function", "assumes", "that", "src", "is", "27", "bytes", "long", "and", "dst", "is", "20", "bytes", "long", ".", "Any", "unused", "bytes", "in", "dst", "will", "be", "set", "to", "zero", "." ]
7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8
https://github.com/segmentio/ksuid/blob/7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8/base62.go#L111-L184
train
segmentio/ksuid
base62.go
fastAppendDecodeBase62
func fastAppendDecodeBase62(dst []byte, src []byte) []byte { dst = reserve(dst, byteLength) n := len(dst) fastDecodeBase62(dst[n:n+byteLength], src) return dst[:n+byteLength] }
go
func fastAppendDecodeBase62(dst []byte, src []byte) []byte { dst = reserve(dst, byteLength) n := len(dst) fastDecodeBase62(dst[n:n+byteLength], src) return dst[:n+byteLength] }
[ "func", "fastAppendDecodeBase62", "(", "dst", "[", "]", "byte", ",", "src", "[", "]", "byte", ")", "[", "]", "byte", "{", "dst", "=", "reserve", "(", "dst", ",", "byteLength", ")", "\n", "n", ":=", "len", "(", "dst", ")", "\n", "fastDecodeBase62", "(", "dst", "[", "n", ":", "n", "+", "byteLength", "]", ",", "src", ")", "\n", "return", "dst", "[", ":", "n", "+", "byteLength", "]", "\n", "}" ]
// This function appends the base 62 decoded version of src into dst.
[ "This", "function", "appends", "the", "base", "62", "decoded", "version", "of", "src", "into", "dst", "." ]
7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8
https://github.com/segmentio/ksuid/blob/7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8/base62.go#L187-L192
train
segmentio/ksuid
base62.go
reserve
func reserve(dst []byte, nbytes int) []byte { c := cap(dst) n := len(dst) if avail := c - n; avail < nbytes { c *= 2 if (c - n) < nbytes { c = n + nbytes } b := make([]byte, n, c) copy(b, dst) dst = b } return dst }
go
func reserve(dst []byte, nbytes int) []byte { c := cap(dst) n := len(dst) if avail := c - n; avail < nbytes { c *= 2 if (c - n) < nbytes { c = n + nbytes } b := make([]byte, n, c) copy(b, dst) dst = b } return dst }
[ "func", "reserve", "(", "dst", "[", "]", "byte", ",", "nbytes", "int", ")", "[", "]", "byte", "{", "c", ":=", "cap", "(", "dst", ")", "\n", "n", ":=", "len", "(", "dst", ")", "\n\n", "if", "avail", ":=", "c", "-", "n", ";", "avail", "<", "nbytes", "{", "c", "*=", "2", "\n", "if", "(", "c", "-", "n", ")", "<", "nbytes", "{", "c", "=", "n", "+", "nbytes", "\n", "}", "\n", "b", ":=", "make", "(", "[", "]", "byte", ",", "n", ",", "c", ")", "\n", "copy", "(", "b", ",", "dst", ")", "\n", "dst", "=", "b", "\n", "}", "\n\n", "return", "dst", "\n", "}" ]
// Ensures that at least nbytes are available in the remaining capacity of the // destination slice, if not, a new copy is made and returned by the function.
[ "Ensures", "that", "at", "least", "nbytes", "are", "available", "in", "the", "remaining", "capacity", "of", "the", "destination", "slice", "if", "not", "a", "new", "copy", "is", "made", "and", "returned", "by", "the", "function", "." ]
7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8
https://github.com/segmentio/ksuid/blob/7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8/base62.go#L196-L211
train
segmentio/ksuid
ksuid.go
Set
func (i *KSUID) Set(s string) error { return i.UnmarshalText([]byte(s)) }
go
func (i *KSUID) Set(s string) error { return i.UnmarshalText([]byte(s)) }
[ "func", "(", "i", "*", "KSUID", ")", "Set", "(", "s", "string", ")", "error", "{", "return", "i", ".", "UnmarshalText", "(", "[", "]", "byte", "(", "s", ")", ")", "\n", "}" ]
// Set satisfies the flag.Value interface, making it possible to use KSUIDs as // part of of the command line options of a program.
[ "Set", "satisfies", "the", "flag", ".", "Value", "interface", "making", "it", "possible", "to", "use", "KSUIDs", "as", "part", "of", "of", "the", "command", "line", "options", "of", "a", "program", "." ]
7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8
https://github.com/segmentio/ksuid/blob/7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8/ksuid.go#L107-L109
train
segmentio/ksuid
ksuid.go
Value
func (i KSUID) Value() (driver.Value, error) { if i.IsNil() { return nil, nil } return i.String(), nil }
go
func (i KSUID) Value() (driver.Value, error) { if i.IsNil() { return nil, nil } return i.String(), nil }
[ "func", "(", "i", "KSUID", ")", "Value", "(", ")", "(", "driver", ".", "Value", ",", "error", ")", "{", "if", "i", ".", "IsNil", "(", ")", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "i", ".", "String", "(", ")", ",", "nil", "\n", "}" ]
// Value converts the KSUID into a SQL driver value which can be used to // directly use the KSUID as parameter to a SQL query.
[ "Value", "converts", "the", "KSUID", "into", "a", "SQL", "driver", "value", "which", "can", "be", "used", "to", "directly", "use", "the", "KSUID", "as", "parameter", "to", "a", "SQL", "query", "." ]
7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8
https://github.com/segmentio/ksuid/blob/7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8/ksuid.go#L139-L144
train
segmentio/ksuid
ksuid.go
Parse
func Parse(s string) (KSUID, error) { if len(s) != stringEncodedLength { return Nil, errStrSize } src := [stringEncodedLength]byte{} dst := [byteLength]byte{} copy(src[:], s[:]) if err := fastDecodeBase62(dst[:], src[:]); err != nil { return Nil, errStrValue } return FromBytes(dst[:]) }
go
func Parse(s string) (KSUID, error) { if len(s) != stringEncodedLength { return Nil, errStrSize } src := [stringEncodedLength]byte{} dst := [byteLength]byte{} copy(src[:], s[:]) if err := fastDecodeBase62(dst[:], src[:]); err != nil { return Nil, errStrValue } return FromBytes(dst[:]) }
[ "func", "Parse", "(", "s", "string", ")", "(", "KSUID", ",", "error", ")", "{", "if", "len", "(", "s", ")", "!=", "stringEncodedLength", "{", "return", "Nil", ",", "errStrSize", "\n", "}", "\n\n", "src", ":=", "[", "stringEncodedLength", "]", "byte", "{", "}", "\n", "dst", ":=", "[", "byteLength", "]", "byte", "{", "}", "\n\n", "copy", "(", "src", "[", ":", "]", ",", "s", "[", ":", "]", ")", "\n\n", "if", "err", ":=", "fastDecodeBase62", "(", "dst", "[", ":", "]", ",", "src", "[", ":", "]", ")", ";", "err", "!=", "nil", "{", "return", "Nil", ",", "errStrValue", "\n", "}", "\n\n", "return", "FromBytes", "(", "dst", "[", ":", "]", ")", "\n", "}" ]
// Parse decodes a string-encoded representation of a KSUID object
[ "Parse", "decodes", "a", "string", "-", "encoded", "representation", "of", "a", "KSUID", "object" ]
7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8
https://github.com/segmentio/ksuid/blob/7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8/ksuid.go#L177-L192
train
segmentio/ksuid
ksuid.go
New
func New() KSUID { ksuid, err := NewRandom() if err != nil { panic(fmt.Sprintf("Couldn't generate KSUID, inconceivable! error: %v", err)) } return ksuid }
go
func New() KSUID { ksuid, err := NewRandom() if err != nil { panic(fmt.Sprintf("Couldn't generate KSUID, inconceivable! error: %v", err)) } return ksuid }
[ "func", "New", "(", ")", "KSUID", "{", "ksuid", ",", "err", ":=", "NewRandom", "(", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n", "return", "ksuid", "\n", "}" ]
// Generates a new KSUID. In the strange case that random bytes // can't be read, it will panic.
[ "Generates", "a", "new", "KSUID", ".", "In", "the", "strange", "case", "that", "random", "bytes", "can", "t", "be", "read", "it", "will", "panic", "." ]
7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8
https://github.com/segmentio/ksuid/blob/7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8/ksuid.go#L204-L210
train
segmentio/ksuid
ksuid.go
FromParts
func FromParts(t time.Time, payload []byte) (KSUID, error) { if len(payload) != payloadLengthInBytes { return Nil, errPayloadSize } var ksuid KSUID ts := timeToCorrectedUTCTimestamp(t) binary.BigEndian.PutUint32(ksuid[:timestampLengthInBytes], ts) copy(ksuid[timestampLengthInBytes:], payload) return ksuid, nil }
go
func FromParts(t time.Time, payload []byte) (KSUID, error) { if len(payload) != payloadLengthInBytes { return Nil, errPayloadSize } var ksuid KSUID ts := timeToCorrectedUTCTimestamp(t) binary.BigEndian.PutUint32(ksuid[:timestampLengthInBytes], ts) copy(ksuid[timestampLengthInBytes:], payload) return ksuid, nil }
[ "func", "FromParts", "(", "t", "time", ".", "Time", ",", "payload", "[", "]", "byte", ")", "(", "KSUID", ",", "error", ")", "{", "if", "len", "(", "payload", ")", "!=", "payloadLengthInBytes", "{", "return", "Nil", ",", "errPayloadSize", "\n", "}", "\n\n", "var", "ksuid", "KSUID", "\n\n", "ts", ":=", "timeToCorrectedUTCTimestamp", "(", "t", ")", "\n", "binary", ".", "BigEndian", ".", "PutUint32", "(", "ksuid", "[", ":", "timestampLengthInBytes", "]", ",", "ts", ")", "\n\n", "copy", "(", "ksuid", "[", "timestampLengthInBytes", ":", "]", ",", "payload", ")", "\n\n", "return", "ksuid", ",", "nil", "\n", "}" ]
// Constructs a KSUID from constituent parts
[ "Constructs", "a", "KSUID", "from", "constituent", "parts" ]
7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8
https://github.com/segmentio/ksuid/blob/7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8/ksuid.go#L239-L252
train
segmentio/ksuid
ksuid.go
FromBytes
func FromBytes(b []byte) (KSUID, error) { var ksuid KSUID if len(b) != byteLength { return Nil, errSize } copy(ksuid[:], b) return ksuid, nil }
go
func FromBytes(b []byte) (KSUID, error) { var ksuid KSUID if len(b) != byteLength { return Nil, errSize } copy(ksuid[:], b) return ksuid, nil }
[ "func", "FromBytes", "(", "b", "[", "]", "byte", ")", "(", "KSUID", ",", "error", ")", "{", "var", "ksuid", "KSUID", "\n\n", "if", "len", "(", "b", ")", "!=", "byteLength", "{", "return", "Nil", ",", "errSize", "\n", "}", "\n\n", "copy", "(", "ksuid", "[", ":", "]", ",", "b", ")", "\n", "return", "ksuid", ",", "nil", "\n", "}" ]
// Constructs a KSUID from a 20-byte binary representation
[ "Constructs", "a", "KSUID", "from", "a", "20", "-", "byte", "binary", "representation" ]
7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8
https://github.com/segmentio/ksuid/blob/7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8/ksuid.go#L255-L264
train
segmentio/ksuid
ksuid.go
SetRand
func SetRand(r io.Reader) { if r == nil { rander = rand.Reader return } rander = r }
go
func SetRand(r io.Reader) { if r == nil { rander = rand.Reader return } rander = r }
[ "func", "SetRand", "(", "r", "io", ".", "Reader", ")", "{", "if", "r", "==", "nil", "{", "rander", "=", "rand", ".", "Reader", "\n", "return", "\n", "}", "\n", "rander", "=", "r", "\n", "}" ]
// Sets the global source of random bytes for KSUID generation. This // should probably only be set once globally. While this is technically // thread-safe as in it won't cause corruption, there's no guarantee // on ordering.
[ "Sets", "the", "global", "source", "of", "random", "bytes", "for", "KSUID", "generation", ".", "This", "should", "probably", "only", "be", "set", "once", "globally", ".", "While", "this", "is", "technically", "thread", "-", "safe", "as", "in", "it", "won", "t", "cause", "corruption", "there", "s", "no", "guarantee", "on", "ordering", "." ]
7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8
https://github.com/segmentio/ksuid/blob/7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8/ksuid.go#L270-L276
train
segmentio/ksuid
ksuid.go
IsSorted
func IsSorted(ids []KSUID) bool { if len(ids) != 0 { min := ids[0] for _, id := range ids[1:] { if bytes.Compare(min[:], id[:]) > 0 { return false } min = id } } return true }
go
func IsSorted(ids []KSUID) bool { if len(ids) != 0 { min := ids[0] for _, id := range ids[1:] { if bytes.Compare(min[:], id[:]) > 0 { return false } min = id } } return true }
[ "func", "IsSorted", "(", "ids", "[", "]", "KSUID", ")", "bool", "{", "if", "len", "(", "ids", ")", "!=", "0", "{", "min", ":=", "ids", "[", "0", "]", "\n", "for", "_", ",", "id", ":=", "range", "ids", "[", "1", ":", "]", "{", "if", "bytes", ".", "Compare", "(", "min", "[", ":", "]", ",", "id", "[", ":", "]", ")", ">", "0", "{", "return", "false", "\n", "}", "\n", "min", "=", "id", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// IsSorted checks whether a slice of KSUIDs is sorted
[ "IsSorted", "checks", "whether", "a", "slice", "of", "KSUIDs", "is", "sorted" ]
7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8
https://github.com/segmentio/ksuid/blob/7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8/ksuid.go#L289-L300
train
segmentio/ksuid
ksuid.go
Next
func (id KSUID) Next() KSUID { zero := makeUint128(0, 0) t := id.Timestamp() u := uint128Payload(id) v := add128(u, makeUint128(0, 1)) if v == zero { // overflow t++ } return v.ksuid(t) }
go
func (id KSUID) Next() KSUID { zero := makeUint128(0, 0) t := id.Timestamp() u := uint128Payload(id) v := add128(u, makeUint128(0, 1)) if v == zero { // overflow t++ } return v.ksuid(t) }
[ "func", "(", "id", "KSUID", ")", "Next", "(", ")", "KSUID", "{", "zero", ":=", "makeUint128", "(", "0", ",", "0", ")", "\n\n", "t", ":=", "id", ".", "Timestamp", "(", ")", "\n", "u", ":=", "uint128Payload", "(", "id", ")", "\n", "v", ":=", "add128", "(", "u", ",", "makeUint128", "(", "0", ",", "1", ")", ")", "\n\n", "if", "v", "==", "zero", "{", "// overflow", "t", "++", "\n", "}", "\n\n", "return", "v", ".", "ksuid", "(", "t", ")", "\n", "}" ]
// Next returns the next KSUID after id.
[ "Next", "returns", "the", "next", "KSUID", "after", "id", "." ]
7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8
https://github.com/segmentio/ksuid/blob/7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8/ksuid.go#L325-L337
train
segmentio/ksuid
ksuid.go
Prev
func (id KSUID) Prev() KSUID { max := makeUint128(math.MaxUint64, math.MaxUint64) t := id.Timestamp() u := uint128Payload(id) v := sub128(u, makeUint128(0, 1)) if v == max { // overflow t-- } return v.ksuid(t) }
go
func (id KSUID) Prev() KSUID { max := makeUint128(math.MaxUint64, math.MaxUint64) t := id.Timestamp() u := uint128Payload(id) v := sub128(u, makeUint128(0, 1)) if v == max { // overflow t-- } return v.ksuid(t) }
[ "func", "(", "id", "KSUID", ")", "Prev", "(", ")", "KSUID", "{", "max", ":=", "makeUint128", "(", "math", ".", "MaxUint64", ",", "math", ".", "MaxUint64", ")", "\n\n", "t", ":=", "id", ".", "Timestamp", "(", ")", "\n", "u", ":=", "uint128Payload", "(", "id", ")", "\n", "v", ":=", "sub128", "(", "u", ",", "makeUint128", "(", "0", ",", "1", ")", ")", "\n\n", "if", "v", "==", "max", "{", "// overflow", "t", "--", "\n", "}", "\n\n", "return", "v", ".", "ksuid", "(", "t", ")", "\n", "}" ]
// Prev returns the previoud KSUID before id.
[ "Prev", "returns", "the", "previoud", "KSUID", "before", "id", "." ]
7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8
https://github.com/segmentio/ksuid/blob/7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8/ksuid.go#L340-L352
train
segmentio/ksuid
sequence.go
Next
func (seq *Sequence) Next() (KSUID, error) { id := seq.Seed // copy count := seq.count if count > math.MaxUint16 { return Nil, errors.New("too many IDs were generated") } seq.count++ return withSequenceNumber(id, uint16(count)), nil }
go
func (seq *Sequence) Next() (KSUID, error) { id := seq.Seed // copy count := seq.count if count > math.MaxUint16 { return Nil, errors.New("too many IDs were generated") } seq.count++ return withSequenceNumber(id, uint16(count)), nil }
[ "func", "(", "seq", "*", "Sequence", ")", "Next", "(", ")", "(", "KSUID", ",", "error", ")", "{", "id", ":=", "seq", ".", "Seed", "// copy", "\n", "count", ":=", "seq", ".", "count", "\n", "if", "count", ">", "math", ".", "MaxUint16", "{", "return", "Nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "seq", ".", "count", "++", "\n", "return", "withSequenceNumber", "(", "id", ",", "uint16", "(", "count", ")", ")", ",", "nil", "\n", "}" ]
// Next produces the next KSUID in the sequence, or returns an error if the // sequence has been exhausted.
[ "Next", "produces", "the", "next", "KSUID", "in", "the", "sequence", "or", "returns", "an", "error", "if", "the", "sequence", "has", "been", "exhausted", "." ]
7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8
https://github.com/segmentio/ksuid/blob/7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8/sequence.go#L31-L39
train
segmentio/ksuid
sequence.go
Bounds
func (seq *Sequence) Bounds() (min KSUID, max KSUID) { count := seq.count if count > math.MaxUint16 { count = math.MaxUint16 } return withSequenceNumber(seq.Seed, uint16(count)), withSequenceNumber(seq.Seed, math.MaxUint16) }
go
func (seq *Sequence) Bounds() (min KSUID, max KSUID) { count := seq.count if count > math.MaxUint16 { count = math.MaxUint16 } return withSequenceNumber(seq.Seed, uint16(count)), withSequenceNumber(seq.Seed, math.MaxUint16) }
[ "func", "(", "seq", "*", "Sequence", ")", "Bounds", "(", ")", "(", "min", "KSUID", ",", "max", "KSUID", ")", "{", "count", ":=", "seq", ".", "count", "\n", "if", "count", ">", "math", ".", "MaxUint16", "{", "count", "=", "math", ".", "MaxUint16", "\n", "}", "\n", "return", "withSequenceNumber", "(", "seq", ".", "Seed", ",", "uint16", "(", "count", ")", ")", ",", "withSequenceNumber", "(", "seq", ".", "Seed", ",", "math", ".", "MaxUint16", ")", "\n", "}" ]
// Bounds returns the inclusive min and max bounds of the KSUIDs that may be // generated by the sequence. If all ids have been generated already then the // returned min value is equal to the max.
[ "Bounds", "returns", "the", "inclusive", "min", "and", "max", "bounds", "of", "the", "KSUIDs", "that", "may", "be", "generated", "by", "the", "sequence", ".", "If", "all", "ids", "have", "been", "generated", "already", "then", "the", "returned", "min", "value", "is", "equal", "to", "the", "max", "." ]
7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8
https://github.com/segmentio/ksuid/blob/7d859c5329d157d00c7d5a4ead1ce7a9d45eeda8/sequence.go#L44-L50
train
btcsuite/btcwallet
wallet/chainntfns.go
connectBlock
func (w *Wallet) connectBlock(dbtx walletdb.ReadWriteTx, b wtxmgr.BlockMeta) error { addrmgrNs := dbtx.ReadWriteBucket(waddrmgrNamespaceKey) bs := waddrmgr.BlockStamp{ Height: b.Height, Hash: b.Hash, Timestamp: b.Time, } err := w.Manager.SetSyncedTo(addrmgrNs, &bs) if err != nil { return err } // Notify interested clients of the connected block. // // TODO: move all notifications outside of the database transaction. w.NtfnServer.notifyAttachedBlock(dbtx, &b) return nil }
go
func (w *Wallet) connectBlock(dbtx walletdb.ReadWriteTx, b wtxmgr.BlockMeta) error { addrmgrNs := dbtx.ReadWriteBucket(waddrmgrNamespaceKey) bs := waddrmgr.BlockStamp{ Height: b.Height, Hash: b.Hash, Timestamp: b.Time, } err := w.Manager.SetSyncedTo(addrmgrNs, &bs) if err != nil { return err } // Notify interested clients of the connected block. // // TODO: move all notifications outside of the database transaction. w.NtfnServer.notifyAttachedBlock(dbtx, &b) return nil }
[ "func", "(", "w", "*", "Wallet", ")", "connectBlock", "(", "dbtx", "walletdb", ".", "ReadWriteTx", ",", "b", "wtxmgr", ".", "BlockMeta", ")", "error", "{", "addrmgrNs", ":=", "dbtx", ".", "ReadWriteBucket", "(", "waddrmgrNamespaceKey", ")", "\n\n", "bs", ":=", "waddrmgr", ".", "BlockStamp", "{", "Height", ":", "b", ".", "Height", ",", "Hash", ":", "b", ".", "Hash", ",", "Timestamp", ":", "b", ".", "Time", ",", "}", "\n", "err", ":=", "w", ".", "Manager", ".", "SetSyncedTo", "(", "addrmgrNs", ",", "&", "bs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Notify interested clients of the connected block.", "//", "// TODO: move all notifications outside of the database transaction.", "w", ".", "NtfnServer", ".", "notifyAttachedBlock", "(", "dbtx", ",", "&", "b", ")", "\n", "return", "nil", "\n", "}" ]
// connectBlock handles a chain server notification by marking a wallet // that's currently in-sync with the chain server as being synced up to // the passed block.
[ "connectBlock", "handles", "a", "chain", "server", "notification", "by", "marking", "a", "wallet", "that", "s", "currently", "in", "-", "sync", "with", "the", "chain", "server", "as", "being", "synced", "up", "to", "the", "passed", "block", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/chainntfns.go#L205-L223
train
btcsuite/btcwallet
wallet/chainntfns.go
disconnectBlock
func (w *Wallet) disconnectBlock(dbtx walletdb.ReadWriteTx, b wtxmgr.BlockMeta) error { addrmgrNs := dbtx.ReadWriteBucket(waddrmgrNamespaceKey) txmgrNs := dbtx.ReadWriteBucket(wtxmgrNamespaceKey) if !w.ChainSynced() { return nil } // Disconnect the removed block and all blocks after it if we know about // the disconnected block. Otherwise, the block is in the future. if b.Height <= w.Manager.SyncedTo().Height { hash, err := w.Manager.BlockHash(addrmgrNs, b.Height) if err != nil { return err } if bytes.Equal(hash[:], b.Hash[:]) { bs := waddrmgr.BlockStamp{ Height: b.Height - 1, } hash, err = w.Manager.BlockHash(addrmgrNs, bs.Height) if err != nil { return err } b.Hash = *hash client := w.ChainClient() header, err := client.GetBlockHeader(hash) if err != nil { return err } bs.Timestamp = header.Timestamp err = w.Manager.SetSyncedTo(addrmgrNs, &bs) if err != nil { return err } err = w.TxStore.Rollback(txmgrNs, b.Height) if err != nil { return err } } } // Notify interested clients of the disconnected block. w.NtfnServer.notifyDetachedBlock(&b.Hash) return nil }
go
func (w *Wallet) disconnectBlock(dbtx walletdb.ReadWriteTx, b wtxmgr.BlockMeta) error { addrmgrNs := dbtx.ReadWriteBucket(waddrmgrNamespaceKey) txmgrNs := dbtx.ReadWriteBucket(wtxmgrNamespaceKey) if !w.ChainSynced() { return nil } // Disconnect the removed block and all blocks after it if we know about // the disconnected block. Otherwise, the block is in the future. if b.Height <= w.Manager.SyncedTo().Height { hash, err := w.Manager.BlockHash(addrmgrNs, b.Height) if err != nil { return err } if bytes.Equal(hash[:], b.Hash[:]) { bs := waddrmgr.BlockStamp{ Height: b.Height - 1, } hash, err = w.Manager.BlockHash(addrmgrNs, bs.Height) if err != nil { return err } b.Hash = *hash client := w.ChainClient() header, err := client.GetBlockHeader(hash) if err != nil { return err } bs.Timestamp = header.Timestamp err = w.Manager.SetSyncedTo(addrmgrNs, &bs) if err != nil { return err } err = w.TxStore.Rollback(txmgrNs, b.Height) if err != nil { return err } } } // Notify interested clients of the disconnected block. w.NtfnServer.notifyDetachedBlock(&b.Hash) return nil }
[ "func", "(", "w", "*", "Wallet", ")", "disconnectBlock", "(", "dbtx", "walletdb", ".", "ReadWriteTx", ",", "b", "wtxmgr", ".", "BlockMeta", ")", "error", "{", "addrmgrNs", ":=", "dbtx", ".", "ReadWriteBucket", "(", "waddrmgrNamespaceKey", ")", "\n", "txmgrNs", ":=", "dbtx", ".", "ReadWriteBucket", "(", "wtxmgrNamespaceKey", ")", "\n\n", "if", "!", "w", ".", "ChainSynced", "(", ")", "{", "return", "nil", "\n", "}", "\n\n", "// Disconnect the removed block and all blocks after it if we know about", "// the disconnected block. Otherwise, the block is in the future.", "if", "b", ".", "Height", "<=", "w", ".", "Manager", ".", "SyncedTo", "(", ")", ".", "Height", "{", "hash", ",", "err", ":=", "w", ".", "Manager", ".", "BlockHash", "(", "addrmgrNs", ",", "b", ".", "Height", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "bytes", ".", "Equal", "(", "hash", "[", ":", "]", ",", "b", ".", "Hash", "[", ":", "]", ")", "{", "bs", ":=", "waddrmgr", ".", "BlockStamp", "{", "Height", ":", "b", ".", "Height", "-", "1", ",", "}", "\n", "hash", ",", "err", "=", "w", ".", "Manager", ".", "BlockHash", "(", "addrmgrNs", ",", "bs", ".", "Height", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "b", ".", "Hash", "=", "*", "hash", "\n\n", "client", ":=", "w", ".", "ChainClient", "(", ")", "\n", "header", ",", "err", ":=", "client", ".", "GetBlockHeader", "(", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "bs", ".", "Timestamp", "=", "header", ".", "Timestamp", "\n", "err", "=", "w", ".", "Manager", ".", "SetSyncedTo", "(", "addrmgrNs", ",", "&", "bs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "err", "=", "w", ".", "TxStore", ".", "Rollback", "(", "txmgrNs", ",", "b", ".", "Height", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Notify interested clients of the disconnected block.", "w", ".", "NtfnServer", ".", "notifyDetachedBlock", "(", "&", "b", ".", "Hash", ")", "\n\n", "return", "nil", "\n", "}" ]
// disconnectBlock handles a chain server reorganize by rolling back all // block history from the reorged block for a wallet in-sync with the chain // server.
[ "disconnectBlock", "handles", "a", "chain", "server", "reorganize", "by", "rolling", "back", "all", "block", "history", "from", "the", "reorged", "block", "for", "a", "wallet", "in", "-", "sync", "with", "the", "chain", "server", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/chainntfns.go#L228-L276
train
btcsuite/btcwallet
wallet/chainntfns.go
BirthdayBlock
func (s *walletBirthdayStore) BirthdayBlock() (waddrmgr.BlockStamp, bool, error) { var ( birthdayBlock waddrmgr.BlockStamp birthdayBlockVerified bool ) err := walletdb.View(s.db, func(tx walletdb.ReadTx) error { var err error ns := tx.ReadBucket(waddrmgrNamespaceKey) birthdayBlock, birthdayBlockVerified, err = s.manager.BirthdayBlock(ns) return err }) return birthdayBlock, birthdayBlockVerified, err }
go
func (s *walletBirthdayStore) BirthdayBlock() (waddrmgr.BlockStamp, bool, error) { var ( birthdayBlock waddrmgr.BlockStamp birthdayBlockVerified bool ) err := walletdb.View(s.db, func(tx walletdb.ReadTx) error { var err error ns := tx.ReadBucket(waddrmgrNamespaceKey) birthdayBlock, birthdayBlockVerified, err = s.manager.BirthdayBlock(ns) return err }) return birthdayBlock, birthdayBlockVerified, err }
[ "func", "(", "s", "*", "walletBirthdayStore", ")", "BirthdayBlock", "(", ")", "(", "waddrmgr", ".", "BlockStamp", ",", "bool", ",", "error", ")", "{", "var", "(", "birthdayBlock", "waddrmgr", ".", "BlockStamp", "\n", "birthdayBlockVerified", "bool", "\n", ")", "\n\n", "err", ":=", "walletdb", ".", "View", "(", "s", ".", "db", ",", "func", "(", "tx", "walletdb", ".", "ReadTx", ")", "error", "{", "var", "err", "error", "\n", "ns", ":=", "tx", ".", "ReadBucket", "(", "waddrmgrNamespaceKey", ")", "\n", "birthdayBlock", ",", "birthdayBlockVerified", ",", "err", "=", "s", ".", "manager", ".", "BirthdayBlock", "(", "ns", ")", "\n", "return", "err", "\n", "}", ")", "\n\n", "return", "birthdayBlock", ",", "birthdayBlockVerified", ",", "err", "\n", "}" ]
// BirthdayBlock returns the birthday block of the wallet.
[ "BirthdayBlock", "returns", "the", "birthday", "block", "of", "the", "wallet", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/chainntfns.go#L413-L427
train
btcsuite/btcwallet
wtxmgr/error.go
IsNoExists
func IsNoExists(err error) bool { serr, ok := err.(Error) return ok && serr.Code == ErrNoExists }
go
func IsNoExists(err error) bool { serr, ok := err.(Error) return ok && serr.Code == ErrNoExists }
[ "func", "IsNoExists", "(", "err", "error", ")", "bool", "{", "serr", ",", "ok", ":=", "err", ".", "(", "Error", ")", "\n", "return", "ok", "&&", "serr", ".", "Code", "==", "ErrNoExists", "\n", "}" ]
// IsNoExists returns whether an error is a Error with the ErrNoExists error // code.
[ "IsNoExists", "returns", "whether", "an", "error", "is", "a", "Error", "with", "the", "ErrNoExists", "error", "code", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/error.go#L94-L97
train
btcsuite/btcwallet
chain/bitcoind_conn.go
NewBitcoindConn
func NewBitcoindConn(chainParams *chaincfg.Params, host, user, pass, zmqBlockHost, zmqTxHost string, zmqPollInterval time.Duration) (*BitcoindConn, error) { clientCfg := &rpcclient.ConnConfig{ Host: host, User: user, Pass: pass, DisableAutoReconnect: false, DisableConnectOnNew: true, DisableTLS: true, HTTPPostMode: true, } client, err := rpcclient.New(clientCfg, nil) if err != nil { return nil, err } conn := &BitcoindConn{ chainParams: chainParams, client: client, zmqBlockHost: zmqBlockHost, zmqTxHost: zmqTxHost, zmqPollInterval: zmqPollInterval, rescanClients: make(map[uint64]*BitcoindClient), quit: make(chan struct{}), } return conn, nil }
go
func NewBitcoindConn(chainParams *chaincfg.Params, host, user, pass, zmqBlockHost, zmqTxHost string, zmqPollInterval time.Duration) (*BitcoindConn, error) { clientCfg := &rpcclient.ConnConfig{ Host: host, User: user, Pass: pass, DisableAutoReconnect: false, DisableConnectOnNew: true, DisableTLS: true, HTTPPostMode: true, } client, err := rpcclient.New(clientCfg, nil) if err != nil { return nil, err } conn := &BitcoindConn{ chainParams: chainParams, client: client, zmqBlockHost: zmqBlockHost, zmqTxHost: zmqTxHost, zmqPollInterval: zmqPollInterval, rescanClients: make(map[uint64]*BitcoindClient), quit: make(chan struct{}), } return conn, nil }
[ "func", "NewBitcoindConn", "(", "chainParams", "*", "chaincfg", ".", "Params", ",", "host", ",", "user", ",", "pass", ",", "zmqBlockHost", ",", "zmqTxHost", "string", ",", "zmqPollInterval", "time", ".", "Duration", ")", "(", "*", "BitcoindConn", ",", "error", ")", "{", "clientCfg", ":=", "&", "rpcclient", ".", "ConnConfig", "{", "Host", ":", "host", ",", "User", ":", "user", ",", "Pass", ":", "pass", ",", "DisableAutoReconnect", ":", "false", ",", "DisableConnectOnNew", ":", "true", ",", "DisableTLS", ":", "true", ",", "HTTPPostMode", ":", "true", ",", "}", "\n\n", "client", ",", "err", ":=", "rpcclient", ".", "New", "(", "clientCfg", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "conn", ":=", "&", "BitcoindConn", "{", "chainParams", ":", "chainParams", ",", "client", ":", "client", ",", "zmqBlockHost", ":", "zmqBlockHost", ",", "zmqTxHost", ":", "zmqTxHost", ",", "zmqPollInterval", ":", "zmqPollInterval", ",", "rescanClients", ":", "make", "(", "map", "[", "uint64", "]", "*", "BitcoindClient", ")", ",", "quit", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n\n", "return", "conn", ",", "nil", "\n", "}" ]
// NewBitcoindConn creates a client connection to the node described by the host // string. The connection is not established immediately, but must be done using // the Start method. If the remote node does not operate on the same bitcoin // network as described by the passed chain parameters, the connection will be // disconnected.
[ "NewBitcoindConn", "creates", "a", "client", "connection", "to", "the", "node", "described", "by", "the", "host", "string", ".", "The", "connection", "is", "not", "established", "immediately", "but", "must", "be", "done", "using", "the", "Start", "method", ".", "If", "the", "remote", "node", "does", "not", "operate", "on", "the", "same", "bitcoin", "network", "as", "described", "by", "the", "passed", "chain", "parameters", "the", "connection", "will", "be", "disconnected", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_conn.go#L62-L92
train
btcsuite/btcwallet
chain/bitcoind_conn.go
Start
func (c *BitcoindConn) Start() error { if !atomic.CompareAndSwapInt32(&c.started, 0, 1) { return nil } // Verify that the node is running on the expected network. net, err := c.getCurrentNet() if err != nil { c.client.Disconnect() return err } if net != c.chainParams.Net { c.client.Disconnect() return fmt.Errorf("expected network %v, got %v", c.chainParams.Net, net) } // Establish two different ZMQ connections to bitcoind to retrieve block // and transaction event notifications. We'll use two as a separation of // concern to ensure one type of event isn't dropped from the connection // queue due to another type of event filling it up. zmqBlockConn, err := gozmq.Subscribe( c.zmqBlockHost, []string{"rawblock"}, c.zmqPollInterval, ) if err != nil { c.client.Disconnect() return fmt.Errorf("unable to subscribe for zmq block events: "+ "%v", err) } zmqTxConn, err := gozmq.Subscribe( c.zmqTxHost, []string{"rawtx"}, c.zmqPollInterval, ) if err != nil { c.client.Disconnect() return fmt.Errorf("unable to subscribe for zmq tx events: %v", err) } c.wg.Add(2) go c.blockEventHandler(zmqBlockConn) go c.txEventHandler(zmqTxConn) return nil }
go
func (c *BitcoindConn) Start() error { if !atomic.CompareAndSwapInt32(&c.started, 0, 1) { return nil } // Verify that the node is running on the expected network. net, err := c.getCurrentNet() if err != nil { c.client.Disconnect() return err } if net != c.chainParams.Net { c.client.Disconnect() return fmt.Errorf("expected network %v, got %v", c.chainParams.Net, net) } // Establish two different ZMQ connections to bitcoind to retrieve block // and transaction event notifications. We'll use two as a separation of // concern to ensure one type of event isn't dropped from the connection // queue due to another type of event filling it up. zmqBlockConn, err := gozmq.Subscribe( c.zmqBlockHost, []string{"rawblock"}, c.zmqPollInterval, ) if err != nil { c.client.Disconnect() return fmt.Errorf("unable to subscribe for zmq block events: "+ "%v", err) } zmqTxConn, err := gozmq.Subscribe( c.zmqTxHost, []string{"rawtx"}, c.zmqPollInterval, ) if err != nil { c.client.Disconnect() return fmt.Errorf("unable to subscribe for zmq tx events: %v", err) } c.wg.Add(2) go c.blockEventHandler(zmqBlockConn) go c.txEventHandler(zmqTxConn) return nil }
[ "func", "(", "c", "*", "BitcoindConn", ")", "Start", "(", ")", "error", "{", "if", "!", "atomic", ".", "CompareAndSwapInt32", "(", "&", "c", ".", "started", ",", "0", ",", "1", ")", "{", "return", "nil", "\n", "}", "\n\n", "// Verify that the node is running on the expected network.", "net", ",", "err", ":=", "c", ".", "getCurrentNet", "(", ")", "\n", "if", "err", "!=", "nil", "{", "c", ".", "client", ".", "Disconnect", "(", ")", "\n", "return", "err", "\n", "}", "\n", "if", "net", "!=", "c", ".", "chainParams", ".", "Net", "{", "c", ".", "client", ".", "Disconnect", "(", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "c", ".", "chainParams", ".", "Net", ",", "net", ")", "\n", "}", "\n\n", "// Establish two different ZMQ connections to bitcoind to retrieve block", "// and transaction event notifications. We'll use two as a separation of", "// concern to ensure one type of event isn't dropped from the connection", "// queue due to another type of event filling it up.", "zmqBlockConn", ",", "err", ":=", "gozmq", ".", "Subscribe", "(", "c", ".", "zmqBlockHost", ",", "[", "]", "string", "{", "\"", "\"", "}", ",", "c", ".", "zmqPollInterval", ",", ")", "\n", "if", "err", "!=", "nil", "{", "c", ".", "client", ".", "Disconnect", "(", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "zmqTxConn", ",", "err", ":=", "gozmq", ".", "Subscribe", "(", "c", ".", "zmqTxHost", ",", "[", "]", "string", "{", "\"", "\"", "}", ",", "c", ".", "zmqPollInterval", ",", ")", "\n", "if", "err", "!=", "nil", "{", "c", ".", "client", ".", "Disconnect", "(", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "c", ".", "wg", ".", "Add", "(", "2", ")", "\n", "go", "c", ".", "blockEventHandler", "(", "zmqBlockConn", ")", "\n", "go", "c", ".", "txEventHandler", "(", "zmqTxConn", ")", "\n\n", "return", "nil", "\n", "}" ]
// Start attempts to establish a RPC and ZMQ connection to a bitcoind node. If // successful, a goroutine is spawned to read events from the ZMQ connection. // It's possible for this function to fail due to a limited number of connection // attempts. This is done to prevent waiting forever on the connection to be // established in the case that the node is down.
[ "Start", "attempts", "to", "establish", "a", "RPC", "and", "ZMQ", "connection", "to", "a", "bitcoind", "node", ".", "If", "successful", "a", "goroutine", "is", "spawned", "to", "read", "events", "from", "the", "ZMQ", "connection", ".", "It", "s", "possible", "for", "this", "function", "to", "fail", "due", "to", "a", "limited", "number", "of", "connection", "attempts", ".", "This", "is", "done", "to", "prevent", "waiting", "forever", "on", "the", "connection", "to", "be", "established", "in", "the", "case", "that", "the", "node", "is", "down", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_conn.go#L99-L143
train
btcsuite/btcwallet
chain/bitcoind_conn.go
Stop
func (c *BitcoindConn) Stop() { if !atomic.CompareAndSwapInt32(&c.stopped, 0, 1) { return } for _, client := range c.rescanClients { client.Stop() } close(c.quit) c.client.Shutdown() c.client.WaitForShutdown() c.wg.Wait() }
go
func (c *BitcoindConn) Stop() { if !atomic.CompareAndSwapInt32(&c.stopped, 0, 1) { return } for _, client := range c.rescanClients { client.Stop() } close(c.quit) c.client.Shutdown() c.client.WaitForShutdown() c.wg.Wait() }
[ "func", "(", "c", "*", "BitcoindConn", ")", "Stop", "(", ")", "{", "if", "!", "atomic", ".", "CompareAndSwapInt32", "(", "&", "c", ".", "stopped", ",", "0", ",", "1", ")", "{", "return", "\n", "}", "\n\n", "for", "_", ",", "client", ":=", "range", "c", ".", "rescanClients", "{", "client", ".", "Stop", "(", ")", "\n", "}", "\n\n", "close", "(", "c", ".", "quit", ")", "\n", "c", ".", "client", ".", "Shutdown", "(", ")", "\n\n", "c", ".", "client", ".", "WaitForShutdown", "(", ")", "\n", "c", ".", "wg", ".", "Wait", "(", ")", "\n", "}" ]
// Stop terminates the RPC and ZMQ connection to a bitcoind node and removes any // active rescan clients.
[ "Stop", "terminates", "the", "RPC", "and", "ZMQ", "connection", "to", "a", "bitcoind", "node", "and", "removes", "any", "active", "rescan", "clients", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_conn.go#L147-L161
train
btcsuite/btcwallet
chain/bitcoind_conn.go
getCurrentNet
func (c *BitcoindConn) getCurrentNet() (wire.BitcoinNet, error) { hash, err := c.client.GetBlockHash(0) if err != nil { return 0, err } switch *hash { case *chaincfg.TestNet3Params.GenesisHash: return chaincfg.TestNet3Params.Net, nil case *chaincfg.RegressionNetParams.GenesisHash: return chaincfg.RegressionNetParams.Net, nil case *chaincfg.MainNetParams.GenesisHash: return chaincfg.MainNetParams.Net, nil default: return 0, fmt.Errorf("unknown network with genesis hash %v", hash) } }
go
func (c *BitcoindConn) getCurrentNet() (wire.BitcoinNet, error) { hash, err := c.client.GetBlockHash(0) if err != nil { return 0, err } switch *hash { case *chaincfg.TestNet3Params.GenesisHash: return chaincfg.TestNet3Params.Net, nil case *chaincfg.RegressionNetParams.GenesisHash: return chaincfg.RegressionNetParams.Net, nil case *chaincfg.MainNetParams.GenesisHash: return chaincfg.MainNetParams.Net, nil default: return 0, fmt.Errorf("unknown network with genesis hash %v", hash) } }
[ "func", "(", "c", "*", "BitcoindConn", ")", "getCurrentNet", "(", ")", "(", "wire", ".", "BitcoinNet", ",", "error", ")", "{", "hash", ",", "err", ":=", "c", ".", "client", ".", "GetBlockHash", "(", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "switch", "*", "hash", "{", "case", "*", "chaincfg", ".", "TestNet3Params", ".", "GenesisHash", ":", "return", "chaincfg", ".", "TestNet3Params", ".", "Net", ",", "nil", "\n", "case", "*", "chaincfg", ".", "RegressionNetParams", ".", "GenesisHash", ":", "return", "chaincfg", ".", "RegressionNetParams", ".", "Net", ",", "nil", "\n", "case", "*", "chaincfg", ".", "MainNetParams", ".", "GenesisHash", ":", "return", "chaincfg", ".", "MainNetParams", ".", "Net", ",", "nil", "\n", "default", ":", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hash", ")", "\n", "}", "\n", "}" ]
// getCurrentNet returns the network on which the bitcoind node is running.
[ "getCurrentNet", "returns", "the", "network", "on", "which", "the", "bitcoind", "node", "is", "running", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_conn.go#L316-L332
train
btcsuite/btcwallet
chain/bitcoind_conn.go
NewBitcoindClient
func (c *BitcoindConn) NewBitcoindClient() *BitcoindClient { return &BitcoindClient{ quit: make(chan struct{}), id: atomic.AddUint64(&c.rescanClientCounter, 1), chainParams: c.chainParams, chainConn: c, rescanUpdate: make(chan interface{}), watchedAddresses: make(map[string]struct{}), watchedOutPoints: make(map[wire.OutPoint]struct{}), watchedTxs: make(map[chainhash.Hash]struct{}), notificationQueue: NewConcurrentQueue(20), zmqTxNtfns: make(chan *wire.MsgTx), zmqBlockNtfns: make(chan *wire.MsgBlock), mempool: make(map[chainhash.Hash]struct{}), expiredMempool: make(map[int32]map[chainhash.Hash]struct{}), } }
go
func (c *BitcoindConn) NewBitcoindClient() *BitcoindClient { return &BitcoindClient{ quit: make(chan struct{}), id: atomic.AddUint64(&c.rescanClientCounter, 1), chainParams: c.chainParams, chainConn: c, rescanUpdate: make(chan interface{}), watchedAddresses: make(map[string]struct{}), watchedOutPoints: make(map[wire.OutPoint]struct{}), watchedTxs: make(map[chainhash.Hash]struct{}), notificationQueue: NewConcurrentQueue(20), zmqTxNtfns: make(chan *wire.MsgTx), zmqBlockNtfns: make(chan *wire.MsgBlock), mempool: make(map[chainhash.Hash]struct{}), expiredMempool: make(map[int32]map[chainhash.Hash]struct{}), } }
[ "func", "(", "c", "*", "BitcoindConn", ")", "NewBitcoindClient", "(", ")", "*", "BitcoindClient", "{", "return", "&", "BitcoindClient", "{", "quit", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "id", ":", "atomic", ".", "AddUint64", "(", "&", "c", ".", "rescanClientCounter", ",", "1", ")", ",", "chainParams", ":", "c", ".", "chainParams", ",", "chainConn", ":", "c", ",", "rescanUpdate", ":", "make", "(", "chan", "interface", "{", "}", ")", ",", "watchedAddresses", ":", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", ",", "watchedOutPoints", ":", "make", "(", "map", "[", "wire", ".", "OutPoint", "]", "struct", "{", "}", ")", ",", "watchedTxs", ":", "make", "(", "map", "[", "chainhash", ".", "Hash", "]", "struct", "{", "}", ")", ",", "notificationQueue", ":", "NewConcurrentQueue", "(", "20", ")", ",", "zmqTxNtfns", ":", "make", "(", "chan", "*", "wire", ".", "MsgTx", ")", ",", "zmqBlockNtfns", ":", "make", "(", "chan", "*", "wire", ".", "MsgBlock", ")", ",", "mempool", ":", "make", "(", "map", "[", "chainhash", ".", "Hash", "]", "struct", "{", "}", ")", ",", "expiredMempool", ":", "make", "(", "map", "[", "int32", "]", "map", "[", "chainhash", ".", "Hash", "]", "struct", "{", "}", ")", ",", "}", "\n", "}" ]
// NewBitcoindClient returns a bitcoind client using the current bitcoind // connection. This allows us to share the same connection using multiple // clients.
[ "NewBitcoindClient", "returns", "a", "bitcoind", "client", "using", "the", "current", "bitcoind", "connection", ".", "This", "allows", "us", "to", "share", "the", "same", "connection", "using", "multiple", "clients", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/bitcoind_conn.go#L337-L358
train
btcsuite/btcwallet
internal/prompt/prompt.go
ProvideSeed
func ProvideSeed() ([]byte, error) { reader := bufio.NewReader(os.Stdin) for { fmt.Print("Enter existing wallet seed: ") seedStr, err := reader.ReadString('\n') if err != nil { return nil, err } seedStr = strings.TrimSpace(strings.ToLower(seedStr)) seed, err := hex.DecodeString(seedStr) if err != nil || len(seed) < hdkeychain.MinSeedBytes || len(seed) > hdkeychain.MaxSeedBytes { fmt.Printf("Invalid seed specified. Must be a "+ "hexadecimal value that is at least %d bits and "+ "at most %d bits\n", hdkeychain.MinSeedBytes*8, hdkeychain.MaxSeedBytes*8) continue } return seed, nil } }
go
func ProvideSeed() ([]byte, error) { reader := bufio.NewReader(os.Stdin) for { fmt.Print("Enter existing wallet seed: ") seedStr, err := reader.ReadString('\n') if err != nil { return nil, err } seedStr = strings.TrimSpace(strings.ToLower(seedStr)) seed, err := hex.DecodeString(seedStr) if err != nil || len(seed) < hdkeychain.MinSeedBytes || len(seed) > hdkeychain.MaxSeedBytes { fmt.Printf("Invalid seed specified. Must be a "+ "hexadecimal value that is at least %d bits and "+ "at most %d bits\n", hdkeychain.MinSeedBytes*8, hdkeychain.MaxSeedBytes*8) continue } return seed, nil } }
[ "func", "ProvideSeed", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "reader", ":=", "bufio", ".", "NewReader", "(", "os", ".", "Stdin", ")", "\n", "for", "{", "fmt", ".", "Print", "(", "\"", "\"", ")", "\n", "seedStr", ",", "err", ":=", "reader", ".", "ReadString", "(", "'\\n'", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "seedStr", "=", "strings", ".", "TrimSpace", "(", "strings", ".", "ToLower", "(", "seedStr", ")", ")", "\n\n", "seed", ",", "err", ":=", "hex", ".", "DecodeString", "(", "seedStr", ")", "\n", "if", "err", "!=", "nil", "||", "len", "(", "seed", ")", "<", "hdkeychain", ".", "MinSeedBytes", "||", "len", "(", "seed", ")", ">", "hdkeychain", ".", "MaxSeedBytes", "{", "fmt", ".", "Printf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\\n", "\"", ",", "hdkeychain", ".", "MinSeedBytes", "*", "8", ",", "hdkeychain", ".", "MaxSeedBytes", "*", "8", ")", "\n", "continue", "\n", "}", "\n\n", "return", "seed", ",", "nil", "\n", "}", "\n", "}" ]
// ProvideSeed is used to prompt for the wallet seed which maybe required during // upgrades.
[ "ProvideSeed", "is", "used", "to", "prompt", "for", "the", "wallet", "seed", "which", "maybe", "required", "during", "upgrades", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/prompt/prompt.go#L22-L45
train
btcsuite/btcwallet
internal/prompt/prompt.go
ProvidePrivPassphrase
func ProvidePrivPassphrase() ([]byte, error) { prompt := "Enter the private passphrase of your wallet: " for { fmt.Print(prompt) pass, err := terminal.ReadPassword(int(os.Stdin.Fd())) if err != nil { return nil, err } fmt.Print("\n") pass = bytes.TrimSpace(pass) if len(pass) == 0 { continue } return pass, nil } }
go
func ProvidePrivPassphrase() ([]byte, error) { prompt := "Enter the private passphrase of your wallet: " for { fmt.Print(prompt) pass, err := terminal.ReadPassword(int(os.Stdin.Fd())) if err != nil { return nil, err } fmt.Print("\n") pass = bytes.TrimSpace(pass) if len(pass) == 0 { continue } return pass, nil } }
[ "func", "ProvidePrivPassphrase", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "prompt", ":=", "\"", "\"", "\n", "for", "{", "fmt", ".", "Print", "(", "prompt", ")", "\n", "pass", ",", "err", ":=", "terminal", ".", "ReadPassword", "(", "int", "(", "os", ".", "Stdin", ".", "Fd", "(", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "fmt", ".", "Print", "(", "\"", "\\n", "\"", ")", "\n", "pass", "=", "bytes", ".", "TrimSpace", "(", "pass", ")", "\n", "if", "len", "(", "pass", ")", "==", "0", "{", "continue", "\n", "}", "\n\n", "return", "pass", ",", "nil", "\n", "}", "\n", "}" ]
// ProvidePrivPassphrase is used to prompt for the private passphrase which // maybe required during upgrades.
[ "ProvidePrivPassphrase", "is", "used", "to", "prompt", "for", "the", "private", "passphrase", "which", "maybe", "required", "during", "upgrades", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/prompt/prompt.go#L49-L65
train
btcsuite/btcwallet
internal/prompt/prompt.go
promptList
func promptList(reader *bufio.Reader, prefix string, validResponses []string, defaultEntry string) (string, error) { // Setup the prompt according to the parameters. validStrings := strings.Join(validResponses, "/") var prompt string if defaultEntry != "" { prompt = fmt.Sprintf("%s (%s) [%s]: ", prefix, validStrings, defaultEntry) } else { prompt = fmt.Sprintf("%s (%s): ", prefix, validStrings) } // Prompt the user until one of the valid responses is given. for { fmt.Print(prompt) reply, err := reader.ReadString('\n') if err != nil { return "", err } reply = strings.TrimSpace(strings.ToLower(reply)) if reply == "" { reply = defaultEntry } for _, validResponse := range validResponses { if reply == validResponse { return reply, nil } } } }
go
func promptList(reader *bufio.Reader, prefix string, validResponses []string, defaultEntry string) (string, error) { // Setup the prompt according to the parameters. validStrings := strings.Join(validResponses, "/") var prompt string if defaultEntry != "" { prompt = fmt.Sprintf("%s (%s) [%s]: ", prefix, validStrings, defaultEntry) } else { prompt = fmt.Sprintf("%s (%s): ", prefix, validStrings) } // Prompt the user until one of the valid responses is given. for { fmt.Print(prompt) reply, err := reader.ReadString('\n') if err != nil { return "", err } reply = strings.TrimSpace(strings.ToLower(reply)) if reply == "" { reply = defaultEntry } for _, validResponse := range validResponses { if reply == validResponse { return reply, nil } } } }
[ "func", "promptList", "(", "reader", "*", "bufio", ".", "Reader", ",", "prefix", "string", ",", "validResponses", "[", "]", "string", ",", "defaultEntry", "string", ")", "(", "string", ",", "error", ")", "{", "// Setup the prompt according to the parameters.", "validStrings", ":=", "strings", ".", "Join", "(", "validResponses", ",", "\"", "\"", ")", "\n", "var", "prompt", "string", "\n", "if", "defaultEntry", "!=", "\"", "\"", "{", "prompt", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "prefix", ",", "validStrings", ",", "defaultEntry", ")", "\n", "}", "else", "{", "prompt", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "prefix", ",", "validStrings", ")", "\n", "}", "\n\n", "// Prompt the user until one of the valid responses is given.", "for", "{", "fmt", ".", "Print", "(", "prompt", ")", "\n", "reply", ",", "err", ":=", "reader", ".", "ReadString", "(", "'\\n'", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "reply", "=", "strings", ".", "TrimSpace", "(", "strings", ".", "ToLower", "(", "reply", ")", ")", "\n", "if", "reply", "==", "\"", "\"", "{", "reply", "=", "defaultEntry", "\n", "}", "\n\n", "for", "_", ",", "validResponse", ":=", "range", "validResponses", "{", "if", "reply", "==", "validResponse", "{", "return", "reply", ",", "nil", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// promptList prompts the user with the given prefix, list of valid responses, // and default list entry to use. The function will repeat the prompt to the // user until they enter a valid response.
[ "promptList", "prompts", "the", "user", "with", "the", "given", "prefix", "list", "of", "valid", "responses", "and", "default", "list", "entry", "to", "use", ".", "The", "function", "will", "repeat", "the", "prompt", "to", "the", "user", "until", "they", "enter", "a", "valid", "response", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/prompt/prompt.go#L70-L99
train
btcsuite/btcwallet
internal/prompt/prompt.go
promptPass
func promptPass(reader *bufio.Reader, prefix string, confirm bool) ([]byte, error) { // Prompt the user until they enter a passphrase. prompt := fmt.Sprintf("%s: ", prefix) for { fmt.Print(prompt) pass, err := terminal.ReadPassword(int(os.Stdin.Fd())) if err != nil { return nil, err } fmt.Print("\n") pass = bytes.TrimSpace(pass) if len(pass) == 0 { continue } if !confirm { return pass, nil } fmt.Print("Confirm passphrase: ") confirm, err := terminal.ReadPassword(int(os.Stdin.Fd())) if err != nil { return nil, err } fmt.Print("\n") confirm = bytes.TrimSpace(confirm) if !bytes.Equal(pass, confirm) { fmt.Println("The entered passphrases do not match") continue } return pass, nil } }
go
func promptPass(reader *bufio.Reader, prefix string, confirm bool) ([]byte, error) { // Prompt the user until they enter a passphrase. prompt := fmt.Sprintf("%s: ", prefix) for { fmt.Print(prompt) pass, err := terminal.ReadPassword(int(os.Stdin.Fd())) if err != nil { return nil, err } fmt.Print("\n") pass = bytes.TrimSpace(pass) if len(pass) == 0 { continue } if !confirm { return pass, nil } fmt.Print("Confirm passphrase: ") confirm, err := terminal.ReadPassword(int(os.Stdin.Fd())) if err != nil { return nil, err } fmt.Print("\n") confirm = bytes.TrimSpace(confirm) if !bytes.Equal(pass, confirm) { fmt.Println("The entered passphrases do not match") continue } return pass, nil } }
[ "func", "promptPass", "(", "reader", "*", "bufio", ".", "Reader", ",", "prefix", "string", ",", "confirm", "bool", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// Prompt the user until they enter a passphrase.", "prompt", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "prefix", ")", "\n", "for", "{", "fmt", ".", "Print", "(", "prompt", ")", "\n", "pass", ",", "err", ":=", "terminal", ".", "ReadPassword", "(", "int", "(", "os", ".", "Stdin", ".", "Fd", "(", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "fmt", ".", "Print", "(", "\"", "\\n", "\"", ")", "\n", "pass", "=", "bytes", ".", "TrimSpace", "(", "pass", ")", "\n", "if", "len", "(", "pass", ")", "==", "0", "{", "continue", "\n", "}", "\n\n", "if", "!", "confirm", "{", "return", "pass", ",", "nil", "\n", "}", "\n\n", "fmt", ".", "Print", "(", "\"", "\"", ")", "\n", "confirm", ",", "err", ":=", "terminal", ".", "ReadPassword", "(", "int", "(", "os", ".", "Stdin", ".", "Fd", "(", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "fmt", ".", "Print", "(", "\"", "\\n", "\"", ")", "\n", "confirm", "=", "bytes", ".", "TrimSpace", "(", "confirm", ")", "\n", "if", "!", "bytes", ".", "Equal", "(", "pass", ",", "confirm", ")", "{", "fmt", ".", "Println", "(", "\"", "\"", ")", "\n", "continue", "\n", "}", "\n\n", "return", "pass", ",", "nil", "\n", "}", "\n", "}" ]
// promptPass prompts the user for a passphrase with the given prefix. The // function will ask the user to confirm the passphrase and will repeat the // prompts until they enter a matching response.
[ "promptPass", "prompts", "the", "user", "for", "a", "passphrase", "with", "the", "given", "prefix", ".", "The", "function", "will", "ask", "the", "user", "to", "confirm", "the", "passphrase", "and", "will", "repeat", "the", "prompts", "until", "they", "enter", "a", "matching", "response", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/prompt/prompt.go#L117-L150
train
btcsuite/btcwallet
internal/prompt/prompt.go
PrivatePass
func PrivatePass(reader *bufio.Reader, legacyKeyStore *keystore.Store) ([]byte, error) { // When there is not an existing legacy wallet, simply prompt the user // for a new private passphase and return it. if legacyKeyStore == nil { return promptPass(reader, "Enter the private "+ "passphrase for your new wallet", true) } // At this point, there is an existing legacy wallet, so prompt the user // for the existing private passphrase and ensure it properly unlocks // the legacy wallet so all of the addresses can later be imported. fmt.Println("You have an existing legacy wallet. All addresses from " + "your existing legacy wallet will be imported into the new " + "wallet format.") for { privPass, err := promptPass(reader, "Enter the private "+ "passphrase for your existing wallet", false) if err != nil { return nil, err } // Keep prompting the user until the passphrase is correct. if err := legacyKeyStore.Unlock([]byte(privPass)); err != nil { if err == keystore.ErrWrongPassphrase { fmt.Println(err) continue } return nil, err } return privPass, nil } }
go
func PrivatePass(reader *bufio.Reader, legacyKeyStore *keystore.Store) ([]byte, error) { // When there is not an existing legacy wallet, simply prompt the user // for a new private passphase and return it. if legacyKeyStore == nil { return promptPass(reader, "Enter the private "+ "passphrase for your new wallet", true) } // At this point, there is an existing legacy wallet, so prompt the user // for the existing private passphrase and ensure it properly unlocks // the legacy wallet so all of the addresses can later be imported. fmt.Println("You have an existing legacy wallet. All addresses from " + "your existing legacy wallet will be imported into the new " + "wallet format.") for { privPass, err := promptPass(reader, "Enter the private "+ "passphrase for your existing wallet", false) if err != nil { return nil, err } // Keep prompting the user until the passphrase is correct. if err := legacyKeyStore.Unlock([]byte(privPass)); err != nil { if err == keystore.ErrWrongPassphrase { fmt.Println(err) continue } return nil, err } return privPass, nil } }
[ "func", "PrivatePass", "(", "reader", "*", "bufio", ".", "Reader", ",", "legacyKeyStore", "*", "keystore", ".", "Store", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// When there is not an existing legacy wallet, simply prompt the user", "// for a new private passphase and return it.", "if", "legacyKeyStore", "==", "nil", "{", "return", "promptPass", "(", "reader", ",", "\"", "\"", "+", "\"", "\"", ",", "true", ")", "\n", "}", "\n\n", "// At this point, there is an existing legacy wallet, so prompt the user", "// for the existing private passphrase and ensure it properly unlocks", "// the legacy wallet so all of the addresses can later be imported.", "fmt", ".", "Println", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ")", "\n", "for", "{", "privPass", ",", "err", ":=", "promptPass", "(", "reader", ",", "\"", "\"", "+", "\"", "\"", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Keep prompting the user until the passphrase is correct.", "if", "err", ":=", "legacyKeyStore", ".", "Unlock", "(", "[", "]", "byte", "(", "privPass", ")", ")", ";", "err", "!=", "nil", "{", "if", "err", "==", "keystore", ".", "ErrWrongPassphrase", "{", "fmt", ".", "Println", "(", "err", ")", "\n", "continue", "\n", "}", "\n\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "privPass", ",", "nil", "\n", "}", "\n", "}" ]
// PrivatePass prompts the user for a private passphrase with varying behavior // depending on whether the passed legacy keystore exists. When it does, the // user is prompted for the existing passphrase which is then used to unlock it. // On the other hand, when the legacy keystore is nil, the user is prompted for // a new private passphrase. All prompts are repeated until the user enters a // valid response.
[ "PrivatePass", "prompts", "the", "user", "for", "a", "private", "passphrase", "with", "varying", "behavior", "depending", "on", "whether", "the", "passed", "legacy", "keystore", "exists", ".", "When", "it", "does", "the", "user", "is", "prompted", "for", "the", "existing", "passphrase", "which", "is", "then", "used", "to", "unlock", "it", ".", "On", "the", "other", "hand", "when", "the", "legacy", "keystore", "is", "nil", "the", "user", "is", "prompted", "for", "a", "new", "private", "passphrase", ".", "All", "prompts", "are", "repeated", "until", "the", "user", "enters", "a", "valid", "response", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/prompt/prompt.go#L158-L191
train
btcsuite/btcwallet
internal/prompt/prompt.go
PublicPass
func PublicPass(reader *bufio.Reader, privPass []byte, defaultPubPassphrase, configPubPassphrase []byte) ([]byte, error) { pubPass := defaultPubPassphrase usePubPass, err := promptListBool(reader, "Do you want "+ "to add an additional layer of encryption for public "+ "data?", "no") if err != nil { return nil, err } if !usePubPass { return pubPass, nil } if !bytes.Equal(configPubPassphrase, pubPass) { useExisting, err := promptListBool(reader, "Use the "+ "existing configured public passphrase for encryption "+ "of public data?", "no") if err != nil { return nil, err } if useExisting { return configPubPassphrase, nil } } for { pubPass, err = promptPass(reader, "Enter the public "+ "passphrase for your new wallet", true) if err != nil { return nil, err } if bytes.Equal(pubPass, privPass) { useSamePass, err := promptListBool(reader, "Are you sure want to use the same passphrase "+ "for public and private data?", "no") if err != nil { return nil, err } if useSamePass { break } continue } break } fmt.Println("NOTE: Use the --walletpass option to configure your " + "public passphrase.") return pubPass, nil }
go
func PublicPass(reader *bufio.Reader, privPass []byte, defaultPubPassphrase, configPubPassphrase []byte) ([]byte, error) { pubPass := defaultPubPassphrase usePubPass, err := promptListBool(reader, "Do you want "+ "to add an additional layer of encryption for public "+ "data?", "no") if err != nil { return nil, err } if !usePubPass { return pubPass, nil } if !bytes.Equal(configPubPassphrase, pubPass) { useExisting, err := promptListBool(reader, "Use the "+ "existing configured public passphrase for encryption "+ "of public data?", "no") if err != nil { return nil, err } if useExisting { return configPubPassphrase, nil } } for { pubPass, err = promptPass(reader, "Enter the public "+ "passphrase for your new wallet", true) if err != nil { return nil, err } if bytes.Equal(pubPass, privPass) { useSamePass, err := promptListBool(reader, "Are you sure want to use the same passphrase "+ "for public and private data?", "no") if err != nil { return nil, err } if useSamePass { break } continue } break } fmt.Println("NOTE: Use the --walletpass option to configure your " + "public passphrase.") return pubPass, nil }
[ "func", "PublicPass", "(", "reader", "*", "bufio", ".", "Reader", ",", "privPass", "[", "]", "byte", ",", "defaultPubPassphrase", ",", "configPubPassphrase", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "pubPass", ":=", "defaultPubPassphrase", "\n", "usePubPass", ",", "err", ":=", "promptListBool", "(", "reader", ",", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "!", "usePubPass", "{", "return", "pubPass", ",", "nil", "\n", "}", "\n\n", "if", "!", "bytes", ".", "Equal", "(", "configPubPassphrase", ",", "pubPass", ")", "{", "useExisting", ",", "err", ":=", "promptListBool", "(", "reader", ",", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "useExisting", "{", "return", "configPubPassphrase", ",", "nil", "\n", "}", "\n", "}", "\n\n", "for", "{", "pubPass", ",", "err", "=", "promptPass", "(", "reader", ",", "\"", "\"", "+", "\"", "\"", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "bytes", ".", "Equal", "(", "pubPass", ",", "privPass", ")", "{", "useSamePass", ",", "err", ":=", "promptListBool", "(", "reader", ",", "\"", "\"", "+", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "useSamePass", "{", "break", "\n", "}", "\n\n", "continue", "\n", "}", "\n\n", "break", "\n", "}", "\n\n", "fmt", ".", "Println", "(", "\"", "\"", "+", "\"", "\"", ")", "\n", "return", "pubPass", ",", "nil", "\n", "}" ]
// PublicPass prompts the user whether they want to add an additional layer of // encryption to the wallet. When the user answers yes and there is already a // public passphrase provided via the passed config, it prompts them whether or // not to use that configured passphrase. It will also detect when the same // passphrase is used for the private and public passphrase and prompt the user // if they are sure they want to use the same passphrase for both. Finally, all // prompts are repeated until the user enters a valid response.
[ "PublicPass", "prompts", "the", "user", "whether", "they", "want", "to", "add", "an", "additional", "layer", "of", "encryption", "to", "the", "wallet", ".", "When", "the", "user", "answers", "yes", "and", "there", "is", "already", "a", "public", "passphrase", "provided", "via", "the", "passed", "config", "it", "prompts", "them", "whether", "or", "not", "to", "use", "that", "configured", "passphrase", ".", "It", "will", "also", "detect", "when", "the", "same", "passphrase", "is", "used", "for", "the", "private", "and", "public", "passphrase", "and", "prompt", "the", "user", "if", "they", "are", "sure", "they", "want", "to", "use", "the", "same", "passphrase", "for", "both", ".", "Finally", "all", "prompts", "are", "repeated", "until", "the", "user", "enters", "a", "valid", "response", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/prompt/prompt.go#L200-L256
train
btcsuite/btcwallet
internal/prompt/prompt.go
Seed
func Seed(reader *bufio.Reader) ([]byte, error) { // Ascertain the wallet generation seed. useUserSeed, err := promptListBool(reader, "Do you have an "+ "existing wallet seed you want to use?", "no") if err != nil { return nil, err } if !useUserSeed { seed, err := hdkeychain.GenerateSeed(hdkeychain.RecommendedSeedLen) if err != nil { return nil, err } fmt.Println("Your wallet generation seed is:") fmt.Printf("%x\n", seed) fmt.Println("IMPORTANT: Keep the seed in a safe place as you\n" + "will NOT be able to restore your wallet without it.") fmt.Println("Please keep in mind that anyone who has access\n" + "to the seed can also restore your wallet thereby\n" + "giving them access to all your funds, so it is\n" + "imperative that you keep it in a secure location.") for { fmt.Print(`Once you have stored the seed in a safe ` + `and secure location, enter "OK" to continue: `) confirmSeed, err := reader.ReadString('\n') if err != nil { return nil, err } confirmSeed = strings.TrimSpace(confirmSeed) confirmSeed = strings.Trim(confirmSeed, `"`) if confirmSeed == "OK" { break } } return seed, nil } for { fmt.Print("Enter existing wallet seed: ") seedStr, err := reader.ReadString('\n') if err != nil { return nil, err } seedStr = strings.TrimSpace(strings.ToLower(seedStr)) seed, err := hex.DecodeString(seedStr) if err != nil || len(seed) < hdkeychain.MinSeedBytes || len(seed) > hdkeychain.MaxSeedBytes { fmt.Printf("Invalid seed specified. Must be a "+ "hexadecimal value that is at least %d bits and "+ "at most %d bits\n", hdkeychain.MinSeedBytes*8, hdkeychain.MaxSeedBytes*8) continue } return seed, nil } }
go
func Seed(reader *bufio.Reader) ([]byte, error) { // Ascertain the wallet generation seed. useUserSeed, err := promptListBool(reader, "Do you have an "+ "existing wallet seed you want to use?", "no") if err != nil { return nil, err } if !useUserSeed { seed, err := hdkeychain.GenerateSeed(hdkeychain.RecommendedSeedLen) if err != nil { return nil, err } fmt.Println("Your wallet generation seed is:") fmt.Printf("%x\n", seed) fmt.Println("IMPORTANT: Keep the seed in a safe place as you\n" + "will NOT be able to restore your wallet without it.") fmt.Println("Please keep in mind that anyone who has access\n" + "to the seed can also restore your wallet thereby\n" + "giving them access to all your funds, so it is\n" + "imperative that you keep it in a secure location.") for { fmt.Print(`Once you have stored the seed in a safe ` + `and secure location, enter "OK" to continue: `) confirmSeed, err := reader.ReadString('\n') if err != nil { return nil, err } confirmSeed = strings.TrimSpace(confirmSeed) confirmSeed = strings.Trim(confirmSeed, `"`) if confirmSeed == "OK" { break } } return seed, nil } for { fmt.Print("Enter existing wallet seed: ") seedStr, err := reader.ReadString('\n') if err != nil { return nil, err } seedStr = strings.TrimSpace(strings.ToLower(seedStr)) seed, err := hex.DecodeString(seedStr) if err != nil || len(seed) < hdkeychain.MinSeedBytes || len(seed) > hdkeychain.MaxSeedBytes { fmt.Printf("Invalid seed specified. Must be a "+ "hexadecimal value that is at least %d bits and "+ "at most %d bits\n", hdkeychain.MinSeedBytes*8, hdkeychain.MaxSeedBytes*8) continue } return seed, nil } }
[ "func", "Seed", "(", "reader", "*", "bufio", ".", "Reader", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// Ascertain the wallet generation seed.", "useUserSeed", ",", "err", ":=", "promptListBool", "(", "reader", ",", "\"", "\"", "+", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "!", "useUserSeed", "{", "seed", ",", "err", ":=", "hdkeychain", ".", "GenerateSeed", "(", "hdkeychain", ".", "RecommendedSeedLen", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "fmt", ".", "Println", "(", "\"", "\"", ")", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "seed", ")", "\n", "fmt", ".", "Println", "(", "\"", "\\n", "\"", "+", "\"", "\"", ")", "\n", "fmt", ".", "Println", "(", "\"", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", "\"", ")", "\n\n", "for", "{", "fmt", ".", "Print", "(", "`Once you have stored the seed in a safe `", "+", "`and secure location, enter \"OK\" to continue: `", ")", "\n", "confirmSeed", ",", "err", ":=", "reader", ".", "ReadString", "(", "'\\n'", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "confirmSeed", "=", "strings", ".", "TrimSpace", "(", "confirmSeed", ")", "\n", "confirmSeed", "=", "strings", ".", "Trim", "(", "confirmSeed", ",", "`\"`", ")", "\n", "if", "confirmSeed", "==", "\"", "\"", "{", "break", "\n", "}", "\n", "}", "\n\n", "return", "seed", ",", "nil", "\n", "}", "\n\n", "for", "{", "fmt", ".", "Print", "(", "\"", "\"", ")", "\n", "seedStr", ",", "err", ":=", "reader", ".", "ReadString", "(", "'\\n'", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "seedStr", "=", "strings", ".", "TrimSpace", "(", "strings", ".", "ToLower", "(", "seedStr", ")", ")", "\n\n", "seed", ",", "err", ":=", "hex", ".", "DecodeString", "(", "seedStr", ")", "\n", "if", "err", "!=", "nil", "||", "len", "(", "seed", ")", "<", "hdkeychain", ".", "MinSeedBytes", "||", "len", "(", "seed", ")", ">", "hdkeychain", ".", "MaxSeedBytes", "{", "fmt", ".", "Printf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\\n", "\"", ",", "hdkeychain", ".", "MinSeedBytes", "*", "8", ",", "hdkeychain", ".", "MaxSeedBytes", "*", "8", ")", "\n", "continue", "\n", "}", "\n\n", "return", "seed", ",", "nil", "\n", "}", "\n", "}" ]
// Seed prompts the user whether they want to use an existing wallet generation // seed. When the user answers no, a seed will be generated and displayed to // the user along with prompting them for confirmation. When the user answers // yes, a the user is prompted for it. All prompts are repeated until the user // enters a valid response.
[ "Seed", "prompts", "the", "user", "whether", "they", "want", "to", "use", "an", "existing", "wallet", "generation", "seed", ".", "When", "the", "user", "answers", "no", "a", "seed", "will", "be", "generated", "and", "displayed", "to", "the", "user", "along", "with", "prompting", "them", "for", "confirmation", ".", "When", "the", "user", "answers", "yes", "a", "the", "user", "is", "prompted", "for", "it", ".", "All", "prompts", "are", "repeated", "until", "the", "user", "enters", "a", "valid", "response", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/prompt/prompt.go#L263-L323
train
btcsuite/btcwallet
waddrmgr/migrations.go
upgradeToVersion2
func upgradeToVersion2(ns walletdb.ReadWriteBucket) error { currentMgrVersion := uint32(2) _, err := ns.CreateBucketIfNotExists(usedAddrBucketName) if err != nil { str := "failed to create used addresses bucket" return managerError(ErrDatabase, str, err) } return putManagerVersion(ns, currentMgrVersion) }
go
func upgradeToVersion2(ns walletdb.ReadWriteBucket) error { currentMgrVersion := uint32(2) _, err := ns.CreateBucketIfNotExists(usedAddrBucketName) if err != nil { str := "failed to create used addresses bucket" return managerError(ErrDatabase, str, err) } return putManagerVersion(ns, currentMgrVersion) }
[ "func", "upgradeToVersion2", "(", "ns", "walletdb", ".", "ReadWriteBucket", ")", "error", "{", "currentMgrVersion", ":=", "uint32", "(", "2", ")", "\n\n", "_", ",", "err", ":=", "ns", ".", "CreateBucketIfNotExists", "(", "usedAddrBucketName", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "managerError", "(", "ErrDatabase", ",", "str", ",", "err", ")", "\n", "}", "\n\n", "return", "putManagerVersion", "(", "ns", ",", "currentMgrVersion", ")", "\n", "}" ]
// upgradeToVersion2 upgrades the database from version 1 to version 2 // 'usedAddrBucketName' a bucket for storing addrs flagged as marked is // initialized and it will be updated on the next rescan.
[ "upgradeToVersion2", "upgrades", "the", "database", "from", "version", "1", "to", "version", "2", "usedAddrBucketName", "a", "bucket", "for", "storing", "addrs", "flagged", "as", "marked", "is", "initialized", "and", "it", "will", "be", "updated", "on", "the", "next", "rescan", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/migrations.go#L105-L115
train
btcsuite/btcwallet
waddrmgr/migrations.go
upgradeToVersion5
func upgradeToVersion5(ns walletdb.ReadWriteBucket) error { // First, we'll check if there are any existing segwit addresses, which // can't be upgraded to the new version. If so, we abort and warn the // user. err := ns.NestedReadBucket(addrBucketName).ForEach( func(k []byte, v []byte) error { row, err := deserializeAddressRow(v) if err != nil { return err } if row.addrType > adtScript { return fmt.Errorf("segwit address exists in " + "wallet, can't upgrade from v4 to " + "v5: well, we tried ¯\\_(ツ)_/¯") } return nil }) if err != nil { return err } // Next, we'll write out the new database version. if err := putManagerVersion(ns, 5); err != nil { return err } // First, we'll need to create the new buckets that are used in the new // database version. scopeBucket, err := ns.CreateBucket(scopeBucketName) if err != nil { str := "failed to create scope bucket" return managerError(ErrDatabase, str, err) } scopeSchemas, err := ns.CreateBucket(scopeSchemaBucketName) if err != nil { str := "failed to create scope schema bucket" return managerError(ErrDatabase, str, err) } // With the buckets created, we can now create the default BIP0044 // scope which will be the only scope usable in the database after this // update. scopeKey := scopeToBytes(&KeyScopeBIP0044) scopeSchema := ScopeAddrMap[KeyScopeBIP0044] schemaBytes := scopeSchemaToBytes(&scopeSchema) if err := scopeSchemas.Put(scopeKey[:], schemaBytes); err != nil { return err } if err := createScopedManagerNS(scopeBucket, &KeyScopeBIP0044); err != nil { return err } bip44Bucket := scopeBucket.NestedReadWriteBucket(scopeKey[:]) // With the buckets created, we now need to port over *each* item in // the prior main bucket, into the new default scope. mainBucket := ns.NestedReadWriteBucket(mainBucketName) // First, we'll move over the encrypted coin type private and public // keys to the new sub-bucket. encCoinPrivKeys := mainBucket.Get(coinTypePrivKeyName) encCoinPubKeys := mainBucket.Get(coinTypePubKeyName) err = bip44Bucket.Put(coinTypePrivKeyName, encCoinPrivKeys) if err != nil { return err } err = bip44Bucket.Put(coinTypePubKeyName, encCoinPubKeys) if err != nil { return err } if err := mainBucket.Delete(coinTypePrivKeyName); err != nil { return err } if err := mainBucket.Delete(coinTypePubKeyName); err != nil { return err } // Next, we'll move over everything that was in the meta bucket to the // meta bucket within the new scope. metaBucket := ns.NestedReadWriteBucket(metaBucketName) lastAccount := metaBucket.Get(lastAccountName) if err := metaBucket.Delete(lastAccountName); err != nil { return err } scopedMetaBucket := bip44Bucket.NestedReadWriteBucket(metaBucketName) err = scopedMetaBucket.Put(lastAccountName, lastAccount) if err != nil { return err } // Finally, we'll recursively move over a set of keys which were // formerly under the main bucket, into the new scoped buckets. We'll // do so by obtaining a slice of all the keys that we need to modify // and then recursing through each of them, moving both nested buckets // and key/value pairs. keysToMigrate := [][]byte{ acctBucketName, addrBucketName, usedAddrBucketName, addrAcctIdxBucketName, acctNameIdxBucketName, acctIDIdxBucketName, } // Migrate each bucket recursively. for _, bucketKey := range keysToMigrate { err := migrateRecursively(ns, bip44Bucket, bucketKey) if err != nil { return err } } return nil }
go
func upgradeToVersion5(ns walletdb.ReadWriteBucket) error { // First, we'll check if there are any existing segwit addresses, which // can't be upgraded to the new version. If so, we abort and warn the // user. err := ns.NestedReadBucket(addrBucketName).ForEach( func(k []byte, v []byte) error { row, err := deserializeAddressRow(v) if err != nil { return err } if row.addrType > adtScript { return fmt.Errorf("segwit address exists in " + "wallet, can't upgrade from v4 to " + "v5: well, we tried ¯\\_(ツ)_/¯") } return nil }) if err != nil { return err } // Next, we'll write out the new database version. if err := putManagerVersion(ns, 5); err != nil { return err } // First, we'll need to create the new buckets that are used in the new // database version. scopeBucket, err := ns.CreateBucket(scopeBucketName) if err != nil { str := "failed to create scope bucket" return managerError(ErrDatabase, str, err) } scopeSchemas, err := ns.CreateBucket(scopeSchemaBucketName) if err != nil { str := "failed to create scope schema bucket" return managerError(ErrDatabase, str, err) } // With the buckets created, we can now create the default BIP0044 // scope which will be the only scope usable in the database after this // update. scopeKey := scopeToBytes(&KeyScopeBIP0044) scopeSchema := ScopeAddrMap[KeyScopeBIP0044] schemaBytes := scopeSchemaToBytes(&scopeSchema) if err := scopeSchemas.Put(scopeKey[:], schemaBytes); err != nil { return err } if err := createScopedManagerNS(scopeBucket, &KeyScopeBIP0044); err != nil { return err } bip44Bucket := scopeBucket.NestedReadWriteBucket(scopeKey[:]) // With the buckets created, we now need to port over *each* item in // the prior main bucket, into the new default scope. mainBucket := ns.NestedReadWriteBucket(mainBucketName) // First, we'll move over the encrypted coin type private and public // keys to the new sub-bucket. encCoinPrivKeys := mainBucket.Get(coinTypePrivKeyName) encCoinPubKeys := mainBucket.Get(coinTypePubKeyName) err = bip44Bucket.Put(coinTypePrivKeyName, encCoinPrivKeys) if err != nil { return err } err = bip44Bucket.Put(coinTypePubKeyName, encCoinPubKeys) if err != nil { return err } if err := mainBucket.Delete(coinTypePrivKeyName); err != nil { return err } if err := mainBucket.Delete(coinTypePubKeyName); err != nil { return err } // Next, we'll move over everything that was in the meta bucket to the // meta bucket within the new scope. metaBucket := ns.NestedReadWriteBucket(metaBucketName) lastAccount := metaBucket.Get(lastAccountName) if err := metaBucket.Delete(lastAccountName); err != nil { return err } scopedMetaBucket := bip44Bucket.NestedReadWriteBucket(metaBucketName) err = scopedMetaBucket.Put(lastAccountName, lastAccount) if err != nil { return err } // Finally, we'll recursively move over a set of keys which were // formerly under the main bucket, into the new scoped buckets. We'll // do so by obtaining a slice of all the keys that we need to modify // and then recursing through each of them, moving both nested buckets // and key/value pairs. keysToMigrate := [][]byte{ acctBucketName, addrBucketName, usedAddrBucketName, addrAcctIdxBucketName, acctNameIdxBucketName, acctIDIdxBucketName, } // Migrate each bucket recursively. for _, bucketKey := range keysToMigrate { err := migrateRecursively(ns, bip44Bucket, bucketKey) if err != nil { return err } } return nil }
[ "func", "upgradeToVersion5", "(", "ns", "walletdb", ".", "ReadWriteBucket", ")", "error", "{", "// First, we'll check if there are any existing segwit addresses, which", "// can't be upgraded to the new version. If so, we abort and warn the", "// user.", "err", ":=", "ns", ".", "NestedReadBucket", "(", "addrBucketName", ")", ".", "ForEach", "(", "func", "(", "k", "[", "]", "byte", ",", "v", "[", "]", "byte", ")", "error", "{", "row", ",", "err", ":=", "deserializeAddressRow", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "row", ".", "addrType", ">", "adtScript", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\\_", "", "", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Next, we'll write out the new database version.", "if", "err", ":=", "putManagerVersion", "(", "ns", ",", "5", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// First, we'll need to create the new buckets that are used in the new", "// database version.", "scopeBucket", ",", "err", ":=", "ns", ".", "CreateBucket", "(", "scopeBucketName", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "managerError", "(", "ErrDatabase", ",", "str", ",", "err", ")", "\n", "}", "\n", "scopeSchemas", ",", "err", ":=", "ns", ".", "CreateBucket", "(", "scopeSchemaBucketName", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "managerError", "(", "ErrDatabase", ",", "str", ",", "err", ")", "\n", "}", "\n\n", "// With the buckets created, we can now create the default BIP0044", "// scope which will be the only scope usable in the database after this", "// update.", "scopeKey", ":=", "scopeToBytes", "(", "&", "KeyScopeBIP0044", ")", "\n", "scopeSchema", ":=", "ScopeAddrMap", "[", "KeyScopeBIP0044", "]", "\n", "schemaBytes", ":=", "scopeSchemaToBytes", "(", "&", "scopeSchema", ")", "\n", "if", "err", ":=", "scopeSchemas", ".", "Put", "(", "scopeKey", "[", ":", "]", ",", "schemaBytes", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "createScopedManagerNS", "(", "scopeBucket", ",", "&", "KeyScopeBIP0044", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "bip44Bucket", ":=", "scopeBucket", ".", "NestedReadWriteBucket", "(", "scopeKey", "[", ":", "]", ")", "\n\n", "// With the buckets created, we now need to port over *each* item in", "// the prior main bucket, into the new default scope.", "mainBucket", ":=", "ns", ".", "NestedReadWriteBucket", "(", "mainBucketName", ")", "\n\n", "// First, we'll move over the encrypted coin type private and public", "// keys to the new sub-bucket.", "encCoinPrivKeys", ":=", "mainBucket", ".", "Get", "(", "coinTypePrivKeyName", ")", "\n", "encCoinPubKeys", ":=", "mainBucket", ".", "Get", "(", "coinTypePubKeyName", ")", "\n\n", "err", "=", "bip44Bucket", ".", "Put", "(", "coinTypePrivKeyName", ",", "encCoinPrivKeys", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "bip44Bucket", ".", "Put", "(", "coinTypePubKeyName", ",", "encCoinPubKeys", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "mainBucket", ".", "Delete", "(", "coinTypePrivKeyName", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "mainBucket", ".", "Delete", "(", "coinTypePubKeyName", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Next, we'll move over everything that was in the meta bucket to the", "// meta bucket within the new scope.", "metaBucket", ":=", "ns", ".", "NestedReadWriteBucket", "(", "metaBucketName", ")", "\n", "lastAccount", ":=", "metaBucket", ".", "Get", "(", "lastAccountName", ")", "\n", "if", "err", ":=", "metaBucket", ".", "Delete", "(", "lastAccountName", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "scopedMetaBucket", ":=", "bip44Bucket", ".", "NestedReadWriteBucket", "(", "metaBucketName", ")", "\n", "err", "=", "scopedMetaBucket", ".", "Put", "(", "lastAccountName", ",", "lastAccount", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Finally, we'll recursively move over a set of keys which were", "// formerly under the main bucket, into the new scoped buckets. We'll", "// do so by obtaining a slice of all the keys that we need to modify", "// and then recursing through each of them, moving both nested buckets", "// and key/value pairs.", "keysToMigrate", ":=", "[", "]", "[", "]", "byte", "{", "acctBucketName", ",", "addrBucketName", ",", "usedAddrBucketName", ",", "addrAcctIdxBucketName", ",", "acctNameIdxBucketName", ",", "acctIDIdxBucketName", ",", "}", "\n\n", "// Migrate each bucket recursively.", "for", "_", ",", "bucketKey", ":=", "range", "keysToMigrate", "{", "err", ":=", "migrateRecursively", "(", "ns", ",", "bip44Bucket", ",", "bucketKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// upgradeToVersion5 upgrades the database from version 4 to version 5. After // this update, the new ScopedKeyManager features cannot be used. This is due // to the fact that in version 5, we now store the encrypted master private // keys on disk. However, using the BIP0044 key scope, users will still be able // to create old p2pkh addresses.
[ "upgradeToVersion5", "upgrades", "the", "database", "from", "version", "4", "to", "version", "5", ".", "After", "this", "update", "the", "new", "ScopedKeyManager", "features", "cannot", "be", "used", ".", "This", "is", "due", "to", "the", "fact", "that", "in", "version", "5", "we", "now", "store", "the", "encrypted", "master", "private", "keys", "on", "disk", ".", "However", "using", "the", "BIP0044", "key", "scope", "users", "will", "still", "be", "able", "to", "create", "old", "p2pkh", "addresses", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/migrations.go#L122-L234
train
btcsuite/btcwallet
waddrmgr/migrations.go
migrateRecursively
func migrateRecursively(src, dst walletdb.ReadWriteBucket, bucketKey []byte) error { // Within this bucket key, we'll migrate over, then delete each key. bucketToMigrate := src.NestedReadWriteBucket(bucketKey) newBucket, err := dst.CreateBucketIfNotExists(bucketKey) if err != nil { return err } err = bucketToMigrate.ForEach(func(k, v []byte) error { if nestedBucket := bucketToMigrate. NestedReadBucket(k); nestedBucket != nil { // We have a nested bucket, so recurse into it. return migrateRecursively(bucketToMigrate, newBucket, k) } if err := newBucket.Put(k, v); err != nil { return err } return bucketToMigrate.Delete(k) }) if err != nil { return err } // Finally, we'll delete the bucket itself. if err := src.DeleteNestedBucket(bucketKey); err != nil { return err } return nil }
go
func migrateRecursively(src, dst walletdb.ReadWriteBucket, bucketKey []byte) error { // Within this bucket key, we'll migrate over, then delete each key. bucketToMigrate := src.NestedReadWriteBucket(bucketKey) newBucket, err := dst.CreateBucketIfNotExists(bucketKey) if err != nil { return err } err = bucketToMigrate.ForEach(func(k, v []byte) error { if nestedBucket := bucketToMigrate. NestedReadBucket(k); nestedBucket != nil { // We have a nested bucket, so recurse into it. return migrateRecursively(bucketToMigrate, newBucket, k) } if err := newBucket.Put(k, v); err != nil { return err } return bucketToMigrate.Delete(k) }) if err != nil { return err } // Finally, we'll delete the bucket itself. if err := src.DeleteNestedBucket(bucketKey); err != nil { return err } return nil }
[ "func", "migrateRecursively", "(", "src", ",", "dst", "walletdb", ".", "ReadWriteBucket", ",", "bucketKey", "[", "]", "byte", ")", "error", "{", "// Within this bucket key, we'll migrate over, then delete each key.", "bucketToMigrate", ":=", "src", ".", "NestedReadWriteBucket", "(", "bucketKey", ")", "\n", "newBucket", ",", "err", ":=", "dst", ".", "CreateBucketIfNotExists", "(", "bucketKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "bucketToMigrate", ".", "ForEach", "(", "func", "(", "k", ",", "v", "[", "]", "byte", ")", "error", "{", "if", "nestedBucket", ":=", "bucketToMigrate", ".", "NestedReadBucket", "(", "k", ")", ";", "nestedBucket", "!=", "nil", "{", "// We have a nested bucket, so recurse into it.", "return", "migrateRecursively", "(", "bucketToMigrate", ",", "newBucket", ",", "k", ")", "\n", "}", "\n\n", "if", "err", ":=", "newBucket", ".", "Put", "(", "k", ",", "v", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "bucketToMigrate", ".", "Delete", "(", "k", ")", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// Finally, we'll delete the bucket itself.", "if", "err", ":=", "src", ".", "DeleteNestedBucket", "(", "bucketKey", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// migrateRecursively moves a nested bucket from one bucket to another, // recursing into nested buckets as required.
[ "migrateRecursively", "moves", "a", "nested", "bucket", "from", "one", "bucket", "to", "another", "recursing", "into", "nested", "buckets", "as", "required", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/migrations.go#L238-L267
train
btcsuite/btcwallet
waddrmgr/migrations.go
resetSyncedBlockToBirthday
func resetSyncedBlockToBirthday(ns walletdb.ReadWriteBucket) error { syncBucket := ns.NestedReadWriteBucket(syncBucketName) if syncBucket == nil { return errors.New("sync bucket does not exist") } birthdayBlock, err := FetchBirthdayBlock(ns) if err != nil { return err } return PutSyncedTo(ns, &birthdayBlock) }
go
func resetSyncedBlockToBirthday(ns walletdb.ReadWriteBucket) error { syncBucket := ns.NestedReadWriteBucket(syncBucketName) if syncBucket == nil { return errors.New("sync bucket does not exist") } birthdayBlock, err := FetchBirthdayBlock(ns) if err != nil { return err } return PutSyncedTo(ns, &birthdayBlock) }
[ "func", "resetSyncedBlockToBirthday", "(", "ns", "walletdb", ".", "ReadWriteBucket", ")", "error", "{", "syncBucket", ":=", "ns", ".", "NestedReadWriteBucket", "(", "syncBucketName", ")", "\n", "if", "syncBucket", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "birthdayBlock", ",", "err", ":=", "FetchBirthdayBlock", "(", "ns", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "PutSyncedTo", "(", "ns", ",", "&", "birthdayBlock", ")", "\n", "}" ]
// resetSyncedBlockToBirthday is a migration that resets the wallet's currently // synced block to its birthday block. This essentially serves as a migration to // force a rescan of the wallet.
[ "resetSyncedBlockToBirthday", "is", "a", "migration", "that", "resets", "the", "wallet", "s", "currently", "synced", "block", "to", "its", "birthday", "block", ".", "This", "essentially", "serves", "as", "a", "migration", "to", "force", "a", "rescan", "of", "the", "wallet", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/migrations.go#L362-L374
train
btcsuite/btcwallet
wallet/notifications.go
TransactionNotifications
func (s *NotificationServer) TransactionNotifications() TransactionNotificationsClient { c := make(chan *TransactionNotifications) s.mu.Lock() s.transactions = append(s.transactions, c) s.mu.Unlock() return TransactionNotificationsClient{ C: c, server: s, } }
go
func (s *NotificationServer) TransactionNotifications() TransactionNotificationsClient { c := make(chan *TransactionNotifications) s.mu.Lock() s.transactions = append(s.transactions, c) s.mu.Unlock() return TransactionNotificationsClient{ C: c, server: s, } }
[ "func", "(", "s", "*", "NotificationServer", ")", "TransactionNotifications", "(", ")", "TransactionNotificationsClient", "{", "c", ":=", "make", "(", "chan", "*", "TransactionNotifications", ")", "\n", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "s", ".", "transactions", "=", "append", "(", "s", ".", "transactions", ",", "c", ")", "\n", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "TransactionNotificationsClient", "{", "C", ":", "c", ",", "server", ":", "s", ",", "}", "\n", "}" ]
// TransactionNotifications returns a client for receiving // TransactionNotifiations notifications over a channel. The channel is // unbuffered. // // When finished, the Done method should be called on the client to disassociate // it from the server.
[ "TransactionNotifications", "returns", "a", "client", "for", "receiving", "TransactionNotifiations", "notifications", "over", "a", "channel", ".", "The", "channel", "is", "unbuffered", ".", "When", "finished", "the", "Done", "method", "should", "be", "called", "on", "the", "client", "to", "disassociate", "it", "from", "the", "server", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/notifications.go#L411-L420
train
btcsuite/btcwallet
wallet/notifications.go
Spender
func (n *SpentnessNotifications) Spender() (*chainhash.Hash, uint32, bool) { return n.spenderHash, n.spenderIndex, n.spenderHash != nil }
go
func (n *SpentnessNotifications) Spender() (*chainhash.Hash, uint32, bool) { return n.spenderHash, n.spenderIndex, n.spenderHash != nil }
[ "func", "(", "n", "*", "SpentnessNotifications", ")", "Spender", "(", ")", "(", "*", "chainhash", ".", "Hash", ",", "uint32", ",", "bool", ")", "{", "return", "n", ".", "spenderHash", ",", "n", ".", "spenderIndex", ",", "n", ".", "spenderHash", "!=", "nil", "\n", "}" ]
// Spender returns the spending transction's hash and input index, if any. If // the output is unspent, the final bool return is false.
[ "Spender", "returns", "the", "spending", "transction", "s", "hash", "and", "input", "index", "if", "any", ".", "If", "the", "output", "is", "unspent", "the", "final", "bool", "return", "is", "false", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/notifications.go#L472-L474
train
btcsuite/btcwallet
wallet/notifications.go
notifyUnspentOutput
func (s *NotificationServer) notifyUnspentOutput(account uint32, hash *chainhash.Hash, index uint32) { defer s.mu.Unlock() s.mu.Lock() clients := s.spentness[account] if len(clients) == 0 { return } n := &SpentnessNotifications{ hash: hash, index: index, } for _, c := range clients { c <- n } }
go
func (s *NotificationServer) notifyUnspentOutput(account uint32, hash *chainhash.Hash, index uint32) { defer s.mu.Unlock() s.mu.Lock() clients := s.spentness[account] if len(clients) == 0 { return } n := &SpentnessNotifications{ hash: hash, index: index, } for _, c := range clients { c <- n } }
[ "func", "(", "s", "*", "NotificationServer", ")", "notifyUnspentOutput", "(", "account", "uint32", ",", "hash", "*", "chainhash", ".", "Hash", ",", "index", "uint32", ")", "{", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "clients", ":=", "s", ".", "spentness", "[", "account", "]", "\n", "if", "len", "(", "clients", ")", "==", "0", "{", "return", "\n", "}", "\n", "n", ":=", "&", "SpentnessNotifications", "{", "hash", ":", "hash", ",", "index", ":", "index", ",", "}", "\n", "for", "_", ",", "c", ":=", "range", "clients", "{", "c", "<-", "n", "\n", "}", "\n", "}" ]
// notifyUnspentOutput notifies registered clients of a new unspent output that // is controlled by the wallet.
[ "notifyUnspentOutput", "notifies", "registered", "clients", "of", "a", "new", "unspent", "output", "that", "is", "controlled", "by", "the", "wallet", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/notifications.go#L478-L492
train
btcsuite/btcwallet
wallet/notifications.go
notifySpentOutput
func (s *NotificationServer) notifySpentOutput(account uint32, op *wire.OutPoint, spenderHash *chainhash.Hash, spenderIndex uint32) { defer s.mu.Unlock() s.mu.Lock() clients := s.spentness[account] if len(clients) == 0 { return } n := &SpentnessNotifications{ hash: &op.Hash, index: op.Index, spenderHash: spenderHash, spenderIndex: spenderIndex, } for _, c := range clients { c <- n } }
go
func (s *NotificationServer) notifySpentOutput(account uint32, op *wire.OutPoint, spenderHash *chainhash.Hash, spenderIndex uint32) { defer s.mu.Unlock() s.mu.Lock() clients := s.spentness[account] if len(clients) == 0 { return } n := &SpentnessNotifications{ hash: &op.Hash, index: op.Index, spenderHash: spenderHash, spenderIndex: spenderIndex, } for _, c := range clients { c <- n } }
[ "func", "(", "s", "*", "NotificationServer", ")", "notifySpentOutput", "(", "account", "uint32", ",", "op", "*", "wire", ".", "OutPoint", ",", "spenderHash", "*", "chainhash", ".", "Hash", ",", "spenderIndex", "uint32", ")", "{", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "clients", ":=", "s", ".", "spentness", "[", "account", "]", "\n", "if", "len", "(", "clients", ")", "==", "0", "{", "return", "\n", "}", "\n", "n", ":=", "&", "SpentnessNotifications", "{", "hash", ":", "&", "op", ".", "Hash", ",", "index", ":", "op", ".", "Index", ",", "spenderHash", ":", "spenderHash", ",", "spenderIndex", ":", "spenderIndex", ",", "}", "\n", "for", "_", ",", "c", ":=", "range", "clients", "{", "c", "<-", "n", "\n", "}", "\n", "}" ]
// notifySpentOutput notifies registered clients that a previously-unspent // output is now spent, and includes the spender hash and input index in the // notification.
[ "notifySpentOutput", "notifies", "registered", "clients", "that", "a", "previously", "-", "unspent", "output", "is", "now", "spent", "and", "includes", "the", "spender", "hash", "and", "input", "index", "in", "the", "notification", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/notifications.go#L497-L513
train
btcsuite/btcwallet
wallet/notifications.go
AccountSpentnessNotifications
func (s *NotificationServer) AccountSpentnessNotifications(account uint32) SpentnessNotificationsClient { c := make(chan *SpentnessNotifications) s.mu.Lock() s.spentness[account] = append(s.spentness[account], c) s.mu.Unlock() return SpentnessNotificationsClient{ C: c, account: account, server: s, } }
go
func (s *NotificationServer) AccountSpentnessNotifications(account uint32) SpentnessNotificationsClient { c := make(chan *SpentnessNotifications) s.mu.Lock() s.spentness[account] = append(s.spentness[account], c) s.mu.Unlock() return SpentnessNotificationsClient{ C: c, account: account, server: s, } }
[ "func", "(", "s", "*", "NotificationServer", ")", "AccountSpentnessNotifications", "(", "account", "uint32", ")", "SpentnessNotificationsClient", "{", "c", ":=", "make", "(", "chan", "*", "SpentnessNotifications", ")", "\n", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "s", ".", "spentness", "[", "account", "]", "=", "append", "(", "s", ".", "spentness", "[", "account", "]", ",", "c", ")", "\n", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "SpentnessNotificationsClient", "{", "C", ":", "c", ",", "account", ":", "account", ",", "server", ":", "s", ",", "}", "\n", "}" ]
// AccountSpentnessNotifications registers a client for spentness changes of // outputs controlled by the account.
[ "AccountSpentnessNotifications", "registers", "a", "client", "for", "spentness", "changes", "of", "outputs", "controlled", "by", "the", "account", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/notifications.go#L525-L535
train
btcsuite/btcwallet
wallet/notifications.go
AccountNotifications
func (s *NotificationServer) AccountNotifications() AccountNotificationsClient { c := make(chan *AccountNotification) s.mu.Lock() s.accountClients = append(s.accountClients, c) s.mu.Unlock() return AccountNotificationsClient{ C: c, server: s, } }
go
func (s *NotificationServer) AccountNotifications() AccountNotificationsClient { c := make(chan *AccountNotification) s.mu.Lock() s.accountClients = append(s.accountClients, c) s.mu.Unlock() return AccountNotificationsClient{ C: c, server: s, } }
[ "func", "(", "s", "*", "NotificationServer", ")", "AccountNotifications", "(", ")", "AccountNotificationsClient", "{", "c", ":=", "make", "(", "chan", "*", "AccountNotification", ")", "\n", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "s", ".", "accountClients", "=", "append", "(", "s", ".", "accountClients", ",", "c", ")", "\n", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "AccountNotificationsClient", "{", "C", ":", "c", ",", "server", ":", "s", ",", "}", "\n", "}" ]
// AccountNotifications returns a client for receiving AccountNotifications over // a channel. The channel is unbuffered. When finished, the client's Done // method should be called to disassociate the client from the server.
[ "AccountNotifications", "returns", "a", "client", "for", "receiving", "AccountNotifications", "over", "a", "channel", ".", "The", "channel", "is", "unbuffered", ".", "When", "finished", "the", "client", "s", "Done", "method", "should", "be", "called", "to", "disassociate", "the", "client", "from", "the", "server", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/notifications.go#L602-L611
train
btcsuite/btcwallet
internal/cfgutil/explicitflags.go
UnmarshalFlag
func (e *ExplicitString) UnmarshalFlag(value string) error { e.Value = value e.explicitlySet = true return nil }
go
func (e *ExplicitString) UnmarshalFlag(value string) error { e.Value = value e.explicitlySet = true return nil }
[ "func", "(", "e", "*", "ExplicitString", ")", "UnmarshalFlag", "(", "value", "string", ")", "error", "{", "e", ".", "Value", "=", "value", "\n", "e", ".", "explicitlySet", "=", "true", "\n", "return", "nil", "\n", "}" ]
// UnmarshalFlag implements the flags.Unmarshaler interface.
[ "UnmarshalFlag", "implements", "the", "flags", ".", "Unmarshaler", "interface", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/cfgutil/explicitflags.go#L32-L36
train
btcsuite/btcwallet
walletdb/interface.go
RegisterDriver
func RegisterDriver(driver Driver) error { if _, exists := drivers[driver.DbType]; exists { return ErrDbTypeRegistered } drivers[driver.DbType] = &driver return nil }
go
func RegisterDriver(driver Driver) error { if _, exists := drivers[driver.DbType]; exists { return ErrDbTypeRegistered } drivers[driver.DbType] = &driver return nil }
[ "func", "RegisterDriver", "(", "driver", "Driver", ")", "error", "{", "if", "_", ",", "exists", ":=", "drivers", "[", "driver", ".", "DbType", "]", ";", "exists", "{", "return", "ErrDbTypeRegistered", "\n", "}", "\n\n", "drivers", "[", "driver", ".", "DbType", "]", "=", "&", "driver", "\n", "return", "nil", "\n", "}" ]
// RegisterDriver adds a backend database driver to available interfaces. // ErrDbTypeRegistered will be retruned if the database type for the driver has // already been registered.
[ "RegisterDriver", "adds", "a", "backend", "database", "driver", "to", "available", "interfaces", ".", "ErrDbTypeRegistered", "will", "be", "retruned", "if", "the", "database", "type", "for", "the", "driver", "has", "already", "been", "registered", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/walletdb/interface.go#L259-L266
train
btcsuite/btcwallet
walletdb/interface.go
Open
func Open(dbType string, args ...interface{}) (DB, error) { drv, exists := drivers[dbType] if !exists { return nil, ErrDbUnknownType } return drv.Open(args...) }
go
func Open(dbType string, args ...interface{}) (DB, error) { drv, exists := drivers[dbType] if !exists { return nil, ErrDbUnknownType } return drv.Open(args...) }
[ "func", "Open", "(", "dbType", "string", ",", "args", "...", "interface", "{", "}", ")", "(", "DB", ",", "error", ")", "{", "drv", ",", "exists", ":=", "drivers", "[", "dbType", "]", "\n", "if", "!", "exists", "{", "return", "nil", ",", "ErrDbUnknownType", "\n", "}", "\n\n", "return", "drv", ".", "Open", "(", "args", "...", ")", "\n", "}" ]
// Open opens an existing database for the specified type. The arguments are // specific to the database type driver. See the documentation for the database // driver for further details. // // ErrDbUnknownType will be returned if the the database type is not registered.
[ "Open", "opens", "an", "existing", "database", "for", "the", "specified", "type", ".", "The", "arguments", "are", "specific", "to", "the", "database", "type", "driver", ".", "See", "the", "documentation", "for", "the", "database", "driver", "for", "further", "details", ".", "ErrDbUnknownType", "will", "be", "returned", "if", "the", "the", "database", "type", "is", "not", "registered", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/walletdb/interface.go#L297-L304
train
btcsuite/btcwallet
waddrmgr/error.go
managerError
func managerError(c ErrorCode, desc string, err error) ManagerError { return ManagerError{ErrorCode: c, Description: desc, Err: err} }
go
func managerError(c ErrorCode, desc string, err error) ManagerError { return ManagerError{ErrorCode: c, Description: desc, Err: err} }
[ "func", "managerError", "(", "c", "ErrorCode", ",", "desc", "string", ",", "err", "error", ")", "ManagerError", "{", "return", "ManagerError", "{", "ErrorCode", ":", "c", ",", "Description", ":", "desc", ",", "Err", ":", "err", "}", "\n", "}" ]
// managerError creates a ManagerError given a set of arguments.
[ "managerError", "creates", "a", "ManagerError", "given", "a", "set", "of", "arguments", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/error.go#L206-L208
train
btcsuite/btcwallet
waddrmgr/error.go
IsError
func IsError(err error, code ErrorCode) bool { e, ok := err.(ManagerError) return ok && e.ErrorCode == code }
go
func IsError(err error, code ErrorCode) bool { e, ok := err.(ManagerError) return ok && e.ErrorCode == code }
[ "func", "IsError", "(", "err", "error", ",", "code", "ErrorCode", ")", "bool", "{", "e", ",", "ok", ":=", "err", ".", "(", "ManagerError", ")", "\n", "return", "ok", "&&", "e", ".", "ErrorCode", "==", "code", "\n", "}" ]
// IsError returns whether the error is a ManagerError with a matching error // code.
[ "IsError", "returns", "whether", "the", "error", "is", "a", "ManagerError", "with", "a", "matching", "error", "code", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/error.go#L216-L219
train
btcsuite/btcwallet
config.go
supportedSubsystems
func supportedSubsystems() []string { // Convert the subsystemLoggers map keys to a slice. subsystems := make([]string, 0, len(subsystemLoggers)) for subsysID := range subsystemLoggers { subsystems = append(subsystems, subsysID) } // Sort the subsytems for stable display. sort.Strings(subsystems) return subsystems }
go
func supportedSubsystems() []string { // Convert the subsystemLoggers map keys to a slice. subsystems := make([]string, 0, len(subsystemLoggers)) for subsysID := range subsystemLoggers { subsystems = append(subsystems, subsysID) } // Sort the subsytems for stable display. sort.Strings(subsystems) return subsystems }
[ "func", "supportedSubsystems", "(", ")", "[", "]", "string", "{", "// Convert the subsystemLoggers map keys to a slice.", "subsystems", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "subsystemLoggers", ")", ")", "\n", "for", "subsysID", ":=", "range", "subsystemLoggers", "{", "subsystems", "=", "append", "(", "subsystems", ",", "subsysID", ")", "\n", "}", "\n\n", "// Sort the subsytems for stable display.", "sort", ".", "Strings", "(", "subsystems", ")", "\n", "return", "subsystems", "\n", "}" ]
// supportedSubsystems returns a sorted slice of the supported subsystems for // logging purposes.
[ "supportedSubsystems", "returns", "a", "sorted", "slice", "of", "the", "supported", "subsystems", "for", "logging", "purposes", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/config.go#L181-L191
train
btcsuite/btcwallet
chain/neutrino.go
NewNeutrinoClient
func NewNeutrinoClient(chainParams *chaincfg.Params, chainService *neutrino.ChainService) *NeutrinoClient { return &NeutrinoClient{ CS: chainService, chainParams: chainParams, } }
go
func NewNeutrinoClient(chainParams *chaincfg.Params, chainService *neutrino.ChainService) *NeutrinoClient { return &NeutrinoClient{ CS: chainService, chainParams: chainParams, } }
[ "func", "NewNeutrinoClient", "(", "chainParams", "*", "chaincfg", ".", "Params", ",", "chainService", "*", "neutrino", ".", "ChainService", ")", "*", "NeutrinoClient", "{", "return", "&", "NeutrinoClient", "{", "CS", ":", "chainService", ",", "chainParams", ":", "chainParams", ",", "}", "\n", "}" ]
// NewNeutrinoClient creates a new NeutrinoClient struct with a backing // ChainService.
[ "NewNeutrinoClient", "creates", "a", "new", "NeutrinoClient", "struct", "with", "a", "backing", "ChainService", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/neutrino.go#L52-L59
train
btcsuite/btcwallet
chain/neutrino.go
Start
func (s *NeutrinoClient) Start() error { s.CS.Start() s.clientMtx.Lock() defer s.clientMtx.Unlock() if !s.started { s.enqueueNotification = make(chan interface{}) s.dequeueNotification = make(chan interface{}) s.currentBlock = make(chan *waddrmgr.BlockStamp) s.quit = make(chan struct{}) s.started = true s.wg.Add(1) go func() { select { case s.enqueueNotification <- ClientConnected{}: case <-s.quit: } }() go s.notificationHandler() } return nil }
go
func (s *NeutrinoClient) Start() error { s.CS.Start() s.clientMtx.Lock() defer s.clientMtx.Unlock() if !s.started { s.enqueueNotification = make(chan interface{}) s.dequeueNotification = make(chan interface{}) s.currentBlock = make(chan *waddrmgr.BlockStamp) s.quit = make(chan struct{}) s.started = true s.wg.Add(1) go func() { select { case s.enqueueNotification <- ClientConnected{}: case <-s.quit: } }() go s.notificationHandler() } return nil }
[ "func", "(", "s", "*", "NeutrinoClient", ")", "Start", "(", ")", "error", "{", "s", ".", "CS", ".", "Start", "(", ")", "\n", "s", ".", "clientMtx", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "clientMtx", ".", "Unlock", "(", ")", "\n", "if", "!", "s", ".", "started", "{", "s", ".", "enqueueNotification", "=", "make", "(", "chan", "interface", "{", "}", ")", "\n", "s", ".", "dequeueNotification", "=", "make", "(", "chan", "interface", "{", "}", ")", "\n", "s", ".", "currentBlock", "=", "make", "(", "chan", "*", "waddrmgr", ".", "BlockStamp", ")", "\n", "s", ".", "quit", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "s", ".", "started", "=", "true", "\n", "s", ".", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "select", "{", "case", "s", ".", "enqueueNotification", "<-", "ClientConnected", "{", "}", ":", "case", "<-", "s", ".", "quit", ":", "}", "\n", "}", "(", ")", "\n", "go", "s", ".", "notificationHandler", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Start replicates the RPC client's Start method.
[ "Start", "replicates", "the", "RPC", "client", "s", "Start", "method", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/neutrino.go#L67-L87
train
btcsuite/btcwallet
chain/neutrino.go
Stop
func (s *NeutrinoClient) Stop() { s.clientMtx.Lock() defer s.clientMtx.Unlock() if !s.started { return } close(s.quit) s.started = false }
go
func (s *NeutrinoClient) Stop() { s.clientMtx.Lock() defer s.clientMtx.Unlock() if !s.started { return } close(s.quit) s.started = false }
[ "func", "(", "s", "*", "NeutrinoClient", ")", "Stop", "(", ")", "{", "s", ".", "clientMtx", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "clientMtx", ".", "Unlock", "(", ")", "\n", "if", "!", "s", ".", "started", "{", "return", "\n", "}", "\n", "close", "(", "s", ".", "quit", ")", "\n", "s", ".", "started", "=", "false", "\n", "}" ]
// Stop replicates the RPC client's Stop method.
[ "Stop", "replicates", "the", "RPC", "client", "s", "Stop", "method", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/neutrino.go#L90-L98
train
btcsuite/btcwallet
chain/neutrino.go
GetBlock
func (s *NeutrinoClient) GetBlock(hash *chainhash.Hash) (*wire.MsgBlock, error) { // TODO(roasbeef): add a block cache? // * which evication strategy? depends on use case // Should the block cache be INSIDE neutrino instead of in btcwallet? block, err := s.CS.GetBlock(*hash) if err != nil { return nil, err } return block.MsgBlock(), nil }
go
func (s *NeutrinoClient) GetBlock(hash *chainhash.Hash) (*wire.MsgBlock, error) { // TODO(roasbeef): add a block cache? // * which evication strategy? depends on use case // Should the block cache be INSIDE neutrino instead of in btcwallet? block, err := s.CS.GetBlock(*hash) if err != nil { return nil, err } return block.MsgBlock(), nil }
[ "func", "(", "s", "*", "NeutrinoClient", ")", "GetBlock", "(", "hash", "*", "chainhash", ".", "Hash", ")", "(", "*", "wire", ".", "MsgBlock", ",", "error", ")", "{", "// TODO(roasbeef): add a block cache?", "// * which evication strategy? depends on use case", "// Should the block cache be INSIDE neutrino instead of in btcwallet?", "block", ",", "err", ":=", "s", ".", "CS", ".", "GetBlock", "(", "*", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "block", ".", "MsgBlock", "(", ")", ",", "nil", "\n", "}" ]
// GetBlock replicates the RPC client's GetBlock command.
[ "GetBlock", "replicates", "the", "RPC", "client", "s", "GetBlock", "command", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/neutrino.go#L106-L115
train
btcsuite/btcwallet
chain/neutrino.go
GetBlockHeight
func (s *NeutrinoClient) GetBlockHeight(hash *chainhash.Hash) (int32, error) { return s.CS.GetBlockHeight(hash) }
go
func (s *NeutrinoClient) GetBlockHeight(hash *chainhash.Hash) (int32, error) { return s.CS.GetBlockHeight(hash) }
[ "func", "(", "s", "*", "NeutrinoClient", ")", "GetBlockHeight", "(", "hash", "*", "chainhash", ".", "Hash", ")", "(", "int32", ",", "error", ")", "{", "return", "s", ".", "CS", ".", "GetBlockHeight", "(", "hash", ")", "\n", "}" ]
// GetBlockHeight gets the height of a block by its hash. It serves as a // replacement for the use of GetBlockVerboseTxAsync for the wallet package // since we can't actually return a FutureGetBlockVerboseResult because the // underlying type is private to rpcclient.
[ "GetBlockHeight", "gets", "the", "height", "of", "a", "block", "by", "its", "hash", ".", "It", "serves", "as", "a", "replacement", "for", "the", "use", "of", "GetBlockVerboseTxAsync", "for", "the", "wallet", "package", "since", "we", "can", "t", "actually", "return", "a", "FutureGetBlockVerboseResult", "because", "the", "underlying", "type", "is", "private", "to", "rpcclient", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/neutrino.go#L121-L123
train
btcsuite/btcwallet
chain/neutrino.go
GetBestBlock
func (s *NeutrinoClient) GetBestBlock() (*chainhash.Hash, int32, error) { chainTip, err := s.CS.BestBlock() if err != nil { return nil, 0, err } return &chainTip.Hash, chainTip.Height, nil }
go
func (s *NeutrinoClient) GetBestBlock() (*chainhash.Hash, int32, error) { chainTip, err := s.CS.BestBlock() if err != nil { return nil, 0, err } return &chainTip.Hash, chainTip.Height, nil }
[ "func", "(", "s", "*", "NeutrinoClient", ")", "GetBestBlock", "(", ")", "(", "*", "chainhash", ".", "Hash", ",", "int32", ",", "error", ")", "{", "chainTip", ",", "err", ":=", "s", ".", "CS", ".", "BestBlock", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "err", "\n", "}", "\n\n", "return", "&", "chainTip", ".", "Hash", ",", "chainTip", ".", "Height", ",", "nil", "\n", "}" ]
// GetBestBlock replicates the RPC client's GetBestBlock command.
[ "GetBestBlock", "replicates", "the", "RPC", "client", "s", "GetBestBlock", "command", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/neutrino.go#L126-L133
train
btcsuite/btcwallet
chain/neutrino.go
GetBlockHash
func (s *NeutrinoClient) GetBlockHash(height int64) (*chainhash.Hash, error) { return s.CS.GetBlockHash(height) }
go
func (s *NeutrinoClient) GetBlockHash(height int64) (*chainhash.Hash, error) { return s.CS.GetBlockHash(height) }
[ "func", "(", "s", "*", "NeutrinoClient", ")", "GetBlockHash", "(", "height", "int64", ")", "(", "*", "chainhash", ".", "Hash", ",", "error", ")", "{", "return", "s", ".", "CS", ".", "GetBlockHash", "(", "height", ")", "\n", "}" ]
// GetBlockHash returns the block hash for the given height, or an error if the // client has been shut down or the hash at the block height doesn't exist or // is unknown.
[ "GetBlockHash", "returns", "the", "block", "hash", "for", "the", "given", "height", "or", "an", "error", "if", "the", "client", "has", "been", "shut", "down", "or", "the", "hash", "at", "the", "block", "height", "doesn", "t", "exist", "or", "is", "unknown", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/neutrino.go#L149-L151
train
btcsuite/btcwallet
chain/neutrino.go
GetBlockHeader
func (s *NeutrinoClient) GetBlockHeader( blockHash *chainhash.Hash) (*wire.BlockHeader, error) { return s.CS.GetBlockHeader(blockHash) }
go
func (s *NeutrinoClient) GetBlockHeader( blockHash *chainhash.Hash) (*wire.BlockHeader, error) { return s.CS.GetBlockHeader(blockHash) }
[ "func", "(", "s", "*", "NeutrinoClient", ")", "GetBlockHeader", "(", "blockHash", "*", "chainhash", ".", "Hash", ")", "(", "*", "wire", ".", "BlockHeader", ",", "error", ")", "{", "return", "s", ".", "CS", ".", "GetBlockHeader", "(", "blockHash", ")", "\n", "}" ]
// GetBlockHeader returns the block header for the given block hash, or an error // if the client has been shut down or the hash doesn't exist or is unknown.
[ "GetBlockHeader", "returns", "the", "block", "header", "for", "the", "given", "block", "hash", "or", "an", "error", "if", "the", "client", "has", "been", "shut", "down", "or", "the", "hash", "doesn", "t", "exist", "or", "is", "unknown", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/neutrino.go#L155-L158
train
btcsuite/btcwallet
chain/neutrino.go
SendRawTransaction
func (s *NeutrinoClient) SendRawTransaction(tx *wire.MsgTx, allowHighFees bool) ( *chainhash.Hash, error) { err := s.CS.SendTransaction(tx) if err != nil { return nil, err } hash := tx.TxHash() return &hash, nil }
go
func (s *NeutrinoClient) SendRawTransaction(tx *wire.MsgTx, allowHighFees bool) ( *chainhash.Hash, error) { err := s.CS.SendTransaction(tx) if err != nil { return nil, err } hash := tx.TxHash() return &hash, nil }
[ "func", "(", "s", "*", "NeutrinoClient", ")", "SendRawTransaction", "(", "tx", "*", "wire", ".", "MsgTx", ",", "allowHighFees", "bool", ")", "(", "*", "chainhash", ".", "Hash", ",", "error", ")", "{", "err", ":=", "s", ".", "CS", ".", "SendTransaction", "(", "tx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "hash", ":=", "tx", ".", "TxHash", "(", ")", "\n", "return", "&", "hash", ",", "nil", "\n", "}" ]
// SendRawTransaction replicates the RPC client's SendRawTransaction command.
[ "SendRawTransaction", "replicates", "the", "RPC", "client", "s", "SendRawTransaction", "command", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/neutrino.go#L161-L169
train
btcsuite/btcwallet
chain/neutrino.go
buildFilterBlocksWatchList
func buildFilterBlocksWatchList(req *FilterBlocksRequest) ([][]byte, error) { // Construct a watch list containing the script addresses of all // internal and external addresses that were requested, in addition to // the set of outpoints currently being watched. watchListSize := len(req.ExternalAddrs) + len(req.InternalAddrs) + len(req.WatchedOutPoints) watchList := make([][]byte, 0, watchListSize) for _, addr := range req.ExternalAddrs { p2shAddr, err := txscript.PayToAddrScript(addr) if err != nil { return nil, err } watchList = append(watchList, p2shAddr) } for _, addr := range req.InternalAddrs { p2shAddr, err := txscript.PayToAddrScript(addr) if err != nil { return nil, err } watchList = append(watchList, p2shAddr) } for _, addr := range req.WatchedOutPoints { addr, err := txscript.PayToAddrScript(addr) if err != nil { return nil, err } watchList = append(watchList, addr) } return watchList, nil }
go
func buildFilterBlocksWatchList(req *FilterBlocksRequest) ([][]byte, error) { // Construct a watch list containing the script addresses of all // internal and external addresses that were requested, in addition to // the set of outpoints currently being watched. watchListSize := len(req.ExternalAddrs) + len(req.InternalAddrs) + len(req.WatchedOutPoints) watchList := make([][]byte, 0, watchListSize) for _, addr := range req.ExternalAddrs { p2shAddr, err := txscript.PayToAddrScript(addr) if err != nil { return nil, err } watchList = append(watchList, p2shAddr) } for _, addr := range req.InternalAddrs { p2shAddr, err := txscript.PayToAddrScript(addr) if err != nil { return nil, err } watchList = append(watchList, p2shAddr) } for _, addr := range req.WatchedOutPoints { addr, err := txscript.PayToAddrScript(addr) if err != nil { return nil, err } watchList = append(watchList, addr) } return watchList, nil }
[ "func", "buildFilterBlocksWatchList", "(", "req", "*", "FilterBlocksRequest", ")", "(", "[", "]", "[", "]", "byte", ",", "error", ")", "{", "// Construct a watch list containing the script addresses of all", "// internal and external addresses that were requested, in addition to", "// the set of outpoints currently being watched.", "watchListSize", ":=", "len", "(", "req", ".", "ExternalAddrs", ")", "+", "len", "(", "req", ".", "InternalAddrs", ")", "+", "len", "(", "req", ".", "WatchedOutPoints", ")", "\n\n", "watchList", ":=", "make", "(", "[", "]", "[", "]", "byte", ",", "0", ",", "watchListSize", ")", "\n\n", "for", "_", ",", "addr", ":=", "range", "req", ".", "ExternalAddrs", "{", "p2shAddr", ",", "err", ":=", "txscript", ".", "PayToAddrScript", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "watchList", "=", "append", "(", "watchList", ",", "p2shAddr", ")", "\n", "}", "\n\n", "for", "_", ",", "addr", ":=", "range", "req", ".", "InternalAddrs", "{", "p2shAddr", ",", "err", ":=", "txscript", ".", "PayToAddrScript", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "watchList", "=", "append", "(", "watchList", ",", "p2shAddr", ")", "\n", "}", "\n\n", "for", "_", ",", "addr", ":=", "range", "req", ".", "WatchedOutPoints", "{", "addr", ",", "err", ":=", "txscript", ".", "PayToAddrScript", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "watchList", "=", "append", "(", "watchList", ",", "addr", ")", "\n", "}", "\n\n", "return", "watchList", ",", "nil", "\n", "}" ]
// buildFilterBlocksWatchList constructs a watchlist used for matching against a // cfilter from a FilterBlocksRequest. The watchlist will be populated with all // external addresses, internal addresses, and outpoints contained in the // request.
[ "buildFilterBlocksWatchList", "constructs", "a", "watchlist", "used", "for", "matching", "against", "a", "cfilter", "from", "a", "FilterBlocksRequest", ".", "The", "watchlist", "will", "be", "populated", "with", "all", "external", "addresses", "internal", "addresses", "and", "outpoints", "contained", "in", "the", "request", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/neutrino.go#L252-L290
train
btcsuite/btcwallet
chain/neutrino.go
pollCFilter
func (s *NeutrinoClient) pollCFilter(hash *chainhash.Hash) (*gcs.Filter, error) { var ( filter *gcs.Filter err error count int ) const maxFilterRetries = 50 for count < maxFilterRetries { if count > 0 { time.Sleep(100 * time.Millisecond) } filter, err = s.CS.GetCFilter(*hash, wire.GCSFilterRegular) if err != nil { count++ continue } return filter, nil } return nil, err }
go
func (s *NeutrinoClient) pollCFilter(hash *chainhash.Hash) (*gcs.Filter, error) { var ( filter *gcs.Filter err error count int ) const maxFilterRetries = 50 for count < maxFilterRetries { if count > 0 { time.Sleep(100 * time.Millisecond) } filter, err = s.CS.GetCFilter(*hash, wire.GCSFilterRegular) if err != nil { count++ continue } return filter, nil } return nil, err }
[ "func", "(", "s", "*", "NeutrinoClient", ")", "pollCFilter", "(", "hash", "*", "chainhash", ".", "Hash", ")", "(", "*", "gcs", ".", "Filter", ",", "error", ")", "{", "var", "(", "filter", "*", "gcs", ".", "Filter", "\n", "err", "error", "\n", "count", "int", "\n", ")", "\n\n", "const", "maxFilterRetries", "=", "50", "\n", "for", "count", "<", "maxFilterRetries", "{", "if", "count", ">", "0", "{", "time", ".", "Sleep", "(", "100", "*", "time", ".", "Millisecond", ")", "\n", "}", "\n\n", "filter", ",", "err", "=", "s", ".", "CS", ".", "GetCFilter", "(", "*", "hash", ",", "wire", ".", "GCSFilterRegular", ")", "\n", "if", "err", "!=", "nil", "{", "count", "++", "\n", "continue", "\n", "}", "\n\n", "return", "filter", ",", "nil", "\n", "}", "\n\n", "return", "nil", ",", "err", "\n", "}" ]
// pollCFilter attempts to fetch a CFilter from the neutrino client. This is // used to get around the fact that the filter headers may lag behind the // highest known block header.
[ "pollCFilter", "attempts", "to", "fetch", "a", "CFilter", "from", "the", "neutrino", "client", ".", "This", "is", "used", "to", "get", "around", "the", "fact", "that", "the", "filter", "headers", "may", "lag", "behind", "the", "highest", "known", "block", "header", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/neutrino.go#L295-L318
train
btcsuite/btcwallet
chain/neutrino.go
Rescan
func (s *NeutrinoClient) Rescan(startHash *chainhash.Hash, addrs []btcutil.Address, outPoints map[wire.OutPoint]btcutil.Address) error { s.clientMtx.Lock() defer s.clientMtx.Unlock() if !s.started { return fmt.Errorf("can't do a rescan when the chain client " + "is not started") } if s.scanning { // Restart the rescan by killing the existing rescan. close(s.rescanQuit) s.clientMtx.Unlock() s.rescan.WaitForShutdown() s.clientMtx.Lock() s.rescan = nil s.rescanErr = nil } s.rescanQuit = make(chan struct{}) s.scanning = true s.finished = false s.lastProgressSent = false s.lastFilteredBlockHeader = nil s.isRescan = true bestBlock, err := s.CS.BestBlock() if err != nil { return fmt.Errorf("Can't get chain service's best block: %s", err) } header, err := s.CS.GetBlockHeader(&bestBlock.Hash) if err != nil { return fmt.Errorf("Can't get block header for hash %v: %s", bestBlock.Hash, err) } // If the wallet is already fully caught up, or the rescan has started // with state that indicates a "fresh" wallet, we'll send a // notification indicating the rescan has "finished". if header.BlockHash() == *startHash { s.finished = true select { case s.enqueueNotification <- &RescanFinished{ Hash: startHash, Height: int32(bestBlock.Height), Time: header.Timestamp, }: case <-s.quit: return nil case <-s.rescanQuit: return nil } } var inputsToWatch []neutrino.InputWithScript for op, addr := range outPoints { addrScript, err := txscript.PayToAddrScript(addr) if err != nil { } inputsToWatch = append(inputsToWatch, neutrino.InputWithScript{ OutPoint: op, PkScript: addrScript, }) } newRescan := neutrino.NewRescan( &neutrino.RescanChainSource{ ChainService: s.CS, }, neutrino.NotificationHandlers(rpcclient.NotificationHandlers{ OnBlockConnected: s.onBlockConnected, OnFilteredBlockConnected: s.onFilteredBlockConnected, OnBlockDisconnected: s.onBlockDisconnected, }), neutrino.StartBlock(&waddrmgr.BlockStamp{Hash: *startHash}), neutrino.StartTime(s.startTime), neutrino.QuitChan(s.rescanQuit), neutrino.WatchAddrs(addrs...), neutrino.WatchInputs(inputsToWatch...), ) s.rescan = newRescan s.rescanErr = s.rescan.Start() return nil }
go
func (s *NeutrinoClient) Rescan(startHash *chainhash.Hash, addrs []btcutil.Address, outPoints map[wire.OutPoint]btcutil.Address) error { s.clientMtx.Lock() defer s.clientMtx.Unlock() if !s.started { return fmt.Errorf("can't do a rescan when the chain client " + "is not started") } if s.scanning { // Restart the rescan by killing the existing rescan. close(s.rescanQuit) s.clientMtx.Unlock() s.rescan.WaitForShutdown() s.clientMtx.Lock() s.rescan = nil s.rescanErr = nil } s.rescanQuit = make(chan struct{}) s.scanning = true s.finished = false s.lastProgressSent = false s.lastFilteredBlockHeader = nil s.isRescan = true bestBlock, err := s.CS.BestBlock() if err != nil { return fmt.Errorf("Can't get chain service's best block: %s", err) } header, err := s.CS.GetBlockHeader(&bestBlock.Hash) if err != nil { return fmt.Errorf("Can't get block header for hash %v: %s", bestBlock.Hash, err) } // If the wallet is already fully caught up, or the rescan has started // with state that indicates a "fresh" wallet, we'll send a // notification indicating the rescan has "finished". if header.BlockHash() == *startHash { s.finished = true select { case s.enqueueNotification <- &RescanFinished{ Hash: startHash, Height: int32(bestBlock.Height), Time: header.Timestamp, }: case <-s.quit: return nil case <-s.rescanQuit: return nil } } var inputsToWatch []neutrino.InputWithScript for op, addr := range outPoints { addrScript, err := txscript.PayToAddrScript(addr) if err != nil { } inputsToWatch = append(inputsToWatch, neutrino.InputWithScript{ OutPoint: op, PkScript: addrScript, }) } newRescan := neutrino.NewRescan( &neutrino.RescanChainSource{ ChainService: s.CS, }, neutrino.NotificationHandlers(rpcclient.NotificationHandlers{ OnBlockConnected: s.onBlockConnected, OnFilteredBlockConnected: s.onFilteredBlockConnected, OnBlockDisconnected: s.onBlockDisconnected, }), neutrino.StartBlock(&waddrmgr.BlockStamp{Hash: *startHash}), neutrino.StartTime(s.startTime), neutrino.QuitChan(s.rescanQuit), neutrino.WatchAddrs(addrs...), neutrino.WatchInputs(inputsToWatch...), ) s.rescan = newRescan s.rescanErr = s.rescan.Start() return nil }
[ "func", "(", "s", "*", "NeutrinoClient", ")", "Rescan", "(", "startHash", "*", "chainhash", ".", "Hash", ",", "addrs", "[", "]", "btcutil", ".", "Address", ",", "outPoints", "map", "[", "wire", ".", "OutPoint", "]", "btcutil", ".", "Address", ")", "error", "{", "s", ".", "clientMtx", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "clientMtx", ".", "Unlock", "(", ")", "\n", "if", "!", "s", ".", "started", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ")", "\n", "}", "\n", "if", "s", ".", "scanning", "{", "// Restart the rescan by killing the existing rescan.", "close", "(", "s", ".", "rescanQuit", ")", "\n", "s", ".", "clientMtx", ".", "Unlock", "(", ")", "\n", "s", ".", "rescan", ".", "WaitForShutdown", "(", ")", "\n", "s", ".", "clientMtx", ".", "Lock", "(", ")", "\n", "s", ".", "rescan", "=", "nil", "\n", "s", ".", "rescanErr", "=", "nil", "\n", "}", "\n", "s", ".", "rescanQuit", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "s", ".", "scanning", "=", "true", "\n", "s", ".", "finished", "=", "false", "\n", "s", ".", "lastProgressSent", "=", "false", "\n", "s", ".", "lastFilteredBlockHeader", "=", "nil", "\n", "s", ".", "isRescan", "=", "true", "\n\n", "bestBlock", ",", "err", ":=", "s", ".", "CS", ".", "BestBlock", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "header", ",", "err", ":=", "s", ".", "CS", ".", "GetBlockHeader", "(", "&", "bestBlock", ".", "Hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "bestBlock", ".", "Hash", ",", "err", ")", "\n", "}", "\n\n", "// If the wallet is already fully caught up, or the rescan has started", "// with state that indicates a \"fresh\" wallet, we'll send a", "// notification indicating the rescan has \"finished\".", "if", "header", ".", "BlockHash", "(", ")", "==", "*", "startHash", "{", "s", ".", "finished", "=", "true", "\n", "select", "{", "case", "s", ".", "enqueueNotification", "<-", "&", "RescanFinished", "{", "Hash", ":", "startHash", ",", "Height", ":", "int32", "(", "bestBlock", ".", "Height", ")", ",", "Time", ":", "header", ".", "Timestamp", ",", "}", ":", "case", "<-", "s", ".", "quit", ":", "return", "nil", "\n", "case", "<-", "s", ".", "rescanQuit", ":", "return", "nil", "\n", "}", "\n", "}", "\n\n", "var", "inputsToWatch", "[", "]", "neutrino", ".", "InputWithScript", "\n", "for", "op", ",", "addr", ":=", "range", "outPoints", "{", "addrScript", ",", "err", ":=", "txscript", ".", "PayToAddrScript", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "}", "\n\n", "inputsToWatch", "=", "append", "(", "inputsToWatch", ",", "neutrino", ".", "InputWithScript", "{", "OutPoint", ":", "op", ",", "PkScript", ":", "addrScript", ",", "}", ")", "\n", "}", "\n\n", "newRescan", ":=", "neutrino", ".", "NewRescan", "(", "&", "neutrino", ".", "RescanChainSource", "{", "ChainService", ":", "s", ".", "CS", ",", "}", ",", "neutrino", ".", "NotificationHandlers", "(", "rpcclient", ".", "NotificationHandlers", "{", "OnBlockConnected", ":", "s", ".", "onBlockConnected", ",", "OnFilteredBlockConnected", ":", "s", ".", "onFilteredBlockConnected", ",", "OnBlockDisconnected", ":", "s", ".", "onBlockDisconnected", ",", "}", ")", ",", "neutrino", ".", "StartBlock", "(", "&", "waddrmgr", ".", "BlockStamp", "{", "Hash", ":", "*", "startHash", "}", ")", ",", "neutrino", ".", "StartTime", "(", "s", ".", "startTime", ")", ",", "neutrino", ".", "QuitChan", "(", "s", ".", "rescanQuit", ")", ",", "neutrino", ".", "WatchAddrs", "(", "addrs", "...", ")", ",", "neutrino", ".", "WatchInputs", "(", "inputsToWatch", "...", ")", ",", ")", "\n", "s", ".", "rescan", "=", "newRescan", "\n", "s", ".", "rescanErr", "=", "s", ".", "rescan", ".", "Start", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// Rescan replicates the RPC client's Rescan command.
[ "Rescan", "replicates", "the", "RPC", "client", "s", "Rescan", "command", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/neutrino.go#L321-L405
train
btcsuite/btcwallet
chain/neutrino.go
NotifyBlocks
func (s *NeutrinoClient) NotifyBlocks() error { s.clientMtx.Lock() // If we're scanning, we're already notifying on blocks. Otherwise, // start a rescan without watching any addresses. if !s.scanning { s.clientMtx.Unlock() return s.NotifyReceived([]btcutil.Address{}) } s.clientMtx.Unlock() return nil }
go
func (s *NeutrinoClient) NotifyBlocks() error { s.clientMtx.Lock() // If we're scanning, we're already notifying on blocks. Otherwise, // start a rescan without watching any addresses. if !s.scanning { s.clientMtx.Unlock() return s.NotifyReceived([]btcutil.Address{}) } s.clientMtx.Unlock() return nil }
[ "func", "(", "s", "*", "NeutrinoClient", ")", "NotifyBlocks", "(", ")", "error", "{", "s", ".", "clientMtx", ".", "Lock", "(", ")", "\n", "// If we're scanning, we're already notifying on blocks. Otherwise,", "// start a rescan without watching any addresses.", "if", "!", "s", ".", "scanning", "{", "s", ".", "clientMtx", ".", "Unlock", "(", ")", "\n", "return", "s", ".", "NotifyReceived", "(", "[", "]", "btcutil", ".", "Address", "{", "}", ")", "\n", "}", "\n", "s", ".", "clientMtx", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}" ]
// NotifyBlocks replicates the RPC client's NotifyBlocks command.
[ "NotifyBlocks", "replicates", "the", "RPC", "client", "s", "NotifyBlocks", "command", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/neutrino.go#L408-L418
train
btcsuite/btcwallet
chain/neutrino.go
NotifyReceived
func (s *NeutrinoClient) NotifyReceived(addrs []btcutil.Address) error { s.clientMtx.Lock() // If we have a rescan running, we just need to add the appropriate // addresses to the watch list. if s.scanning { s.clientMtx.Unlock() return s.rescan.Update(neutrino.AddAddrs(addrs...)) } s.rescanQuit = make(chan struct{}) s.scanning = true // Don't need RescanFinished or RescanProgress notifications. s.finished = true s.lastProgressSent = true s.lastFilteredBlockHeader = nil // Rescan with just the specified addresses. newRescan := neutrino.NewRescan( &neutrino.RescanChainSource{ ChainService: s.CS, }, neutrino.NotificationHandlers(rpcclient.NotificationHandlers{ OnBlockConnected: s.onBlockConnected, OnFilteredBlockConnected: s.onFilteredBlockConnected, OnBlockDisconnected: s.onBlockDisconnected, }), neutrino.StartTime(s.startTime), neutrino.QuitChan(s.rescanQuit), neutrino.WatchAddrs(addrs...), ) s.rescan = newRescan s.rescanErr = s.rescan.Start() s.clientMtx.Unlock() return nil }
go
func (s *NeutrinoClient) NotifyReceived(addrs []btcutil.Address) error { s.clientMtx.Lock() // If we have a rescan running, we just need to add the appropriate // addresses to the watch list. if s.scanning { s.clientMtx.Unlock() return s.rescan.Update(neutrino.AddAddrs(addrs...)) } s.rescanQuit = make(chan struct{}) s.scanning = true // Don't need RescanFinished or RescanProgress notifications. s.finished = true s.lastProgressSent = true s.lastFilteredBlockHeader = nil // Rescan with just the specified addresses. newRescan := neutrino.NewRescan( &neutrino.RescanChainSource{ ChainService: s.CS, }, neutrino.NotificationHandlers(rpcclient.NotificationHandlers{ OnBlockConnected: s.onBlockConnected, OnFilteredBlockConnected: s.onFilteredBlockConnected, OnBlockDisconnected: s.onBlockDisconnected, }), neutrino.StartTime(s.startTime), neutrino.QuitChan(s.rescanQuit), neutrino.WatchAddrs(addrs...), ) s.rescan = newRescan s.rescanErr = s.rescan.Start() s.clientMtx.Unlock() return nil }
[ "func", "(", "s", "*", "NeutrinoClient", ")", "NotifyReceived", "(", "addrs", "[", "]", "btcutil", ".", "Address", ")", "error", "{", "s", ".", "clientMtx", ".", "Lock", "(", ")", "\n\n", "// If we have a rescan running, we just need to add the appropriate", "// addresses to the watch list.", "if", "s", ".", "scanning", "{", "s", ".", "clientMtx", ".", "Unlock", "(", ")", "\n", "return", "s", ".", "rescan", ".", "Update", "(", "neutrino", ".", "AddAddrs", "(", "addrs", "...", ")", ")", "\n", "}", "\n\n", "s", ".", "rescanQuit", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "s", ".", "scanning", "=", "true", "\n\n", "// Don't need RescanFinished or RescanProgress notifications.", "s", ".", "finished", "=", "true", "\n", "s", ".", "lastProgressSent", "=", "true", "\n", "s", ".", "lastFilteredBlockHeader", "=", "nil", "\n\n", "// Rescan with just the specified addresses.", "newRescan", ":=", "neutrino", ".", "NewRescan", "(", "&", "neutrino", ".", "RescanChainSource", "{", "ChainService", ":", "s", ".", "CS", ",", "}", ",", "neutrino", ".", "NotificationHandlers", "(", "rpcclient", ".", "NotificationHandlers", "{", "OnBlockConnected", ":", "s", ".", "onBlockConnected", ",", "OnFilteredBlockConnected", ":", "s", ".", "onFilteredBlockConnected", ",", "OnBlockDisconnected", ":", "s", ".", "onBlockDisconnected", ",", "}", ")", ",", "neutrino", ".", "StartTime", "(", "s", ".", "startTime", ")", ",", "neutrino", ".", "QuitChan", "(", "s", ".", "rescanQuit", ")", ",", "neutrino", ".", "WatchAddrs", "(", "addrs", "...", ")", ",", ")", "\n", "s", ".", "rescan", "=", "newRescan", "\n", "s", ".", "rescanErr", "=", "s", ".", "rescan", ".", "Start", "(", ")", "\n", "s", ".", "clientMtx", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}" ]
// NotifyReceived replicates the RPC client's NotifyReceived command.
[ "NotifyReceived", "replicates", "the", "RPC", "client", "s", "NotifyReceived", "command", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/neutrino.go#L421-L457
train
btcsuite/btcwallet
chain/neutrino.go
onFilteredBlockConnected
func (s *NeutrinoClient) onFilteredBlockConnected(height int32, header *wire.BlockHeader, relevantTxs []*btcutil.Tx) { ntfn := FilteredBlockConnected{ Block: &wtxmgr.BlockMeta{ Block: wtxmgr.Block{ Hash: header.BlockHash(), Height: height, }, Time: header.Timestamp, }, } for _, tx := range relevantTxs { rec, err := wtxmgr.NewTxRecordFromMsgTx(tx.MsgTx(), header.Timestamp) if err != nil { log.Errorf("Cannot create transaction record for "+ "relevant tx: %s", err) // TODO(aakselrod): Return? continue } ntfn.RelevantTxs = append(ntfn.RelevantTxs, rec) } select { case s.enqueueNotification <- ntfn: case <-s.quit: return case <-s.rescanQuit: return } s.clientMtx.Lock() s.lastFilteredBlockHeader = header s.clientMtx.Unlock() // Handle RescanFinished notification if required. s.dispatchRescanFinished() }
go
func (s *NeutrinoClient) onFilteredBlockConnected(height int32, header *wire.BlockHeader, relevantTxs []*btcutil.Tx) { ntfn := FilteredBlockConnected{ Block: &wtxmgr.BlockMeta{ Block: wtxmgr.Block{ Hash: header.BlockHash(), Height: height, }, Time: header.Timestamp, }, } for _, tx := range relevantTxs { rec, err := wtxmgr.NewTxRecordFromMsgTx(tx.MsgTx(), header.Timestamp) if err != nil { log.Errorf("Cannot create transaction record for "+ "relevant tx: %s", err) // TODO(aakselrod): Return? continue } ntfn.RelevantTxs = append(ntfn.RelevantTxs, rec) } select { case s.enqueueNotification <- ntfn: case <-s.quit: return case <-s.rescanQuit: return } s.clientMtx.Lock() s.lastFilteredBlockHeader = header s.clientMtx.Unlock() // Handle RescanFinished notification if required. s.dispatchRescanFinished() }
[ "func", "(", "s", "*", "NeutrinoClient", ")", "onFilteredBlockConnected", "(", "height", "int32", ",", "header", "*", "wire", ".", "BlockHeader", ",", "relevantTxs", "[", "]", "*", "btcutil", ".", "Tx", ")", "{", "ntfn", ":=", "FilteredBlockConnected", "{", "Block", ":", "&", "wtxmgr", ".", "BlockMeta", "{", "Block", ":", "wtxmgr", ".", "Block", "{", "Hash", ":", "header", ".", "BlockHash", "(", ")", ",", "Height", ":", "height", ",", "}", ",", "Time", ":", "header", ".", "Timestamp", ",", "}", ",", "}", "\n", "for", "_", ",", "tx", ":=", "range", "relevantTxs", "{", "rec", ",", "err", ":=", "wtxmgr", ".", "NewTxRecordFromMsgTx", "(", "tx", ".", "MsgTx", "(", ")", ",", "header", ".", "Timestamp", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "err", ")", "\n", "// TODO(aakselrod): Return?", "continue", "\n", "}", "\n", "ntfn", ".", "RelevantTxs", "=", "append", "(", "ntfn", ".", "RelevantTxs", ",", "rec", ")", "\n", "}", "\n\n", "select", "{", "case", "s", ".", "enqueueNotification", "<-", "ntfn", ":", "case", "<-", "s", ".", "quit", ":", "return", "\n", "case", "<-", "s", ".", "rescanQuit", ":", "return", "\n", "}", "\n\n", "s", ".", "clientMtx", ".", "Lock", "(", ")", "\n", "s", ".", "lastFilteredBlockHeader", "=", "header", "\n", "s", ".", "clientMtx", ".", "Unlock", "(", ")", "\n\n", "// Handle RescanFinished notification if required.", "s", ".", "dispatchRescanFinished", "(", ")", "\n", "}" ]
// onFilteredBlockConnected sends appropriate notifications to the notification // channel.
[ "onFilteredBlockConnected", "sends", "appropriate", "notifications", "to", "the", "notification", "channel", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/neutrino.go#L479-L516
train
btcsuite/btcwallet
chain/neutrino.go
onBlockDisconnected
func (s *NeutrinoClient) onBlockDisconnected(hash *chainhash.Hash, height int32, t time.Time) { select { case s.enqueueNotification <- BlockDisconnected{ Block: wtxmgr.Block{ Hash: *hash, Height: height, }, Time: t, }: case <-s.quit: case <-s.rescanQuit: } }
go
func (s *NeutrinoClient) onBlockDisconnected(hash *chainhash.Hash, height int32, t time.Time) { select { case s.enqueueNotification <- BlockDisconnected{ Block: wtxmgr.Block{ Hash: *hash, Height: height, }, Time: t, }: case <-s.quit: case <-s.rescanQuit: } }
[ "func", "(", "s", "*", "NeutrinoClient", ")", "onBlockDisconnected", "(", "hash", "*", "chainhash", ".", "Hash", ",", "height", "int32", ",", "t", "time", ".", "Time", ")", "{", "select", "{", "case", "s", ".", "enqueueNotification", "<-", "BlockDisconnected", "{", "Block", ":", "wtxmgr", ".", "Block", "{", "Hash", ":", "*", "hash", ",", "Height", ":", "height", ",", "}", ",", "Time", ":", "t", ",", "}", ":", "case", "<-", "s", ".", "quit", ":", "case", "<-", "s", ".", "rescanQuit", ":", "}", "\n", "}" ]
// onBlockDisconnected sends appropriate notifications to the notification // channel.
[ "onBlockDisconnected", "sends", "appropriate", "notifications", "to", "the", "notification", "channel", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/neutrino.go#L520-L533
train
btcsuite/btcwallet
chain/neutrino.go
dispatchRescanFinished
func (s *NeutrinoClient) dispatchRescanFinished() { bs, err := s.CS.BestBlock() if err != nil { log.Errorf("Can't get chain service's best block: %s", err) return } s.clientMtx.Lock() // Only send the RescanFinished notification once. if s.lastFilteredBlockHeader == nil || s.finished { s.clientMtx.Unlock() return } // Only send the RescanFinished notification once the underlying chain // service sees itself as current. if bs.Hash != s.lastFilteredBlockHeader.BlockHash() { s.clientMtx.Unlock() return } s.finished = s.CS.IsCurrent() && s.lastProgressSent if !s.finished { s.clientMtx.Unlock() return } header := s.lastFilteredBlockHeader s.clientMtx.Unlock() select { case s.enqueueNotification <- &RescanFinished{ Hash: &bs.Hash, Height: bs.Height, Time: header.Timestamp, }: case <-s.quit: return case <-s.rescanQuit: return } }
go
func (s *NeutrinoClient) dispatchRescanFinished() { bs, err := s.CS.BestBlock() if err != nil { log.Errorf("Can't get chain service's best block: %s", err) return } s.clientMtx.Lock() // Only send the RescanFinished notification once. if s.lastFilteredBlockHeader == nil || s.finished { s.clientMtx.Unlock() return } // Only send the RescanFinished notification once the underlying chain // service sees itself as current. if bs.Hash != s.lastFilteredBlockHeader.BlockHash() { s.clientMtx.Unlock() return } s.finished = s.CS.IsCurrent() && s.lastProgressSent if !s.finished { s.clientMtx.Unlock() return } header := s.lastFilteredBlockHeader s.clientMtx.Unlock() select { case s.enqueueNotification <- &RescanFinished{ Hash: &bs.Hash, Height: bs.Height, Time: header.Timestamp, }: case <-s.quit: return case <-s.rescanQuit: return } }
[ "func", "(", "s", "*", "NeutrinoClient", ")", "dispatchRescanFinished", "(", ")", "{", "bs", ",", "err", ":=", "s", ".", "CS", ".", "BestBlock", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "s", ".", "clientMtx", ".", "Lock", "(", ")", "\n", "// Only send the RescanFinished notification once.", "if", "s", ".", "lastFilteredBlockHeader", "==", "nil", "||", "s", ".", "finished", "{", "s", ".", "clientMtx", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n\n", "// Only send the RescanFinished notification once the underlying chain", "// service sees itself as current.", "if", "bs", ".", "Hash", "!=", "s", ".", "lastFilteredBlockHeader", ".", "BlockHash", "(", ")", "{", "s", ".", "clientMtx", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n\n", "s", ".", "finished", "=", "s", ".", "CS", ".", "IsCurrent", "(", ")", "&&", "s", ".", "lastProgressSent", "\n", "if", "!", "s", ".", "finished", "{", "s", ".", "clientMtx", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n\n", "header", ":=", "s", ".", "lastFilteredBlockHeader", "\n", "s", ".", "clientMtx", ".", "Unlock", "(", ")", "\n\n", "select", "{", "case", "s", ".", "enqueueNotification", "<-", "&", "RescanFinished", "{", "Hash", ":", "&", "bs", ".", "Hash", ",", "Height", ":", "bs", ".", "Height", ",", "Time", ":", "header", ".", "Timestamp", ",", "}", ":", "case", "<-", "s", ".", "quit", ":", "return", "\n", "case", "<-", "s", ".", "rescanQuit", ":", "return", "\n", "}", "\n", "}" ]
// dispatchRescanFinished determines whether we're able to dispatch our final // RescanFinished notification in order to mark the wallet as synced with the // chain. If the notification has already been dispatched, then it won't be done // again.
[ "dispatchRescanFinished", "determines", "whether", "we", "re", "able", "to", "dispatch", "our", "final", "RescanFinished", "notification", "in", "order", "to", "mark", "the", "wallet", "as", "synced", "with", "the", "chain", ".", "If", "the", "notification", "has", "already", "been", "dispatched", "then", "it", "won", "t", "be", "done", "again", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/neutrino.go#L600-L641
train
btcsuite/btcwallet
chain/neutrino.go
notificationHandler
func (s *NeutrinoClient) notificationHandler() { hash, height, err := s.GetBestBlock() if err != nil { log.Errorf("Failed to get best block from chain service: %s", err) s.Stop() s.wg.Done() return } bs := &waddrmgr.BlockStamp{Hash: *hash, Height: height} // TODO: Rather than leaving this as an unbounded queue for all types of // notifications, try dropping ones where a later enqueued notification // can fully invalidate one waiting to be processed. For example, // blockconnected notifications for greater block heights can remove the // need to process earlier blockconnected notifications still waiting // here. var notifications []interface{} enqueue := s.enqueueNotification var dequeue chan interface{} var next interface{} out: for { s.clientMtx.Lock() rescanErr := s.rescanErr s.clientMtx.Unlock() select { case n, ok := <-enqueue: if !ok { // If no notifications are queued for handling, // the queue is finished. if len(notifications) == 0 { break out } // nil channel so no more reads can occur. enqueue = nil continue } if len(notifications) == 0 { next = n dequeue = s.dequeueNotification } notifications = append(notifications, n) case dequeue <- next: if n, ok := next.(BlockConnected); ok { bs = &waddrmgr.BlockStamp{ Height: n.Height, Hash: n.Hash, } } notifications[0] = nil notifications = notifications[1:] if len(notifications) != 0 { next = notifications[0] } else { // If no more notifications can be enqueued, the // queue is finished. if enqueue == nil { break out } dequeue = nil } case err := <-rescanErr: if err != nil { log.Errorf("Neutrino rescan ended with error: %s", err) } case s.currentBlock <- bs: case <-s.quit: break out } } s.Stop() close(s.dequeueNotification) s.wg.Done() }
go
func (s *NeutrinoClient) notificationHandler() { hash, height, err := s.GetBestBlock() if err != nil { log.Errorf("Failed to get best block from chain service: %s", err) s.Stop() s.wg.Done() return } bs := &waddrmgr.BlockStamp{Hash: *hash, Height: height} // TODO: Rather than leaving this as an unbounded queue for all types of // notifications, try dropping ones where a later enqueued notification // can fully invalidate one waiting to be processed. For example, // blockconnected notifications for greater block heights can remove the // need to process earlier blockconnected notifications still waiting // here. var notifications []interface{} enqueue := s.enqueueNotification var dequeue chan interface{} var next interface{} out: for { s.clientMtx.Lock() rescanErr := s.rescanErr s.clientMtx.Unlock() select { case n, ok := <-enqueue: if !ok { // If no notifications are queued for handling, // the queue is finished. if len(notifications) == 0 { break out } // nil channel so no more reads can occur. enqueue = nil continue } if len(notifications) == 0 { next = n dequeue = s.dequeueNotification } notifications = append(notifications, n) case dequeue <- next: if n, ok := next.(BlockConnected); ok { bs = &waddrmgr.BlockStamp{ Height: n.Height, Hash: n.Hash, } } notifications[0] = nil notifications = notifications[1:] if len(notifications) != 0 { next = notifications[0] } else { // If no more notifications can be enqueued, the // queue is finished. if enqueue == nil { break out } dequeue = nil } case err := <-rescanErr: if err != nil { log.Errorf("Neutrino rescan ended with error: %s", err) } case s.currentBlock <- bs: case <-s.quit: break out } } s.Stop() close(s.dequeueNotification) s.wg.Done() }
[ "func", "(", "s", "*", "NeutrinoClient", ")", "notificationHandler", "(", ")", "{", "hash", ",", "height", ",", "err", ":=", "s", ".", "GetBestBlock", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "s", ".", "Stop", "(", ")", "\n", "s", ".", "wg", ".", "Done", "(", ")", "\n", "return", "\n", "}", "\n\n", "bs", ":=", "&", "waddrmgr", ".", "BlockStamp", "{", "Hash", ":", "*", "hash", ",", "Height", ":", "height", "}", "\n\n", "// TODO: Rather than leaving this as an unbounded queue for all types of", "// notifications, try dropping ones where a later enqueued notification", "// can fully invalidate one waiting to be processed. For example,", "// blockconnected notifications for greater block heights can remove the", "// need to process earlier blockconnected notifications still waiting", "// here.", "var", "notifications", "[", "]", "interface", "{", "}", "\n", "enqueue", ":=", "s", ".", "enqueueNotification", "\n", "var", "dequeue", "chan", "interface", "{", "}", "\n", "var", "next", "interface", "{", "}", "\n", "out", ":", "for", "{", "s", ".", "clientMtx", ".", "Lock", "(", ")", "\n", "rescanErr", ":=", "s", ".", "rescanErr", "\n", "s", ".", "clientMtx", ".", "Unlock", "(", ")", "\n", "select", "{", "case", "n", ",", "ok", ":=", "<-", "enqueue", ":", "if", "!", "ok", "{", "// If no notifications are queued for handling,", "// the queue is finished.", "if", "len", "(", "notifications", ")", "==", "0", "{", "break", "out", "\n", "}", "\n", "// nil channel so no more reads can occur.", "enqueue", "=", "nil", "\n", "continue", "\n", "}", "\n", "if", "len", "(", "notifications", ")", "==", "0", "{", "next", "=", "n", "\n", "dequeue", "=", "s", ".", "dequeueNotification", "\n", "}", "\n", "notifications", "=", "append", "(", "notifications", ",", "n", ")", "\n\n", "case", "dequeue", "<-", "next", ":", "if", "n", ",", "ok", ":=", "next", ".", "(", "BlockConnected", ")", ";", "ok", "{", "bs", "=", "&", "waddrmgr", ".", "BlockStamp", "{", "Height", ":", "n", ".", "Height", ",", "Hash", ":", "n", ".", "Hash", ",", "}", "\n", "}", "\n\n", "notifications", "[", "0", "]", "=", "nil", "\n", "notifications", "=", "notifications", "[", "1", ":", "]", "\n", "if", "len", "(", "notifications", ")", "!=", "0", "{", "next", "=", "notifications", "[", "0", "]", "\n", "}", "else", "{", "// If no more notifications can be enqueued, the", "// queue is finished.", "if", "enqueue", "==", "nil", "{", "break", "out", "\n", "}", "\n", "dequeue", "=", "nil", "\n", "}", "\n\n", "case", "err", ":=", "<-", "rescanErr", ":", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "case", "s", ".", "currentBlock", "<-", "bs", ":", "case", "<-", "s", ".", "quit", ":", "break", "out", "\n", "}", "\n", "}", "\n\n", "s", ".", "Stop", "(", ")", "\n", "close", "(", "s", ".", "dequeueNotification", ")", "\n", "s", ".", "wg", ".", "Done", "(", ")", "\n", "}" ]
// notificationHandler queues and dequeues notifications. There are currently // no bounds on the queue, so the dequeue channel should be read continually to // avoid running out of memory.
[ "notificationHandler", "queues", "and", "dequeues", "notifications", ".", "There", "are", "currently", "no", "bounds", "on", "the", "queue", "so", "the", "dequeue", "channel", "should", "be", "read", "continually", "to", "avoid", "running", "out", "of", "memory", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/neutrino.go#L646-L728
train
btcsuite/btcwallet
chain/rpc.go
NewRPCClient
func NewRPCClient(chainParams *chaincfg.Params, connect, user, pass string, certs []byte, disableTLS bool, reconnectAttempts int) (*RPCClient, error) { if reconnectAttempts < 0 { return nil, errors.New("reconnectAttempts must be positive") } client := &RPCClient{ connConfig: &rpcclient.ConnConfig{ Host: connect, Endpoint: "ws", User: user, Pass: pass, Certificates: certs, DisableAutoReconnect: false, DisableConnectOnNew: true, DisableTLS: disableTLS, }, chainParams: chainParams, reconnectAttempts: reconnectAttempts, enqueueNotification: make(chan interface{}), dequeueNotification: make(chan interface{}), currentBlock: make(chan *waddrmgr.BlockStamp), quit: make(chan struct{}), } ntfnCallbacks := &rpcclient.NotificationHandlers{ OnClientConnected: client.onClientConnect, OnBlockConnected: client.onBlockConnected, OnBlockDisconnected: client.onBlockDisconnected, OnRecvTx: client.onRecvTx, OnRedeemingTx: client.onRedeemingTx, OnRescanFinished: client.onRescanFinished, OnRescanProgress: client.onRescanProgress, } rpcClient, err := rpcclient.New(client.connConfig, ntfnCallbacks) if err != nil { return nil, err } client.Client = rpcClient return client, nil }
go
func NewRPCClient(chainParams *chaincfg.Params, connect, user, pass string, certs []byte, disableTLS bool, reconnectAttempts int) (*RPCClient, error) { if reconnectAttempts < 0 { return nil, errors.New("reconnectAttempts must be positive") } client := &RPCClient{ connConfig: &rpcclient.ConnConfig{ Host: connect, Endpoint: "ws", User: user, Pass: pass, Certificates: certs, DisableAutoReconnect: false, DisableConnectOnNew: true, DisableTLS: disableTLS, }, chainParams: chainParams, reconnectAttempts: reconnectAttempts, enqueueNotification: make(chan interface{}), dequeueNotification: make(chan interface{}), currentBlock: make(chan *waddrmgr.BlockStamp), quit: make(chan struct{}), } ntfnCallbacks := &rpcclient.NotificationHandlers{ OnClientConnected: client.onClientConnect, OnBlockConnected: client.onBlockConnected, OnBlockDisconnected: client.onBlockDisconnected, OnRecvTx: client.onRecvTx, OnRedeemingTx: client.onRedeemingTx, OnRescanFinished: client.onRescanFinished, OnRescanProgress: client.onRescanProgress, } rpcClient, err := rpcclient.New(client.connConfig, ntfnCallbacks) if err != nil { return nil, err } client.Client = rpcClient return client, nil }
[ "func", "NewRPCClient", "(", "chainParams", "*", "chaincfg", ".", "Params", ",", "connect", ",", "user", ",", "pass", "string", ",", "certs", "[", "]", "byte", ",", "disableTLS", "bool", ",", "reconnectAttempts", "int", ")", "(", "*", "RPCClient", ",", "error", ")", "{", "if", "reconnectAttempts", "<", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "client", ":=", "&", "RPCClient", "{", "connConfig", ":", "&", "rpcclient", ".", "ConnConfig", "{", "Host", ":", "connect", ",", "Endpoint", ":", "\"", "\"", ",", "User", ":", "user", ",", "Pass", ":", "pass", ",", "Certificates", ":", "certs", ",", "DisableAutoReconnect", ":", "false", ",", "DisableConnectOnNew", ":", "true", ",", "DisableTLS", ":", "disableTLS", ",", "}", ",", "chainParams", ":", "chainParams", ",", "reconnectAttempts", ":", "reconnectAttempts", ",", "enqueueNotification", ":", "make", "(", "chan", "interface", "{", "}", ")", ",", "dequeueNotification", ":", "make", "(", "chan", "interface", "{", "}", ")", ",", "currentBlock", ":", "make", "(", "chan", "*", "waddrmgr", ".", "BlockStamp", ")", ",", "quit", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n", "ntfnCallbacks", ":=", "&", "rpcclient", ".", "NotificationHandlers", "{", "OnClientConnected", ":", "client", ".", "onClientConnect", ",", "OnBlockConnected", ":", "client", ".", "onBlockConnected", ",", "OnBlockDisconnected", ":", "client", ".", "onBlockDisconnected", ",", "OnRecvTx", ":", "client", ".", "onRecvTx", ",", "OnRedeemingTx", ":", "client", ".", "onRedeemingTx", ",", "OnRescanFinished", ":", "client", ".", "onRescanFinished", ",", "OnRescanProgress", ":", "client", ".", "onRescanProgress", ",", "}", "\n", "rpcClient", ",", "err", ":=", "rpcclient", ".", "New", "(", "client", ".", "connConfig", ",", "ntfnCallbacks", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "client", ".", "Client", "=", "rpcClient", "\n", "return", "client", ",", "nil", "\n", "}" ]
// NewRPCClient creates a client connection to the server described by the // connect string. If disableTLS is false, the remote RPC certificate must be // provided in the certs slice. The connection is not established immediately, // but must be done using the Start method. If the remote server does not // operate on the same bitcoin network as described by the passed chain // parameters, the connection will be disconnected.
[ "NewRPCClient", "creates", "a", "client", "connection", "to", "the", "server", "described", "by", "the", "connect", "string", ".", "If", "disableTLS", "is", "false", "the", "remote", "RPC", "certificate", "must", "be", "provided", "in", "the", "certs", "slice", ".", "The", "connection", "is", "not", "established", "immediately", "but", "must", "be", "done", "using", "the", "Start", "method", ".", "If", "the", "remote", "server", "does", "not", "operate", "on", "the", "same", "bitcoin", "network", "as", "described", "by", "the", "passed", "chain", "parameters", "the", "connection", "will", "be", "disconnected", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/rpc.go#L48-L88
train
btcsuite/btcwallet
chain/rpc.go
Start
func (c *RPCClient) Start() error { err := c.Connect(c.reconnectAttempts) if err != nil { return err } // Verify that the server is running on the expected network. net, err := c.GetCurrentNet() if err != nil { c.Disconnect() return err } if net != c.chainParams.Net { c.Disconnect() return errors.New("mismatched networks") } c.quitMtx.Lock() c.started = true c.quitMtx.Unlock() c.wg.Add(1) go c.handler() return nil }
go
func (c *RPCClient) Start() error { err := c.Connect(c.reconnectAttempts) if err != nil { return err } // Verify that the server is running on the expected network. net, err := c.GetCurrentNet() if err != nil { c.Disconnect() return err } if net != c.chainParams.Net { c.Disconnect() return errors.New("mismatched networks") } c.quitMtx.Lock() c.started = true c.quitMtx.Unlock() c.wg.Add(1) go c.handler() return nil }
[ "func", "(", "c", "*", "RPCClient", ")", "Start", "(", ")", "error", "{", "err", ":=", "c", ".", "Connect", "(", "c", ".", "reconnectAttempts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Verify that the server is running on the expected network.", "net", ",", "err", ":=", "c", ".", "GetCurrentNet", "(", ")", "\n", "if", "err", "!=", "nil", "{", "c", ".", "Disconnect", "(", ")", "\n", "return", "err", "\n", "}", "\n", "if", "net", "!=", "c", ".", "chainParams", ".", "Net", "{", "c", ".", "Disconnect", "(", ")", "\n", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "c", ".", "quitMtx", ".", "Lock", "(", ")", "\n", "c", ".", "started", "=", "true", "\n", "c", ".", "quitMtx", ".", "Unlock", "(", ")", "\n\n", "c", ".", "wg", ".", "Add", "(", "1", ")", "\n", "go", "c", ".", "handler", "(", ")", "\n", "return", "nil", "\n", "}" ]
// Start attempts to establish a client connection with the remote server. // If successful, handler goroutines are started to process notifications // sent by the server. After a limited number of connection attempts, this // function gives up, and therefore will not block forever waiting for the // connection to be established to a server that may not exist.
[ "Start", "attempts", "to", "establish", "a", "client", "connection", "with", "the", "remote", "server", ".", "If", "successful", "handler", "goroutines", "are", "started", "to", "process", "notifications", "sent", "by", "the", "server", ".", "After", "a", "limited", "number", "of", "connection", "attempts", "this", "function", "gives", "up", "and", "therefore", "will", "not", "block", "forever", "waiting", "for", "the", "connection", "to", "be", "established", "to", "a", "server", "that", "may", "not", "exist", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/rpc.go#L100-L124
train
btcsuite/btcwallet
chain/rpc.go
Stop
func (c *RPCClient) Stop() { c.quitMtx.Lock() select { case <-c.quit: default: close(c.quit) c.Client.Shutdown() if !c.started { close(c.dequeueNotification) } } c.quitMtx.Unlock() }
go
func (c *RPCClient) Stop() { c.quitMtx.Lock() select { case <-c.quit: default: close(c.quit) c.Client.Shutdown() if !c.started { close(c.dequeueNotification) } } c.quitMtx.Unlock() }
[ "func", "(", "c", "*", "RPCClient", ")", "Stop", "(", ")", "{", "c", ".", "quitMtx", ".", "Lock", "(", ")", "\n", "select", "{", "case", "<-", "c", ".", "quit", ":", "default", ":", "close", "(", "c", ".", "quit", ")", "\n", "c", ".", "Client", ".", "Shutdown", "(", ")", "\n\n", "if", "!", "c", ".", "started", "{", "close", "(", "c", ".", "dequeueNotification", ")", "\n", "}", "\n", "}", "\n", "c", ".", "quitMtx", ".", "Unlock", "(", ")", "\n", "}" ]
// Stop disconnects the client and signals the shutdown of all goroutines // started by Start.
[ "Stop", "disconnects", "the", "client", "and", "signals", "the", "shutdown", "of", "all", "goroutines", "started", "by", "Start", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/rpc.go#L128-L141
train
btcsuite/btcwallet
chain/rpc.go
Rescan
func (c *RPCClient) Rescan(startHash *chainhash.Hash, addrs []btcutil.Address, outPoints map[wire.OutPoint]btcutil.Address) error { flatOutpoints := make([]*wire.OutPoint, 0, len(outPoints)) for ops := range outPoints { flatOutpoints = append(flatOutpoints, &ops) } return c.Client.Rescan(startHash, addrs, flatOutpoints) }
go
func (c *RPCClient) Rescan(startHash *chainhash.Hash, addrs []btcutil.Address, outPoints map[wire.OutPoint]btcutil.Address) error { flatOutpoints := make([]*wire.OutPoint, 0, len(outPoints)) for ops := range outPoints { flatOutpoints = append(flatOutpoints, &ops) } return c.Client.Rescan(startHash, addrs, flatOutpoints) }
[ "func", "(", "c", "*", "RPCClient", ")", "Rescan", "(", "startHash", "*", "chainhash", ".", "Hash", ",", "addrs", "[", "]", "btcutil", ".", "Address", ",", "outPoints", "map", "[", "wire", ".", "OutPoint", "]", "btcutil", ".", "Address", ")", "error", "{", "flatOutpoints", ":=", "make", "(", "[", "]", "*", "wire", ".", "OutPoint", ",", "0", ",", "len", "(", "outPoints", ")", ")", "\n", "for", "ops", ":=", "range", "outPoints", "{", "flatOutpoints", "=", "append", "(", "flatOutpoints", ",", "&", "ops", ")", "\n", "}", "\n\n", "return", "c", ".", "Client", ".", "Rescan", "(", "startHash", ",", "addrs", ",", "flatOutpoints", ")", "\n", "}" ]
// Rescan wraps the normal Rescan command with an additional paramter that // allows us to map an oupoint to the address in the chain that it pays to. // This is useful when using BIP 158 filters as they include the prev pkScript // rather than the full outpoint.
[ "Rescan", "wraps", "the", "normal", "Rescan", "command", "with", "an", "additional", "paramter", "that", "allows", "us", "to", "map", "an", "oupoint", "to", "the", "address", "in", "the", "chain", "that", "it", "pays", "to", ".", "This", "is", "useful", "when", "using", "BIP", "158", "filters", "as", "they", "include", "the", "prev", "pkScript", "rather", "than", "the", "full", "outpoint", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/rpc.go#L147-L156
train
btcsuite/btcwallet
chain/rpc.go
parseBlock
func parseBlock(block *btcjson.BlockDetails) (*wtxmgr.BlockMeta, error) { if block == nil { return nil, nil } blkHash, err := chainhash.NewHashFromStr(block.Hash) if err != nil { return nil, err } blk := &wtxmgr.BlockMeta{ Block: wtxmgr.Block{ Height: block.Height, Hash: *blkHash, }, Time: time.Unix(block.Time, 0), } return blk, nil }
go
func parseBlock(block *btcjson.BlockDetails) (*wtxmgr.BlockMeta, error) { if block == nil { return nil, nil } blkHash, err := chainhash.NewHashFromStr(block.Hash) if err != nil { return nil, err } blk := &wtxmgr.BlockMeta{ Block: wtxmgr.Block{ Height: block.Height, Hash: *blkHash, }, Time: time.Unix(block.Time, 0), } return blk, nil }
[ "func", "parseBlock", "(", "block", "*", "btcjson", ".", "BlockDetails", ")", "(", "*", "wtxmgr", ".", "BlockMeta", ",", "error", ")", "{", "if", "block", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "blkHash", ",", "err", ":=", "chainhash", ".", "NewHashFromStr", "(", "block", ".", "Hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "blk", ":=", "&", "wtxmgr", ".", "BlockMeta", "{", "Block", ":", "wtxmgr", ".", "Block", "{", "Height", ":", "block", ".", "Height", ",", "Hash", ":", "*", "blkHash", ",", "}", ",", "Time", ":", "time", ".", "Unix", "(", "block", ".", "Time", ",", "0", ")", ",", "}", "\n", "return", "blk", ",", "nil", "\n", "}" ]
// parseBlock parses a btcws definition of the block a tx is mined it to the // Block structure of the wtxmgr package, and the block index. This is done // here since rpcclient doesn't parse this nicely for us.
[ "parseBlock", "parses", "a", "btcws", "definition", "of", "the", "block", "a", "tx", "is", "mined", "it", "to", "the", "Block", "structure", "of", "the", "wtxmgr", "package", "and", "the", "block", "index", ".", "This", "is", "done", "here", "since", "rpcclient", "doesn", "t", "parse", "this", "nicely", "for", "us", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/rpc.go#L274-L290
train
btcsuite/btcwallet
chain/rpc.go
POSTClient
func (c *RPCClient) POSTClient() (*rpcclient.Client, error) { configCopy := *c.connConfig configCopy.HTTPPostMode = true return rpcclient.New(&configCopy, nil) }
go
func (c *RPCClient) POSTClient() (*rpcclient.Client, error) { configCopy := *c.connConfig configCopy.HTTPPostMode = true return rpcclient.New(&configCopy, nil) }
[ "func", "(", "c", "*", "RPCClient", ")", "POSTClient", "(", ")", "(", "*", "rpcclient", ".", "Client", ",", "error", ")", "{", "configCopy", ":=", "*", "c", ".", "connConfig", "\n", "configCopy", ".", "HTTPPostMode", "=", "true", "\n", "return", "rpcclient", ".", "New", "(", "&", "configCopy", ",", "nil", ")", "\n", "}" ]
// POSTClient creates the equivalent HTTP POST rpcclient.Client.
[ "POSTClient", "creates", "the", "equivalent", "HTTP", "POST", "rpcclient", ".", "Client", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/rpc.go#L443-L447
train
btcsuite/btcwallet
snacl/snacl.go
Encrypt
func (ck *CryptoKey) Encrypt(in []byte) ([]byte, error) { var nonce [NonceSize]byte _, err := io.ReadFull(prng, nonce[:]) if err != nil { return nil, err } blob := secretbox.Seal(nil, in, &nonce, (*[KeySize]byte)(ck)) return append(nonce[:], blob...), nil }
go
func (ck *CryptoKey) Encrypt(in []byte) ([]byte, error) { var nonce [NonceSize]byte _, err := io.ReadFull(prng, nonce[:]) if err != nil { return nil, err } blob := secretbox.Seal(nil, in, &nonce, (*[KeySize]byte)(ck)) return append(nonce[:], blob...), nil }
[ "func", "(", "ck", "*", "CryptoKey", ")", "Encrypt", "(", "in", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "nonce", "[", "NonceSize", "]", "byte", "\n", "_", ",", "err", ":=", "io", ".", "ReadFull", "(", "prng", ",", "nonce", "[", ":", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "blob", ":=", "secretbox", ".", "Seal", "(", "nil", ",", "in", ",", "&", "nonce", ",", "(", "*", "[", "KeySize", "]", "byte", ")", "(", "ck", ")", ")", "\n", "return", "append", "(", "nonce", "[", ":", "]", ",", "blob", "...", ")", ",", "nil", "\n", "}" ]
// Encrypt encrypts the passed data.
[ "Encrypt", "encrypts", "the", "passed", "data", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/snacl/snacl.go#L48-L56
train
btcsuite/btcwallet
snacl/snacl.go
Decrypt
func (ck *CryptoKey) Decrypt(in []byte) ([]byte, error) { if len(in) < NonceSize { return nil, ErrMalformed } var nonce [NonceSize]byte copy(nonce[:], in[:NonceSize]) blob := in[NonceSize:] opened, ok := secretbox.Open(nil, blob, &nonce, (*[KeySize]byte)(ck)) if !ok { return nil, ErrDecryptFailed } return opened, nil }
go
func (ck *CryptoKey) Decrypt(in []byte) ([]byte, error) { if len(in) < NonceSize { return nil, ErrMalformed } var nonce [NonceSize]byte copy(nonce[:], in[:NonceSize]) blob := in[NonceSize:] opened, ok := secretbox.Open(nil, blob, &nonce, (*[KeySize]byte)(ck)) if !ok { return nil, ErrDecryptFailed } return opened, nil }
[ "func", "(", "ck", "*", "CryptoKey", ")", "Decrypt", "(", "in", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "len", "(", "in", ")", "<", "NonceSize", "{", "return", "nil", ",", "ErrMalformed", "\n", "}", "\n\n", "var", "nonce", "[", "NonceSize", "]", "byte", "\n", "copy", "(", "nonce", "[", ":", "]", ",", "in", "[", ":", "NonceSize", "]", ")", "\n", "blob", ":=", "in", "[", "NonceSize", ":", "]", "\n\n", "opened", ",", "ok", ":=", "secretbox", ".", "Open", "(", "nil", ",", "blob", ",", "&", "nonce", ",", "(", "*", "[", "KeySize", "]", "byte", ")", "(", "ck", ")", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "ErrDecryptFailed", "\n", "}", "\n\n", "return", "opened", ",", "nil", "\n", "}" ]
// Decrypt decrypts the passed data. The must be the output of the Encrypt // function.
[ "Decrypt", "decrypts", "the", "passed", "data", ".", "The", "must", "be", "the", "output", "of", "the", "Encrypt", "function", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/snacl/snacl.go#L60-L75
train
btcsuite/btcwallet
snacl/snacl.go
GenerateCryptoKey
func GenerateCryptoKey() (*CryptoKey, error) { var key CryptoKey _, err := io.ReadFull(prng, key[:]) if err != nil { return nil, err } return &key, nil }
go
func GenerateCryptoKey() (*CryptoKey, error) { var key CryptoKey _, err := io.ReadFull(prng, key[:]) if err != nil { return nil, err } return &key, nil }
[ "func", "GenerateCryptoKey", "(", ")", "(", "*", "CryptoKey", ",", "error", ")", "{", "var", "key", "CryptoKey", "\n", "_", ",", "err", ":=", "io", ".", "ReadFull", "(", "prng", ",", "key", "[", ":", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "key", ",", "nil", "\n", "}" ]
// GenerateCryptoKey generates a new crypotgraphically random key.
[ "GenerateCryptoKey", "generates", "a", "new", "crypotgraphically", "random", "key", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/snacl/snacl.go#L86-L94
train
btcsuite/btcwallet
snacl/snacl.go
deriveKey
func (sk *SecretKey) deriveKey(password *[]byte) error { key, err := scrypt.Key(*password, sk.Parameters.Salt[:], sk.Parameters.N, sk.Parameters.R, sk.Parameters.P, len(sk.Key)) if err != nil { return err } copy(sk.Key[:], key) zero.Bytes(key) // I'm not a fan of forced garbage collections, but scrypt allocates a // ton of memory and calling it back to back without a GC cycle in // between means you end up needing twice the amount of memory. For // example, if your scrypt parameters are such that you require 1GB and // you call it twice in a row, without this you end up allocating 2GB // since the first GB probably hasn't been released yet. debug.FreeOSMemory() return nil }
go
func (sk *SecretKey) deriveKey(password *[]byte) error { key, err := scrypt.Key(*password, sk.Parameters.Salt[:], sk.Parameters.N, sk.Parameters.R, sk.Parameters.P, len(sk.Key)) if err != nil { return err } copy(sk.Key[:], key) zero.Bytes(key) // I'm not a fan of forced garbage collections, but scrypt allocates a // ton of memory and calling it back to back without a GC cycle in // between means you end up needing twice the amount of memory. For // example, if your scrypt parameters are such that you require 1GB and // you call it twice in a row, without this you end up allocating 2GB // since the first GB probably hasn't been released yet. debug.FreeOSMemory() return nil }
[ "func", "(", "sk", "*", "SecretKey", ")", "deriveKey", "(", "password", "*", "[", "]", "byte", ")", "error", "{", "key", ",", "err", ":=", "scrypt", ".", "Key", "(", "*", "password", ",", "sk", ".", "Parameters", ".", "Salt", "[", ":", "]", ",", "sk", ".", "Parameters", ".", "N", ",", "sk", ".", "Parameters", ".", "R", ",", "sk", ".", "Parameters", ".", "P", ",", "len", "(", "sk", ".", "Key", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "copy", "(", "sk", ".", "Key", "[", ":", "]", ",", "key", ")", "\n", "zero", ".", "Bytes", "(", "key", ")", "\n\n", "// I'm not a fan of forced garbage collections, but scrypt allocates a", "// ton of memory and calling it back to back without a GC cycle in", "// between means you end up needing twice the amount of memory. For", "// example, if your scrypt parameters are such that you require 1GB and", "// you call it twice in a row, without this you end up allocating 2GB", "// since the first GB probably hasn't been released yet.", "debug", ".", "FreeOSMemory", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// deriveKey fills out the Key field.
[ "deriveKey", "fills", "out", "the", "Key", "field", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/snacl/snacl.go#L113-L134
train
btcsuite/btcwallet
snacl/snacl.go
Marshal
func (sk *SecretKey) Marshal() []byte { params := &sk.Parameters // The marshalled format for the the params is as follows: // <salt><digest><N><R><P> // // KeySize + sha256.Size + N (8 bytes) + R (8 bytes) + P (8 bytes) marshalled := make([]byte, KeySize+sha256.Size+24) b := marshalled copy(b[:KeySize], params.Salt[:]) b = b[KeySize:] copy(b[:sha256.Size], params.Digest[:]) b = b[sha256.Size:] binary.LittleEndian.PutUint64(b[:8], uint64(params.N)) b = b[8:] binary.LittleEndian.PutUint64(b[:8], uint64(params.R)) b = b[8:] binary.LittleEndian.PutUint64(b[:8], uint64(params.P)) return marshalled }
go
func (sk *SecretKey) Marshal() []byte { params := &sk.Parameters // The marshalled format for the the params is as follows: // <salt><digest><N><R><P> // // KeySize + sha256.Size + N (8 bytes) + R (8 bytes) + P (8 bytes) marshalled := make([]byte, KeySize+sha256.Size+24) b := marshalled copy(b[:KeySize], params.Salt[:]) b = b[KeySize:] copy(b[:sha256.Size], params.Digest[:]) b = b[sha256.Size:] binary.LittleEndian.PutUint64(b[:8], uint64(params.N)) b = b[8:] binary.LittleEndian.PutUint64(b[:8], uint64(params.R)) b = b[8:] binary.LittleEndian.PutUint64(b[:8], uint64(params.P)) return marshalled }
[ "func", "(", "sk", "*", "SecretKey", ")", "Marshal", "(", ")", "[", "]", "byte", "{", "params", ":=", "&", "sk", ".", "Parameters", "\n\n", "// The marshalled format for the the params is as follows:", "// <salt><digest><N><R><P>", "//", "// KeySize + sha256.Size + N (8 bytes) + R (8 bytes) + P (8 bytes)", "marshalled", ":=", "make", "(", "[", "]", "byte", ",", "KeySize", "+", "sha256", ".", "Size", "+", "24", ")", "\n\n", "b", ":=", "marshalled", "\n", "copy", "(", "b", "[", ":", "KeySize", "]", ",", "params", ".", "Salt", "[", ":", "]", ")", "\n", "b", "=", "b", "[", "KeySize", ":", "]", "\n", "copy", "(", "b", "[", ":", "sha256", ".", "Size", "]", ",", "params", ".", "Digest", "[", ":", "]", ")", "\n", "b", "=", "b", "[", "sha256", ".", "Size", ":", "]", "\n", "binary", ".", "LittleEndian", ".", "PutUint64", "(", "b", "[", ":", "8", "]", ",", "uint64", "(", "params", ".", "N", ")", ")", "\n", "b", "=", "b", "[", "8", ":", "]", "\n", "binary", ".", "LittleEndian", ".", "PutUint64", "(", "b", "[", ":", "8", "]", ",", "uint64", "(", "params", ".", "R", ")", ")", "\n", "b", "=", "b", "[", "8", ":", "]", "\n", "binary", ".", "LittleEndian", ".", "PutUint64", "(", "b", "[", ":", "8", "]", ",", "uint64", "(", "params", ".", "P", ")", ")", "\n\n", "return", "marshalled", "\n", "}" ]
// Marshal returns the Parameters field marshalled into a format suitable for // storage. This result of this can be stored in clear text.
[ "Marshal", "returns", "the", "Parameters", "field", "marshalled", "into", "a", "format", "suitable", "for", "storage", ".", "This", "result", "of", "this", "can", "be", "stored", "in", "clear", "text", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/snacl/snacl.go#L138-L159
train
btcsuite/btcwallet
snacl/snacl.go
Unmarshal
func (sk *SecretKey) Unmarshal(marshalled []byte) error { if sk.Key == nil { sk.Key = (*CryptoKey)(&[KeySize]byte{}) } // The marshalled format for the the params is as follows: // <salt><digest><N><R><P> // // KeySize + sha256.Size + N (8 bytes) + R (8 bytes) + P (8 bytes) if len(marshalled) != KeySize+sha256.Size+24 { return ErrMalformed } params := &sk.Parameters copy(params.Salt[:], marshalled[:KeySize]) marshalled = marshalled[KeySize:] copy(params.Digest[:], marshalled[:sha256.Size]) marshalled = marshalled[sha256.Size:] params.N = int(binary.LittleEndian.Uint64(marshalled[:8])) marshalled = marshalled[8:] params.R = int(binary.LittleEndian.Uint64(marshalled[:8])) marshalled = marshalled[8:] params.P = int(binary.LittleEndian.Uint64(marshalled[:8])) return nil }
go
func (sk *SecretKey) Unmarshal(marshalled []byte) error { if sk.Key == nil { sk.Key = (*CryptoKey)(&[KeySize]byte{}) } // The marshalled format for the the params is as follows: // <salt><digest><N><R><P> // // KeySize + sha256.Size + N (8 bytes) + R (8 bytes) + P (8 bytes) if len(marshalled) != KeySize+sha256.Size+24 { return ErrMalformed } params := &sk.Parameters copy(params.Salt[:], marshalled[:KeySize]) marshalled = marshalled[KeySize:] copy(params.Digest[:], marshalled[:sha256.Size]) marshalled = marshalled[sha256.Size:] params.N = int(binary.LittleEndian.Uint64(marshalled[:8])) marshalled = marshalled[8:] params.R = int(binary.LittleEndian.Uint64(marshalled[:8])) marshalled = marshalled[8:] params.P = int(binary.LittleEndian.Uint64(marshalled[:8])) return nil }
[ "func", "(", "sk", "*", "SecretKey", ")", "Unmarshal", "(", "marshalled", "[", "]", "byte", ")", "error", "{", "if", "sk", ".", "Key", "==", "nil", "{", "sk", ".", "Key", "=", "(", "*", "CryptoKey", ")", "(", "&", "[", "KeySize", "]", "byte", "{", "}", ")", "\n", "}", "\n\n", "// The marshalled format for the the params is as follows:", "// <salt><digest><N><R><P>", "//", "// KeySize + sha256.Size + N (8 bytes) + R (8 bytes) + P (8 bytes)", "if", "len", "(", "marshalled", ")", "!=", "KeySize", "+", "sha256", ".", "Size", "+", "24", "{", "return", "ErrMalformed", "\n", "}", "\n\n", "params", ":=", "&", "sk", ".", "Parameters", "\n", "copy", "(", "params", ".", "Salt", "[", ":", "]", ",", "marshalled", "[", ":", "KeySize", "]", ")", "\n", "marshalled", "=", "marshalled", "[", "KeySize", ":", "]", "\n", "copy", "(", "params", ".", "Digest", "[", ":", "]", ",", "marshalled", "[", ":", "sha256", ".", "Size", "]", ")", "\n", "marshalled", "=", "marshalled", "[", "sha256", ".", "Size", ":", "]", "\n", "params", ".", "N", "=", "int", "(", "binary", ".", "LittleEndian", ".", "Uint64", "(", "marshalled", "[", ":", "8", "]", ")", ")", "\n", "marshalled", "=", "marshalled", "[", "8", ":", "]", "\n", "params", ".", "R", "=", "int", "(", "binary", ".", "LittleEndian", ".", "Uint64", "(", "marshalled", "[", ":", "8", "]", ")", ")", "\n", "marshalled", "=", "marshalled", "[", "8", ":", "]", "\n", "params", ".", "P", "=", "int", "(", "binary", ".", "LittleEndian", ".", "Uint64", "(", "marshalled", "[", ":", "8", "]", ")", ")", "\n\n", "return", "nil", "\n", "}" ]
// Unmarshal unmarshalls the parameters needed to derive the secret key from a // passphrase into sk.
[ "Unmarshal", "unmarshalls", "the", "parameters", "needed", "to", "derive", "the", "secret", "key", "from", "a", "passphrase", "into", "sk", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/snacl/snacl.go#L163-L188
train
btcsuite/btcwallet
snacl/snacl.go
DeriveKey
func (sk *SecretKey) DeriveKey(password *[]byte) error { if err := sk.deriveKey(password); err != nil { return err } // verify password digest := sha256.Sum256(sk.Key[:]) if subtle.ConstantTimeCompare(digest[:], sk.Parameters.Digest[:]) != 1 { return ErrInvalidPassword } return nil }
go
func (sk *SecretKey) DeriveKey(password *[]byte) error { if err := sk.deriveKey(password); err != nil { return err } // verify password digest := sha256.Sum256(sk.Key[:]) if subtle.ConstantTimeCompare(digest[:], sk.Parameters.Digest[:]) != 1 { return ErrInvalidPassword } return nil }
[ "func", "(", "sk", "*", "SecretKey", ")", "DeriveKey", "(", "password", "*", "[", "]", "byte", ")", "error", "{", "if", "err", ":=", "sk", ".", "deriveKey", "(", "password", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// verify password", "digest", ":=", "sha256", ".", "Sum256", "(", "sk", ".", "Key", "[", ":", "]", ")", "\n", "if", "subtle", ".", "ConstantTimeCompare", "(", "digest", "[", ":", "]", ",", "sk", ".", "Parameters", ".", "Digest", "[", ":", "]", ")", "!=", "1", "{", "return", "ErrInvalidPassword", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// DeriveKey derives the underlying secret key and ensures it matches the // expected digest. This should only be called after previously calling the // Zero function or on an initial Unmarshal.
[ "DeriveKey", "derives", "the", "underlying", "secret", "key", "and", "ensures", "it", "matches", "the", "expected", "digest", ".", "This", "should", "only", "be", "called", "after", "previously", "calling", "the", "Zero", "function", "or", "on", "an", "initial", "Unmarshal", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/snacl/snacl.go#L200-L212
train
btcsuite/btcwallet
snacl/snacl.go
Encrypt
func (sk *SecretKey) Encrypt(in []byte) ([]byte, error) { return sk.Key.Encrypt(in) }
go
func (sk *SecretKey) Encrypt(in []byte) ([]byte, error) { return sk.Key.Encrypt(in) }
[ "func", "(", "sk", "*", "SecretKey", ")", "Encrypt", "(", "in", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "sk", ".", "Key", ".", "Encrypt", "(", "in", ")", "\n", "}" ]
// Encrypt encrypts in bytes and returns a JSON blob.
[ "Encrypt", "encrypts", "in", "bytes", "and", "returns", "a", "JSON", "blob", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/snacl/snacl.go#L215-L217
train
btcsuite/btcwallet
snacl/snacl.go
Decrypt
func (sk *SecretKey) Decrypt(in []byte) ([]byte, error) { return sk.Key.Decrypt(in) }
go
func (sk *SecretKey) Decrypt(in []byte) ([]byte, error) { return sk.Key.Decrypt(in) }
[ "func", "(", "sk", "*", "SecretKey", ")", "Decrypt", "(", "in", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "sk", ".", "Key", ".", "Decrypt", "(", "in", ")", "\n", "}" ]
// Decrypt takes in a JSON blob and returns it's decrypted form.
[ "Decrypt", "takes", "in", "a", "JSON", "blob", "and", "returns", "it", "s", "decrypted", "form", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/snacl/snacl.go#L220-L222
train