repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
genuinetools/reg | registry/tokentransport.go | RoundTrip | func (t *TokenTransport) RoundTrip(req *http.Request) (*http.Response, error) {
resp, err := t.Transport.RoundTrip(req)
if err != nil {
return resp, err
}
authService, err := isTokenDemand(resp)
if err != nil {
resp.Body.Close()
return nil, err
}
if authService == nil {
return resp, nil
}
resp.Body.Close()
return t.authAndRetry(authService, req)
} | go | func (t *TokenTransport) RoundTrip(req *http.Request) (*http.Response, error) {
resp, err := t.Transport.RoundTrip(req)
if err != nil {
return resp, err
}
authService, err := isTokenDemand(resp)
if err != nil {
resp.Body.Close()
return nil, err
}
if authService == nil {
return resp, nil
}
resp.Body.Close()
return t.authAndRetry(authService, req)
} | [
"func",
"(",
"t",
"*",
"TokenTransport",
")",
"RoundTrip",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"resp",
",",
"err",
":=",
"t",
".",
"Transport",
".",
"RoundTrip",
"(",
"req",
")",
... | // RoundTrip defines the round tripper for token transport. | [
"RoundTrip",
"defines",
"the",
"round",
"tripper",
"for",
"token",
"transport",
"."
] | d959057b30da67d5f162790f9d5b5160686901fd | https://github.com/genuinetools/reg/blob/d959057b30da67d5f162790f9d5b5160686901fd/registry/tokentransport.go#L25-L44 | train |
genuinetools/reg | registry/tokentransport.go | Token | func (r *Registry) Token(ctx context.Context, url string) (string, error) {
r.Logf("registry.token url=%s", url)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return "", err
}
client := http.DefaultClient
if r.Opt.Insecure {
client = &http.Client{
Timeout: r.Opt.Timeout,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}
}
resp, err := client.Do(req.WithContext(ctx))
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusForbidden && gcrMatcher.MatchString(url) {
// GCR is not sending HTTP 401 on missing credentials but a HTTP 403 without
// any further information about why the request failed. Sending the credentials
// from the Docker config fixes this.
return "", ErrBasicAuth
}
a, err := isTokenDemand(resp)
if err != nil {
return "", err
}
if a == nil {
r.Logf("registry.token authService=nil")
return "", nil
}
authReq, err := a.Request(r.Username, r.Password)
if err != nil {
return "", err
}
resp, err = http.DefaultClient.Do(authReq.WithContext(ctx))
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("getting token failed with StatusCode != StatusOK but %d", resp.StatusCode)
}
var authToken authToken
if err := json.NewDecoder(resp.Body).Decode(&authToken); err != nil {
return "", err
}
return authToken.String()
} | go | func (r *Registry) Token(ctx context.Context, url string) (string, error) {
r.Logf("registry.token url=%s", url)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return "", err
}
client := http.DefaultClient
if r.Opt.Insecure {
client = &http.Client{
Timeout: r.Opt.Timeout,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}
}
resp, err := client.Do(req.WithContext(ctx))
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusForbidden && gcrMatcher.MatchString(url) {
// GCR is not sending HTTP 401 on missing credentials but a HTTP 403 without
// any further information about why the request failed. Sending the credentials
// from the Docker config fixes this.
return "", ErrBasicAuth
}
a, err := isTokenDemand(resp)
if err != nil {
return "", err
}
if a == nil {
r.Logf("registry.token authService=nil")
return "", nil
}
authReq, err := a.Request(r.Username, r.Password)
if err != nil {
return "", err
}
resp, err = http.DefaultClient.Do(authReq.WithContext(ctx))
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("getting token failed with StatusCode != StatusOK but %d", resp.StatusCode)
}
var authToken authToken
if err := json.NewDecoder(resp.Body).Decode(&authToken); err != nil {
return "", err
}
return authToken.String()
} | [
"func",
"(",
"r",
"*",
"Registry",
")",
"Token",
"(",
"ctx",
"context",
".",
"Context",
",",
"url",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"r",
".",
"Logf",
"(",
"\"registry.token url=%s\"",
",",
"url",
")",
"\n",
"req",
",",
"err",
... | // Token returns the required token for the specific resource url. If the registry requires basic authentication, this
// function returns ErrBasicAuth. | [
"Token",
"returns",
"the",
"required",
"token",
"for",
"the",
"specific",
"resource",
"url",
".",
"If",
"the",
"registry",
"requires",
"basic",
"authentication",
"this",
"function",
"returns",
"ErrBasicAuth",
"."
] | d959057b30da67d5f162790f9d5b5160686901fd | https://github.com/genuinetools/reg/blob/d959057b30da67d5f162790f9d5b5160686901fd/registry/tokentransport.go#L144-L207 | train |
genuinetools/reg | registry/tokentransport.go | Headers | func (r *Registry) Headers(ctx context.Context, uri string) (map[string]string, error) {
// Get the token.
token, err := r.Token(ctx, uri)
if err != nil {
if err == ErrBasicAuth {
// If we couldn't get a token because the server requires basic auth, just return basic auth headers.
return map[string]string{
"Authorization": fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(r.Username+":"+r.Password))),
}, nil
}
}
if len(token) < 1 {
r.Logf("got empty token for %s", uri)
return map[string]string{}, nil
}
return map[string]string{
"Authorization": fmt.Sprintf("Bearer %s", token),
}, nil
} | go | func (r *Registry) Headers(ctx context.Context, uri string) (map[string]string, error) {
// Get the token.
token, err := r.Token(ctx, uri)
if err != nil {
if err == ErrBasicAuth {
// If we couldn't get a token because the server requires basic auth, just return basic auth headers.
return map[string]string{
"Authorization": fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(r.Username+":"+r.Password))),
}, nil
}
}
if len(token) < 1 {
r.Logf("got empty token for %s", uri)
return map[string]string{}, nil
}
return map[string]string{
"Authorization": fmt.Sprintf("Bearer %s", token),
}, nil
} | [
"func",
"(",
"r",
"*",
"Registry",
")",
"Headers",
"(",
"ctx",
"context",
".",
"Context",
",",
"uri",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"token",
",",
"err",
":=",
"r",
".",
"Token",
"(",
"ctx",
",",
... | // Headers returns the authorization headers for a specific uri. | [
"Headers",
"returns",
"the",
"authorization",
"headers",
"for",
"a",
"specific",
"uri",
"."
] | d959057b30da67d5f162790f9d5b5160686901fd | https://github.com/genuinetools/reg/blob/d959057b30da67d5f162790f9d5b5160686901fd/registry/tokentransport.go#L210-L230 | train |
genuinetools/reg | registry/layer.go | DownloadLayer | func (r *Registry) DownloadLayer(ctx context.Context, repository string, digest digest.Digest) (io.ReadCloser, error) {
url := r.url("/v2/%s/blobs/%s", repository, digest)
r.Logf("registry.layer.download url=%s repository=%s digest=%s", url, repository, digest)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
resp, err := r.Client.Do(req.WithContext(ctx))
if err != nil {
return nil, err
}
return resp.Body, nil
} | go | func (r *Registry) DownloadLayer(ctx context.Context, repository string, digest digest.Digest) (io.ReadCloser, error) {
url := r.url("/v2/%s/blobs/%s", repository, digest)
r.Logf("registry.layer.download url=%s repository=%s digest=%s", url, repository, digest)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
resp, err := r.Client.Do(req.WithContext(ctx))
if err != nil {
return nil, err
}
return resp.Body, nil
} | [
"func",
"(",
"r",
"*",
"Registry",
")",
"DownloadLayer",
"(",
"ctx",
"context",
".",
"Context",
",",
"repository",
"string",
",",
"digest",
"digest",
".",
"Digest",
")",
"(",
"io",
".",
"ReadCloser",
",",
"error",
")",
"{",
"url",
":=",
"r",
".",
"ur... | // DownloadLayer downloads a specific layer by digest for a repository. | [
"DownloadLayer",
"downloads",
"a",
"specific",
"layer",
"by",
"digest",
"for",
"a",
"repository",
"."
] | d959057b30da67d5f162790f9d5b5160686901fd | https://github.com/genuinetools/reg/blob/d959057b30da67d5f162790f9d5b5160686901fd/registry/layer.go#L16-L30 | train |
genuinetools/reg | registry/layer.go | UploadLayer | func (r *Registry) UploadLayer(ctx context.Context, repository string, digest reference.Reference, content io.Reader) error {
uploadURL, token, err := r.initiateUpload(ctx, repository)
if err != nil {
return err
}
q := uploadURL.Query()
q.Set("digest", digest.String())
uploadURL.RawQuery = q.Encode()
r.Logf("registry.layer.upload url=%s repository=%s digest=%s", uploadURL, repository, digest)
upload, err := http.NewRequest("PUT", uploadURL.String(), content)
if err != nil {
return err
}
upload.Header.Set("Content-Type", "application/octet-stream")
upload.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
_, err = r.Client.Do(upload.WithContext(ctx))
return err
} | go | func (r *Registry) UploadLayer(ctx context.Context, repository string, digest reference.Reference, content io.Reader) error {
uploadURL, token, err := r.initiateUpload(ctx, repository)
if err != nil {
return err
}
q := uploadURL.Query()
q.Set("digest", digest.String())
uploadURL.RawQuery = q.Encode()
r.Logf("registry.layer.upload url=%s repository=%s digest=%s", uploadURL, repository, digest)
upload, err := http.NewRequest("PUT", uploadURL.String(), content)
if err != nil {
return err
}
upload.Header.Set("Content-Type", "application/octet-stream")
upload.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
_, err = r.Client.Do(upload.WithContext(ctx))
return err
} | [
"func",
"(",
"r",
"*",
"Registry",
")",
"UploadLayer",
"(",
"ctx",
"context",
".",
"Context",
",",
"repository",
"string",
",",
"digest",
"reference",
".",
"Reference",
",",
"content",
"io",
".",
"Reader",
")",
"error",
"{",
"uploadURL",
",",
"token",
",... | // UploadLayer uploads a specific layer by digest for a repository. | [
"UploadLayer",
"uploads",
"a",
"specific",
"layer",
"by",
"digest",
"for",
"a",
"repository",
"."
] | d959057b30da67d5f162790f9d5b5160686901fd | https://github.com/genuinetools/reg/blob/d959057b30da67d5f162790f9d5b5160686901fd/registry/layer.go#L33-L53 | train |
genuinetools/reg | registry/layer.go | HasLayer | func (r *Registry) HasLayer(ctx context.Context, repository string, digest digest.Digest) (bool, error) {
checkURL := r.url("/v2/%s/blobs/%s", repository, digest)
r.Logf("registry.layer.check url=%s repository=%s digest=%s", checkURL, repository, digest)
req, err := http.NewRequest("HEAD", checkURL, nil)
if err != nil {
return false, err
}
resp, err := r.Client.Do(req.WithContext(ctx))
if err == nil {
defer resp.Body.Close()
return resp.StatusCode == http.StatusOK, nil
}
urlErr, ok := err.(*url.Error)
if !ok {
return false, err
}
httpErr, ok := urlErr.Err.(*httpStatusError)
if !ok {
return false, err
}
if httpErr.Response.StatusCode == http.StatusNotFound {
return false, nil
}
return false, err
} | go | func (r *Registry) HasLayer(ctx context.Context, repository string, digest digest.Digest) (bool, error) {
checkURL := r.url("/v2/%s/blobs/%s", repository, digest)
r.Logf("registry.layer.check url=%s repository=%s digest=%s", checkURL, repository, digest)
req, err := http.NewRequest("HEAD", checkURL, nil)
if err != nil {
return false, err
}
resp, err := r.Client.Do(req.WithContext(ctx))
if err == nil {
defer resp.Body.Close()
return resp.StatusCode == http.StatusOK, nil
}
urlErr, ok := err.(*url.Error)
if !ok {
return false, err
}
httpErr, ok := urlErr.Err.(*httpStatusError)
if !ok {
return false, err
}
if httpErr.Response.StatusCode == http.StatusNotFound {
return false, nil
}
return false, err
} | [
"func",
"(",
"r",
"*",
"Registry",
")",
"HasLayer",
"(",
"ctx",
"context",
".",
"Context",
",",
"repository",
"string",
",",
"digest",
"digest",
".",
"Digest",
")",
"(",
"bool",
",",
"error",
")",
"{",
"checkURL",
":=",
"r",
".",
"url",
"(",
"\"/v2/%... | // HasLayer returns if the registry contains the specific digest for a repository. | [
"HasLayer",
"returns",
"if",
"the",
"registry",
"contains",
"the",
"specific",
"digest",
"for",
"a",
"repository",
"."
] | d959057b30da67d5f162790f9d5b5160686901fd | https://github.com/genuinetools/reg/blob/d959057b30da67d5f162790f9d5b5160686901fd/registry/layer.go#L56-L83 | train |
genuinetools/reg | repoutils/repoutils.go | GetAuthConfig | func GetAuthConfig(username, password, registry string) (types.AuthConfig, error) {
if username != "" && password != "" && registry != "" {
return types.AuthConfig{
Username: username,
Password: password,
ServerAddress: registry,
}, nil
}
dcfg, err := config.Load(config.Dir())
if err != nil {
return types.AuthConfig{}, fmt.Errorf("loading config file failed: %v", err)
}
// return error early if there are no auths saved
if !dcfg.ContainsAuth() {
// If we were passed a registry, just use that.
if registry != "" {
return setDefaultRegistry(types.AuthConfig{
ServerAddress: registry,
}), nil
}
// Otherwise, just use an empty auth config.
return types.AuthConfig{}, nil
}
authConfigs, err := dcfg.GetAllCredentials()
if err != nil {
return types.AuthConfig{}, fmt.Errorf("getting credentials failed: %v", err)
}
// if they passed a specific registry, return those creds _if_ they exist
if registry != "" {
// try with the user input
if creds, ok := authConfigs[registry]; ok {
fixAuthConfig(&creds, registry)
return creds, nil
}
// remove https:// from user input and try again
if strings.HasPrefix(registry, "https://") {
registryCleaned := strings.TrimPrefix(registry, "https://")
if creds, ok := authConfigs[registryCleaned]; ok {
fixAuthConfig(&creds, registryCleaned)
return creds, nil
}
}
// remove http:// from user input and try again
if strings.HasPrefix(registry, "http://") {
registryCleaned := strings.TrimPrefix(registry, "http://")
if creds, ok := authConfigs[registryCleaned]; ok {
fixAuthConfig(&creds, registryCleaned)
return creds, nil
}
}
// add https:// to user input and try again
// see https://github.com/genuinetools/reg/issues/32
if !strings.HasPrefix(registry, "https://") && !strings.HasPrefix(registry, "http://") {
registryCleaned := "https://" + registry
if creds, ok := authConfigs[registryCleaned]; ok {
fixAuthConfig(&creds, registryCleaned)
return creds, nil
}
}
logrus.Debugf("Using registry %q with no authentication", registry)
// Otherwise just use the registry with no auth.
return setDefaultRegistry(types.AuthConfig{
ServerAddress: registry,
}), nil
}
// Just set the auth config as the first registryURL, username and password
// found in the auth config.
for _, creds := range authConfigs {
fmt.Printf("No registry passed. Using registry %q\n", creds.ServerAddress)
return creds, nil
}
// Don't use any authentication.
// We should never get here.
fmt.Println("Not using any authentication")
return types.AuthConfig{}, nil
} | go | func GetAuthConfig(username, password, registry string) (types.AuthConfig, error) {
if username != "" && password != "" && registry != "" {
return types.AuthConfig{
Username: username,
Password: password,
ServerAddress: registry,
}, nil
}
dcfg, err := config.Load(config.Dir())
if err != nil {
return types.AuthConfig{}, fmt.Errorf("loading config file failed: %v", err)
}
// return error early if there are no auths saved
if !dcfg.ContainsAuth() {
// If we were passed a registry, just use that.
if registry != "" {
return setDefaultRegistry(types.AuthConfig{
ServerAddress: registry,
}), nil
}
// Otherwise, just use an empty auth config.
return types.AuthConfig{}, nil
}
authConfigs, err := dcfg.GetAllCredentials()
if err != nil {
return types.AuthConfig{}, fmt.Errorf("getting credentials failed: %v", err)
}
// if they passed a specific registry, return those creds _if_ they exist
if registry != "" {
// try with the user input
if creds, ok := authConfigs[registry]; ok {
fixAuthConfig(&creds, registry)
return creds, nil
}
// remove https:// from user input and try again
if strings.HasPrefix(registry, "https://") {
registryCleaned := strings.TrimPrefix(registry, "https://")
if creds, ok := authConfigs[registryCleaned]; ok {
fixAuthConfig(&creds, registryCleaned)
return creds, nil
}
}
// remove http:// from user input and try again
if strings.HasPrefix(registry, "http://") {
registryCleaned := strings.TrimPrefix(registry, "http://")
if creds, ok := authConfigs[registryCleaned]; ok {
fixAuthConfig(&creds, registryCleaned)
return creds, nil
}
}
// add https:// to user input and try again
// see https://github.com/genuinetools/reg/issues/32
if !strings.HasPrefix(registry, "https://") && !strings.HasPrefix(registry, "http://") {
registryCleaned := "https://" + registry
if creds, ok := authConfigs[registryCleaned]; ok {
fixAuthConfig(&creds, registryCleaned)
return creds, nil
}
}
logrus.Debugf("Using registry %q with no authentication", registry)
// Otherwise just use the registry with no auth.
return setDefaultRegistry(types.AuthConfig{
ServerAddress: registry,
}), nil
}
// Just set the auth config as the first registryURL, username and password
// found in the auth config.
for _, creds := range authConfigs {
fmt.Printf("No registry passed. Using registry %q\n", creds.ServerAddress)
return creds, nil
}
// Don't use any authentication.
// We should never get here.
fmt.Println("Not using any authentication")
return types.AuthConfig{}, nil
} | [
"func",
"GetAuthConfig",
"(",
"username",
",",
"password",
",",
"registry",
"string",
")",
"(",
"types",
".",
"AuthConfig",
",",
"error",
")",
"{",
"if",
"username",
"!=",
"\"\"",
"&&",
"password",
"!=",
"\"\"",
"&&",
"registry",
"!=",
"\"\"",
"{",
"retu... | // GetAuthConfig returns the docker registry AuthConfig.
// Optionally takes in the authentication values, otherwise pulls them from the
// docker config file. | [
"GetAuthConfig",
"returns",
"the",
"docker",
"registry",
"AuthConfig",
".",
"Optionally",
"takes",
"in",
"the",
"authentication",
"values",
"otherwise",
"pulls",
"them",
"from",
"the",
"docker",
"config",
"file",
"."
] | d959057b30da67d5f162790f9d5b5160686901fd | https://github.com/genuinetools/reg/blob/d959057b30da67d5f162790f9d5b5160686901fd/repoutils/repoutils.go#L23-L110 | train |
genuinetools/reg | repoutils/repoutils.go | GetRepoAndRef | func GetRepoAndRef(image string) (repo, ref string, err error) {
if image == "" {
return "", "", reference.ErrNameEmpty
}
image = addLatestTagSuffix(image)
var parts []string
if strings.Contains(image, "@") {
parts = strings.Split(image, "@")
} else if strings.Contains(image, ":") {
parts = strings.Split(image, ":")
}
repo = parts[0]
if len(parts) > 1 {
ref = parts[1]
}
return
} | go | func GetRepoAndRef(image string) (repo, ref string, err error) {
if image == "" {
return "", "", reference.ErrNameEmpty
}
image = addLatestTagSuffix(image)
var parts []string
if strings.Contains(image, "@") {
parts = strings.Split(image, "@")
} else if strings.Contains(image, ":") {
parts = strings.Split(image, ":")
}
repo = parts[0]
if len(parts) > 1 {
ref = parts[1]
}
return
} | [
"func",
"GetRepoAndRef",
"(",
"image",
"string",
")",
"(",
"repo",
",",
"ref",
"string",
",",
"err",
"error",
")",
"{",
"if",
"image",
"==",
"\"\"",
"{",
"return",
"\"\"",
",",
"\"\"",
",",
"reference",
".",
"ErrNameEmpty",
"\n",
"}",
"\n",
"image",
... | // GetRepoAndRef parses the repo name and reference. | [
"GetRepoAndRef",
"parses",
"the",
"repo",
"name",
"and",
"reference",
"."
] | d959057b30da67d5f162790f9d5b5160686901fd | https://github.com/genuinetools/reg/blob/d959057b30da67d5f162790f9d5b5160686901fd/repoutils/repoutils.go#L123-L143 | train |
genuinetools/reg | registry/digest.go | Digest | func (r *Registry) Digest(ctx context.Context, image Image) (digest.Digest, error) {
if len(image.Digest) > 1 {
// return early if we already have an image digest.
return image.Digest, nil
}
url := r.url("/v2/%s/manifests/%s", image.Path, image.Tag)
r.Logf("registry.manifests.get url=%s repository=%s ref=%s",
url, image.Path, image.Tag)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return "", err
}
req.Header.Add("Accept", schema2.MediaTypeManifest)
resp, err := r.Client.Do(req.WithContext(ctx))
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNotFound {
return "", fmt.Errorf("got status code: %d", resp.StatusCode)
}
return digest.Parse(resp.Header.Get("Docker-Content-Digest"))
} | go | func (r *Registry) Digest(ctx context.Context, image Image) (digest.Digest, error) {
if len(image.Digest) > 1 {
// return early if we already have an image digest.
return image.Digest, nil
}
url := r.url("/v2/%s/manifests/%s", image.Path, image.Tag)
r.Logf("registry.manifests.get url=%s repository=%s ref=%s",
url, image.Path, image.Tag)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return "", err
}
req.Header.Add("Accept", schema2.MediaTypeManifest)
resp, err := r.Client.Do(req.WithContext(ctx))
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNotFound {
return "", fmt.Errorf("got status code: %d", resp.StatusCode)
}
return digest.Parse(resp.Header.Get("Docker-Content-Digest"))
} | [
"func",
"(",
"r",
"*",
"Registry",
")",
"Digest",
"(",
"ctx",
"context",
".",
"Context",
",",
"image",
"Image",
")",
"(",
"digest",
".",
"Digest",
",",
"error",
")",
"{",
"if",
"len",
"(",
"image",
".",
"Digest",
")",
">",
"1",
"{",
"return",
"im... | // Digest returns the digest for an image. | [
"Digest",
"returns",
"the",
"digest",
"for",
"an",
"image",
"."
] | d959057b30da67d5f162790f9d5b5160686901fd | https://github.com/genuinetools/reg/blob/d959057b30da67d5f162790f9d5b5160686901fd/registry/digest.go#L13-L40 | train |
genuinetools/reg | clair/layerutil.go | NewClairLayer | func (c *Clair) NewClairLayer(ctx context.Context, r *registry.Registry, image string, fsLayers map[int]distribution.Descriptor, index int) (*Layer, error) {
var parentName string
if index < len(fsLayers)-1 {
parentName = fsLayers[index+1].Digest.String()
}
// Form the path.
p := strings.Join([]string{r.URL, "v2", image, "blobs", fsLayers[index].Digest.String()}, "/")
// Get the headers.
h, err := r.Headers(ctx, p)
if err != nil {
return nil, err
}
return &Layer{
Name: fsLayers[index].Digest.String(),
Path: p,
ParentName: parentName,
Format: "Docker",
Headers: h,
}, nil
} | go | func (c *Clair) NewClairLayer(ctx context.Context, r *registry.Registry, image string, fsLayers map[int]distribution.Descriptor, index int) (*Layer, error) {
var parentName string
if index < len(fsLayers)-1 {
parentName = fsLayers[index+1].Digest.String()
}
// Form the path.
p := strings.Join([]string{r.URL, "v2", image, "blobs", fsLayers[index].Digest.String()}, "/")
// Get the headers.
h, err := r.Headers(ctx, p)
if err != nil {
return nil, err
}
return &Layer{
Name: fsLayers[index].Digest.String(),
Path: p,
ParentName: parentName,
Format: "Docker",
Headers: h,
}, nil
} | [
"func",
"(",
"c",
"*",
"Clair",
")",
"NewClairLayer",
"(",
"ctx",
"context",
".",
"Context",
",",
"r",
"*",
"registry",
".",
"Registry",
",",
"image",
"string",
",",
"fsLayers",
"map",
"[",
"int",
"]",
"distribution",
".",
"Descriptor",
",",
"index",
"... | // NewClairLayer will form a layer struct required for a clair scan. | [
"NewClairLayer",
"will",
"form",
"a",
"layer",
"struct",
"required",
"for",
"a",
"clair",
"scan",
"."
] | d959057b30da67d5f162790f9d5b5160686901fd | https://github.com/genuinetools/reg/blob/d959057b30da67d5f162790f9d5b5160686901fd/clair/layerutil.go#L14-L36 | train |
genuinetools/reg | clair/layerutil.go | NewClairV3Layer | func (c *Clair) NewClairV3Layer(ctx context.Context, r *registry.Registry, image string, fsLayer distribution.Descriptor) (*clairpb.PostAncestryRequest_PostLayer, error) {
// Form the path.
p := strings.Join([]string{r.URL, "v2", image, "blobs", fsLayer.Digest.String()}, "/")
// Get the headers.
h, err := r.Headers(ctx, p)
if err != nil {
return nil, err
}
return &clairpb.PostAncestryRequest_PostLayer{
Hash: fsLayer.Digest.String(),
Path: p,
Headers: h,
}, nil
} | go | func (c *Clair) NewClairV3Layer(ctx context.Context, r *registry.Registry, image string, fsLayer distribution.Descriptor) (*clairpb.PostAncestryRequest_PostLayer, error) {
// Form the path.
p := strings.Join([]string{r.URL, "v2", image, "blobs", fsLayer.Digest.String()}, "/")
// Get the headers.
h, err := r.Headers(ctx, p)
if err != nil {
return nil, err
}
return &clairpb.PostAncestryRequest_PostLayer{
Hash: fsLayer.Digest.String(),
Path: p,
Headers: h,
}, nil
} | [
"func",
"(",
"c",
"*",
"Clair",
")",
"NewClairV3Layer",
"(",
"ctx",
"context",
".",
"Context",
",",
"r",
"*",
"registry",
".",
"Registry",
",",
"image",
"string",
",",
"fsLayer",
"distribution",
".",
"Descriptor",
")",
"(",
"*",
"clairpb",
".",
"PostAnce... | // NewClairV3Layer will form a layer struct required for a clair scan. | [
"NewClairV3Layer",
"will",
"form",
"a",
"layer",
"struct",
"required",
"for",
"a",
"clair",
"scan",
"."
] | d959057b30da67d5f162790f9d5b5160686901fd | https://github.com/genuinetools/reg/blob/d959057b30da67d5f162790f9d5b5160686901fd/clair/layerutil.go#L39-L54 | train |
genuinetools/reg | registry/registry.go | New | func New(ctx context.Context, auth types.AuthConfig, opt Opt) (*Registry, error) {
transport := http.DefaultTransport
if opt.Insecure {
transport = &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}
}
return newFromTransport(ctx, auth, transport, opt)
} | go | func New(ctx context.Context, auth types.AuthConfig, opt Opt) (*Registry, error) {
transport := http.DefaultTransport
if opt.Insecure {
transport = &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}
}
return newFromTransport(ctx, auth, transport, opt)
} | [
"func",
"New",
"(",
"ctx",
"context",
".",
"Context",
",",
"auth",
"types",
".",
"AuthConfig",
",",
"opt",
"Opt",
")",
"(",
"*",
"Registry",
",",
"error",
")",
"{",
"transport",
":=",
"http",
".",
"DefaultTransport",
"\n",
"if",
"opt",
".",
"Insecure",... | // New creates a new Registry struct with the given URL and credentials. | [
"New",
"creates",
"a",
"new",
"Registry",
"struct",
"with",
"the",
"given",
"URL",
"and",
"credentials",
"."
] | d959057b30da67d5f162790f9d5b5160686901fd | https://github.com/genuinetools/reg/blob/d959057b30da67d5f162790f9d5b5160686901fd/registry/registry.go#L55-L67 | train |
genuinetools/reg | registry/registry.go | url | func (r *Registry) url(pathTemplate string, args ...interface{}) string {
pathSuffix := fmt.Sprintf(pathTemplate, args...)
url := fmt.Sprintf("%s%s", r.URL, pathSuffix)
return url
} | go | func (r *Registry) url(pathTemplate string, args ...interface{}) string {
pathSuffix := fmt.Sprintf(pathTemplate, args...)
url := fmt.Sprintf("%s%s", r.URL, pathSuffix)
return url
} | [
"func",
"(",
"r",
"*",
"Registry",
")",
"url",
"(",
"pathTemplate",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"string",
"{",
"pathSuffix",
":=",
"fmt",
".",
"Sprintf",
"(",
"pathTemplate",
",",
"args",
"...",
")",
"\n",
"url",
":=",
"... | // url returns a registry URL with the passed arguements concatenated. | [
"url",
"returns",
"a",
"registry",
"URL",
"with",
"the",
"passed",
"arguements",
"concatenated",
"."
] | d959057b30da67d5f162790f9d5b5160686901fd | https://github.com/genuinetools/reg/blob/d959057b30da67d5f162790f9d5b5160686901fd/registry/registry.go#L140-L144 | train |
genuinetools/reg | clair/ancestry.go | GetAncestry | func (c *Clair) GetAncestry(ctx context.Context, name string) (*clairpb.GetAncestryResponse_Ancestry, error) {
c.Logf("clair.ancestry.get name=%s", name)
if c.grpcConn == nil {
return nil, ErrNilGRPCConn
}
client := clairpb.NewAncestryServiceClient(c.grpcConn)
resp, err := client.GetAncestry(ctx, &clairpb.GetAncestryRequest{
AncestryName: name,
})
if err != nil {
return nil, err
}
if resp == nil {
return nil, errors.New("ancestry response was nil")
}
if resp.GetStatus() != nil {
c.Logf("clair.ancestry.get ClairStatus=%#v", *resp.GetStatus())
}
return resp.GetAncestry(), nil
} | go | func (c *Clair) GetAncestry(ctx context.Context, name string) (*clairpb.GetAncestryResponse_Ancestry, error) {
c.Logf("clair.ancestry.get name=%s", name)
if c.grpcConn == nil {
return nil, ErrNilGRPCConn
}
client := clairpb.NewAncestryServiceClient(c.grpcConn)
resp, err := client.GetAncestry(ctx, &clairpb.GetAncestryRequest{
AncestryName: name,
})
if err != nil {
return nil, err
}
if resp == nil {
return nil, errors.New("ancestry response was nil")
}
if resp.GetStatus() != nil {
c.Logf("clair.ancestry.get ClairStatus=%#v", *resp.GetStatus())
}
return resp.GetAncestry(), nil
} | [
"func",
"(",
"c",
"*",
"Clair",
")",
"GetAncestry",
"(",
"ctx",
"context",
".",
"Context",
",",
"name",
"string",
")",
"(",
"*",
"clairpb",
".",
"GetAncestryResponse_Ancestry",
",",
"error",
")",
"{",
"c",
".",
"Logf",
"(",
"\"clair.ancestry.get name=%s\"",
... | // GetAncestry displays an ancestry and all of its features and vulnerabilities. | [
"GetAncestry",
"displays",
"an",
"ancestry",
"and",
"all",
"of",
"its",
"features",
"and",
"vulnerabilities",
"."
] | d959057b30da67d5f162790f9d5b5160686901fd | https://github.com/genuinetools/reg/blob/d959057b30da67d5f162790f9d5b5160686901fd/clair/ancestry.go#L16-L41 | train |
genuinetools/reg | clair/ancestry.go | PostAncestry | func (c *Clair) PostAncestry(ctx context.Context, name string, layers []*clairpb.PostAncestryRequest_PostLayer) error {
c.Logf("clair.ancestry.post name=%s", name)
if c.grpcConn == nil {
return ErrNilGRPCConn
}
client := clairpb.NewAncestryServiceClient(c.grpcConn)
resp, err := client.PostAncestry(ctx, &clairpb.PostAncestryRequest{
AncestryName: name,
Layers: layers,
Format: "Docker",
})
if err != nil {
return err
}
if resp == nil {
return errors.New("ancestry response was nil")
}
if resp.GetStatus() != nil {
c.Logf("clair.ancestry.post ClairStatus=%#v", *resp.GetStatus())
}
return nil
} | go | func (c *Clair) PostAncestry(ctx context.Context, name string, layers []*clairpb.PostAncestryRequest_PostLayer) error {
c.Logf("clair.ancestry.post name=%s", name)
if c.grpcConn == nil {
return ErrNilGRPCConn
}
client := clairpb.NewAncestryServiceClient(c.grpcConn)
resp, err := client.PostAncestry(ctx, &clairpb.PostAncestryRequest{
AncestryName: name,
Layers: layers,
Format: "Docker",
})
if err != nil {
return err
}
if resp == nil {
return errors.New("ancestry response was nil")
}
if resp.GetStatus() != nil {
c.Logf("clair.ancestry.post ClairStatus=%#v", *resp.GetStatus())
}
return nil
} | [
"func",
"(",
"c",
"*",
"Clair",
")",
"PostAncestry",
"(",
"ctx",
"context",
".",
"Context",
",",
"name",
"string",
",",
"layers",
"[",
"]",
"*",
"clairpb",
".",
"PostAncestryRequest_PostLayer",
")",
"error",
"{",
"c",
".",
"Logf",
"(",
"\"clair.ancestry.po... | // PostAncestry performs the analysis of all layers from the provided path. | [
"PostAncestry",
"performs",
"the",
"analysis",
"of",
"all",
"layers",
"from",
"the",
"provided",
"path",
"."
] | d959057b30da67d5f162790f9d5b5160686901fd | https://github.com/genuinetools/reg/blob/d959057b30da67d5f162790f9d5b5160686901fd/clair/ancestry.go#L44-L71 | train |
genuinetools/reg | registry/manifest.go | ManifestList | func (r *Registry) ManifestList(ctx context.Context, repository, ref string) (manifestlist.ManifestList, error) {
uri := r.url("/v2/%s/manifests/%s", repository, ref)
r.Logf("registry.manifests uri=%s repository=%s ref=%s", uri, repository, ref)
var m manifestlist.ManifestList
if _, err := r.getJSON(ctx, uri, &m); err != nil {
r.Logf("registry.manifests response=%v", m)
return m, err
}
return m, nil
} | go | func (r *Registry) ManifestList(ctx context.Context, repository, ref string) (manifestlist.ManifestList, error) {
uri := r.url("/v2/%s/manifests/%s", repository, ref)
r.Logf("registry.manifests uri=%s repository=%s ref=%s", uri, repository, ref)
var m manifestlist.ManifestList
if _, err := r.getJSON(ctx, uri, &m); err != nil {
r.Logf("registry.manifests response=%v", m)
return m, err
}
return m, nil
} | [
"func",
"(",
"r",
"*",
"Registry",
")",
"ManifestList",
"(",
"ctx",
"context",
".",
"Context",
",",
"repository",
",",
"ref",
"string",
")",
"(",
"manifestlist",
".",
"ManifestList",
",",
"error",
")",
"{",
"uri",
":=",
"r",
".",
"url",
"(",
"\"/v2/%s/... | // ManifestList gets the registry v2 manifest list. | [
"ManifestList",
"gets",
"the",
"registry",
"v2",
"manifest",
"list",
"."
] | d959057b30da67d5f162790f9d5b5160686901fd | https://github.com/genuinetools/reg/blob/d959057b30da67d5f162790f9d5b5160686901fd/registry/manifest.go#L56-L67 | train |
genuinetools/reg | registry/manifest.go | ManifestV2 | func (r *Registry) ManifestV2(ctx context.Context, repository, ref string) (schema2.Manifest, error) {
uri := r.url("/v2/%s/manifests/%s", repository, ref)
r.Logf("registry.manifests uri=%s repository=%s ref=%s", uri, repository, ref)
var m schema2.Manifest
if _, err := r.getJSON(ctx, uri, &m); err != nil {
r.Logf("registry.manifests response=%v", m)
return m, err
}
if m.Versioned.SchemaVersion != 2 {
return m, ErrUnexpectedSchemaVersion
}
return m, nil
} | go | func (r *Registry) ManifestV2(ctx context.Context, repository, ref string) (schema2.Manifest, error) {
uri := r.url("/v2/%s/manifests/%s", repository, ref)
r.Logf("registry.manifests uri=%s repository=%s ref=%s", uri, repository, ref)
var m schema2.Manifest
if _, err := r.getJSON(ctx, uri, &m); err != nil {
r.Logf("registry.manifests response=%v", m)
return m, err
}
if m.Versioned.SchemaVersion != 2 {
return m, ErrUnexpectedSchemaVersion
}
return m, nil
} | [
"func",
"(",
"r",
"*",
"Registry",
")",
"ManifestV2",
"(",
"ctx",
"context",
".",
"Context",
",",
"repository",
",",
"ref",
"string",
")",
"(",
"schema2",
".",
"Manifest",
",",
"error",
")",
"{",
"uri",
":=",
"r",
".",
"url",
"(",
"\"/v2/%s/manifests/%... | // ManifestV2 gets the registry v2 manifest. | [
"ManifestV2",
"gets",
"the",
"registry",
"v2",
"manifest",
"."
] | d959057b30da67d5f162790f9d5b5160686901fd | https://github.com/genuinetools/reg/blob/d959057b30da67d5f162790f9d5b5160686901fd/registry/manifest.go#L70-L85 | train |
genuinetools/reg | registry/manifest.go | ManifestV1 | func (r *Registry) ManifestV1(ctx context.Context, repository, ref string) (schema1.SignedManifest, error) {
uri := r.url("/v2/%s/manifests/%s", repository, ref)
r.Logf("registry.manifests uri=%s repository=%s ref=%s", uri, repository, ref)
var m schema1.SignedManifest
if _, err := r.getJSON(ctx, uri, &m); err != nil {
r.Logf("registry.manifests response=%v", m)
return m, err
}
if m.Versioned.SchemaVersion != 1 {
return m, ErrUnexpectedSchemaVersion
}
return m, nil
} | go | func (r *Registry) ManifestV1(ctx context.Context, repository, ref string) (schema1.SignedManifest, error) {
uri := r.url("/v2/%s/manifests/%s", repository, ref)
r.Logf("registry.manifests uri=%s repository=%s ref=%s", uri, repository, ref)
var m schema1.SignedManifest
if _, err := r.getJSON(ctx, uri, &m); err != nil {
r.Logf("registry.manifests response=%v", m)
return m, err
}
if m.Versioned.SchemaVersion != 1 {
return m, ErrUnexpectedSchemaVersion
}
return m, nil
} | [
"func",
"(",
"r",
"*",
"Registry",
")",
"ManifestV1",
"(",
"ctx",
"context",
".",
"Context",
",",
"repository",
",",
"ref",
"string",
")",
"(",
"schema1",
".",
"SignedManifest",
",",
"error",
")",
"{",
"uri",
":=",
"r",
".",
"url",
"(",
"\"/v2/%s/manif... | // ManifestV1 gets the registry v1 manifest. | [
"ManifestV1",
"gets",
"the",
"registry",
"v1",
"manifest",
"."
] | d959057b30da67d5f162790f9d5b5160686901fd | https://github.com/genuinetools/reg/blob/d959057b30da67d5f162790f9d5b5160686901fd/registry/manifest.go#L88-L103 | train |
genuinetools/reg | registry/manifest.go | PutManifest | func (r *Registry) PutManifest(ctx context.Context, repository, ref string, manifest distribution.Manifest) error {
url := r.url("/v2/%s/manifests/%s", repository, ref)
r.Logf("registry.manifest.put url=%s repository=%s reference=%s", url, repository, ref)
b, err := json.Marshal(manifest)
if err != nil {
return err
}
req, err := http.NewRequest("PUT", url, bytes.NewBuffer(b))
if err != nil {
return err
}
req.Header.Set("Content-Type", schema2.MediaTypeManifest)
resp, err := r.Client.Do(req.WithContext(ctx))
if resp != nil {
defer resp.Body.Close()
}
return err
} | go | func (r *Registry) PutManifest(ctx context.Context, repository, ref string, manifest distribution.Manifest) error {
url := r.url("/v2/%s/manifests/%s", repository, ref)
r.Logf("registry.manifest.put url=%s repository=%s reference=%s", url, repository, ref)
b, err := json.Marshal(manifest)
if err != nil {
return err
}
req, err := http.NewRequest("PUT", url, bytes.NewBuffer(b))
if err != nil {
return err
}
req.Header.Set("Content-Type", schema2.MediaTypeManifest)
resp, err := r.Client.Do(req.WithContext(ctx))
if resp != nil {
defer resp.Body.Close()
}
return err
} | [
"func",
"(",
"r",
"*",
"Registry",
")",
"PutManifest",
"(",
"ctx",
"context",
".",
"Context",
",",
"repository",
",",
"ref",
"string",
",",
"manifest",
"distribution",
".",
"Manifest",
")",
"error",
"{",
"url",
":=",
"r",
".",
"url",
"(",
"\"/v2/%s/manif... | // PutManifest calls a PUT for the specific manifest for an image. | [
"PutManifest",
"calls",
"a",
"PUT",
"for",
"the",
"specific",
"manifest",
"for",
"an",
"image",
"."
] | d959057b30da67d5f162790f9d5b5160686901fd | https://github.com/genuinetools/reg/blob/d959057b30da67d5f162790f9d5b5160686901fd/registry/manifest.go#L106-L126 | train |
genuinetools/reg | clair/clair.go | New | func New(url string, opt Opt) (*Clair, error) {
transport := http.DefaultTransport
grpcOpt := []grpc.DialOption{}
if opt.Insecure {
transport = &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}
grpcOpt = append(grpcOpt, grpc.WithInsecure())
}
errorTransport := &ErrorTransport{
Transport: transport,
}
// set the logging
logf := Quiet
if opt.Debug {
logf = Log
}
conn, err := grpc.Dial(url, grpcOpt...)
if err != nil {
logf("grpc dial %s failed: %v", url, err)
}
registry := &Clair{
URL: url,
Client: &http.Client{
Timeout: opt.Timeout,
Transport: errorTransport,
},
Logf: logf,
grpcConn: conn,
}
return registry, nil
} | go | func New(url string, opt Opt) (*Clair, error) {
transport := http.DefaultTransport
grpcOpt := []grpc.DialOption{}
if opt.Insecure {
transport = &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}
grpcOpt = append(grpcOpt, grpc.WithInsecure())
}
errorTransport := &ErrorTransport{
Transport: transport,
}
// set the logging
logf := Quiet
if opt.Debug {
logf = Log
}
conn, err := grpc.Dial(url, grpcOpt...)
if err != nil {
logf("grpc dial %s failed: %v", url, err)
}
registry := &Clair{
URL: url,
Client: &http.Client{
Timeout: opt.Timeout,
Transport: errorTransport,
},
Logf: logf,
grpcConn: conn,
}
return registry, nil
} | [
"func",
"New",
"(",
"url",
"string",
",",
"opt",
"Opt",
")",
"(",
"*",
"Clair",
",",
"error",
")",
"{",
"transport",
":=",
"http",
".",
"DefaultTransport",
"\n",
"grpcOpt",
":=",
"[",
"]",
"grpc",
".",
"DialOption",
"{",
"}",
"\n",
"if",
"opt",
"."... | // New creates a new Clair struct with the given URL and credentials. | [
"New",
"creates",
"a",
"new",
"Clair",
"struct",
"with",
"the",
"given",
"URL",
"and",
"credentials",
"."
] | d959057b30da67d5f162790f9d5b5160686901fd | https://github.com/genuinetools/reg/blob/d959057b30da67d5f162790f9d5b5160686901fd/clair/clair.go#L42-L83 | train |
genuinetools/reg | clair/clair.go | url | func (c *Clair) url(pathTemplate string, args ...interface{}) string {
pathSuffix := fmt.Sprintf(pathTemplate, args...)
url := fmt.Sprintf("%s%s", c.URL, pathSuffix)
return url
} | go | func (c *Clair) url(pathTemplate string, args ...interface{}) string {
pathSuffix := fmt.Sprintf(pathTemplate, args...)
url := fmt.Sprintf("%s%s", c.URL, pathSuffix)
return url
} | [
"func",
"(",
"c",
"*",
"Clair",
")",
"url",
"(",
"pathTemplate",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"string",
"{",
"pathSuffix",
":=",
"fmt",
".",
"Sprintf",
"(",
"pathTemplate",
",",
"args",
"...",
")",
"\n",
"url",
":=",
"fmt... | // url returns a clair URL with the passed arguments concatenated. | [
"url",
"returns",
"a",
"clair",
"URL",
"with",
"the",
"passed",
"arguments",
"concatenated",
"."
] | d959057b30da67d5f162790f9d5b5160686901fd | https://github.com/genuinetools/reg/blob/d959057b30da67d5f162790f9d5b5160686901fd/clair/clair.go#L91-L95 | train |
genuinetools/reg | registry/basictransport.go | RoundTrip | func (t *BasicTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if strings.HasPrefix(req.URL.String(), t.URL) && req.Header.Get("Authorization") == "" {
if t.Username != "" || t.Password != "" {
req.SetBasicAuth(t.Username, t.Password)
}
}
resp, err := t.Transport.RoundTrip(req)
return resp, err
} | go | func (t *BasicTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if strings.HasPrefix(req.URL.String(), t.URL) && req.Header.Get("Authorization") == "" {
if t.Username != "" || t.Password != "" {
req.SetBasicAuth(t.Username, t.Password)
}
}
resp, err := t.Transport.RoundTrip(req)
return resp, err
} | [
"func",
"(",
"t",
"*",
"BasicTransport",
")",
"RoundTrip",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"req",
".",
"URL",
".",
"String",
"(",
")",
... | // RoundTrip defines the round tripper for basic auth transport. | [
"RoundTrip",
"defines",
"the",
"round",
"tripper",
"for",
"basic",
"auth",
"transport",
"."
] | d959057b30da67d5f162790f9d5b5160686901fd | https://github.com/genuinetools/reg/blob/d959057b30da67d5f162790f9d5b5160686901fd/registry/basictransport.go#L17-L25 | train |
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",
":=",
"r... | // 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",
"g... | 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",
"_"... | // 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",
"... | 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",
"{",
... | // 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",
"{",
"ret... | // 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",
"... | 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",
"_",
",",... | // 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",
... | // 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",
"mu... | 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",
"{",
... | // 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",
":=",
"\"VALUE %s %d %d %d\\r\\n\"",
"\n",
"\\r",
"\n",
"\\n",
"\n",
"dest",
":=",
"[",
"]",
"inter... | // 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",... | 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",
"... | // 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",
",",
"resultDele... | // 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",
... | // 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",
"ret... | // 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",
"(",
... | // 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",... | // 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",
"parts",
":=",
"[",
"5",
"]",
"uint32",
"{",
"uint32",
"(",
"src",
"... | // 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",
... | 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",
"fastEncodeBa... | // 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",
"al... | 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",
"_",
"=",
"src",
"[",
"26",
"]",
"\n",
"parts",
":=",
"[",
... | // 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",
... | 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",
... | // 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",
"if",
"avail",
":=",
"c",
"-",
"n",
";",
"avail",
"<",
"nby... | // 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",
... | // 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",
"src",
":=",
"[",
"stringEncodedLength",
"]",
"byte",
"... | // 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",
"(",
"\"Couldn't generate KSUID, inconceivable! error: %v\"",
",",
"err",
")",
")",
"\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",
"}",
"... | // 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",
"if",
"len",
"(",
"b",
")",
"!=",
"byteLength",
"{",
"return",
"Nil",
",",
"errSize",
"\n",
"}",
"\n",
"copy",
"(",
"ksuid"... | // 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",... | 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",... | // 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",
"t",
":=",
"id",
".",
"Timestamp",
"(",
")",
"\n",
"u",
":=",
"uint128Payload",
"(",
"id",
")",
"\n",
"v",
":=",
"add12... | // 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",
"t",
":=",
"id",
".",
"Timestamp",
"(",
")",
"\n",
"u",
":=",
"uint128Payload",
"(... | // 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",
"\n",
"count",
":=",
"seq",
".",
"count",
"\n",
"if",
"count",
">",
"math",
".",
"MaxUint16",
"{",
"return",
"Nil",
... | // 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",
... | // 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",
"va... | 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",
"bs",
":=... | // 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... | // 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",
")... | // 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... | // 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",
"."... | 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",
"net",
",",
"err",
":=",
... | // 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... | 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",
"for",
"_",
",",
"client",
":=",
"range",
... | // 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",
"{",
... | // 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",
"(",
"&"... | // 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",
"(",
"\"Enter existing wallet seed: \"",
")",
"\n",
"seedStr... | // 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",
":=",
"\"Enter the private passphrase of your wallet: \"",
"\n",
"for",
"{",
"fmt",
".",
"Print",
"(",
"prompt",
")",
"\n",
"pass",
",",
"err",
":=",
"termina... | // 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",
")",
"{",
"validStrings",
":=",
"strings",
".",
"Join",
... | // 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",
"... | 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",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s: \"",
",",
"prefix",
")",
"\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... | 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",
")",
"{",
"if",
"legacyKeyStore",
"==",
"nil",
"{",
"return",
"promptPass",
"(",
"reader",
... | // 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"... | 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",
":=",
"defaultP... | // 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"... | 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",
")",
"{",
"useUserSeed",
",",
"err",
":=",
"promptListBool",
"(",
"reader",
",",
"\"Do you have an \"",
"+",
"\"existing wallet seed you want to use?\"",
",",... | // 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... | 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",
"_",
",",
"err",
":=",
"ns",
".",
"CreateBucketIfNotExists",
"(",
"usedAddrBucketName",
")",
"\n",
"if",
... | // 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",
... | 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",
"{",
"err",
":=",
"ns",
".",
"NestedReadBucket",
"(",
"addrBucketName",
")",
".",
"ForEach",
"(",
"func",
"(",
"k",
"[",
"]",
"byte",
",",
"v",
"[",
"]",
"byte",
... | // 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... | 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",
"{",
"bucketToMigrate",
":=",
"src",
".",
"NestedReadWriteBucket",
"(",
"bucketKey",
")",
"\n",
"newBucket",
",",
"err",... | // 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"... | // 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",
"t... | 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",
".",
... | // 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",... | 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",
"!=",
... | // 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",
"... | // 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",
... | // 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",
"(",
"... | // 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",
".",
"accountCli... | // 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",
"dis... | 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",
"drivers",
"[",
"driver",
".",
"DbTy... | // 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",
",",
"ErrDbUnkno... | // 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",
... | 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",
"{",
"subsystems",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"subsystemLoggers",
")",
")",
"\n",
"for",
"subsysID",
":=",
"range",
"subsystemLoggers",
"{",
"subsystems",
... | // 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",
":",... | // 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"... | // 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",
"}",
"\... | // 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",
")",
"{",
"block",
",",
"err",
":=",
"s",
".",
"CS",
".",
"GetBlock",
"(",
"*",
"hash",
")... | // 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",
... | 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",
"!=",
"... | // 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",
"unknow... | 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",
")",
... | // 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"... | // 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",
")",
"{",
"watchListSize",
":=",
"len",
"(",
"req",
".",
"ExternalAddrs",
")",
"+",
"len",
"(",
"req",
".",
"InternalAddrs",
... | // 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",... | 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",
"coun... | // 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",
... | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/neutrino.go#L295-L318 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.