id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
149,500
ncabatoff/process-exporter
proc/read.go
GetStatic
func (p *proccache) GetStatic() (Static, error) { // /proc/<pid>/cmdline is normally world-readable. cmdline, err := p.getCmdLine() if err != nil { return Static{}, err } // /proc/<pid>/stat is normally world-readable. stat, err := p.getStat() if err != nil { return Static{}, err } startTime := time.Unix(int64(p.fs.BootTime), 0).UTC() startTime = startTime.Add(time.Second / userHZ * time.Duration(stat.Starttime)) // /proc/<pid>/status is normally world-readable. status, err := p.getStatus() if err != nil { return Static{}, err } return Static{ Name: stat.Comm, Cmdline: cmdline, ParentPid: stat.PPID, StartTime: startTime, EffectiveUID: status.UIDEffective, }, nil }
go
func (p *proccache) GetStatic() (Static, error) { // /proc/<pid>/cmdline is normally world-readable. cmdline, err := p.getCmdLine() if err != nil { return Static{}, err } // /proc/<pid>/stat is normally world-readable. stat, err := p.getStat() if err != nil { return Static{}, err } startTime := time.Unix(int64(p.fs.BootTime), 0).UTC() startTime = startTime.Add(time.Second / userHZ * time.Duration(stat.Starttime)) // /proc/<pid>/status is normally world-readable. status, err := p.getStatus() if err != nil { return Static{}, err } return Static{ Name: stat.Comm, Cmdline: cmdline, ParentPid: stat.PPID, StartTime: startTime, EffectiveUID: status.UIDEffective, }, nil }
[ "func", "(", "p", "*", "proccache", ")", "GetStatic", "(", ")", "(", "Static", ",", "error", ")", "{", "// /proc/<pid>/cmdline is normally world-readable.", "cmdline", ",", "err", ":=", "p", ".", "getCmdLine", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Static", "{", "}", ",", "err", "\n", "}", "\n\n", "// /proc/<pid>/stat is normally world-readable.", "stat", ",", "err", ":=", "p", ".", "getStat", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Static", "{", "}", ",", "err", "\n", "}", "\n", "startTime", ":=", "time", ".", "Unix", "(", "int64", "(", "p", ".", "fs", ".", "BootTime", ")", ",", "0", ")", ".", "UTC", "(", ")", "\n", "startTime", "=", "startTime", ".", "Add", "(", "time", ".", "Second", "/", "userHZ", "*", "time", ".", "Duration", "(", "stat", ".", "Starttime", ")", ")", "\n\n", "// /proc/<pid>/status is normally world-readable.", "status", ",", "err", ":=", "p", ".", "getStatus", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Static", "{", "}", ",", "err", "\n", "}", "\n\n", "return", "Static", "{", "Name", ":", "stat", ".", "Comm", ",", "Cmdline", ":", "cmdline", ",", "ParentPid", ":", "stat", ".", "PPID", ",", "StartTime", ":", "startTime", ",", "EffectiveUID", ":", "status", ".", "UIDEffective", ",", "}", ",", "nil", "\n", "}" ]
// GetStatic returns the ProcStatic corresponding to this proc.
[ "GetStatic", "returns", "the", "ProcStatic", "corresponding", "to", "this", "proc", "." ]
0f1987d2db4f6fccdec912784031c966b066765d
https://github.com/ncabatoff/process-exporter/blob/0f1987d2db4f6fccdec912784031c966b066765d/proc/read.go#L346-L374
149,501
ncabatoff/process-exporter
proc/read.go
GetMetrics
func (p proc) GetMetrics() (Metrics, int, error) { counts, softerrors, err := p.GetCounts() if err != nil { return Metrics{}, 0, err } // We don't need to check for error here because p will have cached // the successful result of calling getStat in GetCounts. // Since GetMetrics isn't a pointer receiver method, our callers // won't see the effect of the caching between calls. stat, _ := p.getStat() // Ditto for states states, _ := p.GetStates() // Ditto for status status, _ := p.getStatus() numfds, err := p.Proc.FileDescriptorsLen() if err != nil { numfds = -1 softerrors |= 1 } limits, err := p.Proc.NewLimits() if err != nil { return Metrics{}, 0, err } wchan, err := p.getWchan() if err != nil { softerrors |= 1 } return Metrics{ Counts: counts, Memory: Memory{ ResidentBytes: uint64(stat.ResidentMemory()), VirtualBytes: uint64(stat.VirtualMemory()), VmSwapBytes: uint64(status.VmSwapKB * 1024), }, Filedesc: Filedesc{ Open: int64(numfds), Limit: uint64(limits.OpenFiles), }, NumThreads: uint64(stat.NumThreads), States: states, Wchan: wchan, }, softerrors, nil }
go
func (p proc) GetMetrics() (Metrics, int, error) { counts, softerrors, err := p.GetCounts() if err != nil { return Metrics{}, 0, err } // We don't need to check for error here because p will have cached // the successful result of calling getStat in GetCounts. // Since GetMetrics isn't a pointer receiver method, our callers // won't see the effect of the caching between calls. stat, _ := p.getStat() // Ditto for states states, _ := p.GetStates() // Ditto for status status, _ := p.getStatus() numfds, err := p.Proc.FileDescriptorsLen() if err != nil { numfds = -1 softerrors |= 1 } limits, err := p.Proc.NewLimits() if err != nil { return Metrics{}, 0, err } wchan, err := p.getWchan() if err != nil { softerrors |= 1 } return Metrics{ Counts: counts, Memory: Memory{ ResidentBytes: uint64(stat.ResidentMemory()), VirtualBytes: uint64(stat.VirtualMemory()), VmSwapBytes: uint64(status.VmSwapKB * 1024), }, Filedesc: Filedesc{ Open: int64(numfds), Limit: uint64(limits.OpenFiles), }, NumThreads: uint64(stat.NumThreads), States: states, Wchan: wchan, }, softerrors, nil }
[ "func", "(", "p", "proc", ")", "GetMetrics", "(", ")", "(", "Metrics", ",", "int", ",", "error", ")", "{", "counts", ",", "softerrors", ",", "err", ":=", "p", ".", "GetCounts", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Metrics", "{", "}", ",", "0", ",", "err", "\n", "}", "\n\n", "// We don't need to check for error here because p will have cached", "// the successful result of calling getStat in GetCounts.", "// Since GetMetrics isn't a pointer receiver method, our callers", "// won't see the effect of the caching between calls.", "stat", ",", "_", ":=", "p", ".", "getStat", "(", ")", "\n\n", "// Ditto for states", "states", ",", "_", ":=", "p", ".", "GetStates", "(", ")", "\n\n", "// Ditto for status", "status", ",", "_", ":=", "p", ".", "getStatus", "(", ")", "\n\n", "numfds", ",", "err", ":=", "p", ".", "Proc", ".", "FileDescriptorsLen", "(", ")", "\n", "if", "err", "!=", "nil", "{", "numfds", "=", "-", "1", "\n", "softerrors", "|=", "1", "\n", "}", "\n\n", "limits", ",", "err", ":=", "p", ".", "Proc", ".", "NewLimits", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Metrics", "{", "}", ",", "0", ",", "err", "\n", "}", "\n\n", "wchan", ",", "err", ":=", "p", ".", "getWchan", "(", ")", "\n", "if", "err", "!=", "nil", "{", "softerrors", "|=", "1", "\n", "}", "\n\n", "return", "Metrics", "{", "Counts", ":", "counts", ",", "Memory", ":", "Memory", "{", "ResidentBytes", ":", "uint64", "(", "stat", ".", "ResidentMemory", "(", ")", ")", ",", "VirtualBytes", ":", "uint64", "(", "stat", ".", "VirtualMemory", "(", ")", ")", ",", "VmSwapBytes", ":", "uint64", "(", "status", ".", "VmSwapKB", "*", "1024", ")", ",", "}", ",", "Filedesc", ":", "Filedesc", "{", "Open", ":", "int64", "(", "numfds", ")", ",", "Limit", ":", "uint64", "(", "limits", ".", "OpenFiles", ")", ",", "}", ",", "NumThreads", ":", "uint64", "(", "stat", ".", "NumThreads", ")", ",", "States", ":", "states", ",", "Wchan", ":", "wchan", ",", "}", ",", "softerrors", ",", "nil", "\n", "}" ]
// GetMetrics returns the current metrics for the proc. The results are // not cached.
[ "GetMetrics", "returns", "the", "current", "metrics", "for", "the", "proc", ".", "The", "results", "are", "not", "cached", "." ]
0f1987d2db4f6fccdec912784031c966b066765d
https://github.com/ncabatoff/process-exporter/blob/0f1987d2db4f6fccdec912784031c966b066765d/proc/read.go#L438-L487
149,502
ncabatoff/process-exporter
proc/read.go
AllProcs
func (fs *FS) AllProcs() Iter { procs, err := fs.FS.AllProcs() if err != nil { err = fmt.Errorf("Error reading procs: %v", err) } return &procIterator{procs: procfsprocs{procs, fs}, err: err, idx: -1} }
go
func (fs *FS) AllProcs() Iter { procs, err := fs.FS.AllProcs() if err != nil { err = fmt.Errorf("Error reading procs: %v", err) } return &procIterator{procs: procfsprocs{procs, fs}, err: err, idx: -1} }
[ "func", "(", "fs", "*", "FS", ")", "AllProcs", "(", ")", "Iter", "{", "procs", ",", "err", ":=", "fs", ".", "FS", ".", "AllProcs", "(", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "&", "procIterator", "{", "procs", ":", "procfsprocs", "{", "procs", ",", "fs", "}", ",", "err", ":", "err", ",", "idx", ":", "-", "1", "}", "\n", "}" ]
// AllProcs implements Source.
[ "AllProcs", "implements", "Source", "." ]
0f1987d2db4f6fccdec912784031c966b066765d
https://github.com/ncabatoff/process-exporter/blob/0f1987d2db4f6fccdec912784031c966b066765d/proc/read.go#L565-L571
149,503
ncabatoff/process-exporter
proc/read.go
get
func (p procfsprocs) get(i int) Proc { return &proc{proccache{Proc: p.Procs[i], fs: p.fs}} }
go
func (p procfsprocs) get(i int) Proc { return &proc{proccache{Proc: p.Procs[i], fs: p.fs}} }
[ "func", "(", "p", "procfsprocs", ")", "get", "(", "i", "int", ")", "Proc", "{", "return", "&", "proc", "{", "proccache", "{", "Proc", ":", "p", ".", "Procs", "[", "i", "]", ",", "fs", ":", "p", ".", "fs", "}", "}", "\n", "}" ]
// get implements procs.
[ "get", "implements", "procs", "." ]
0f1987d2db4f6fccdec912784031c966b066765d
https://github.com/ncabatoff/process-exporter/blob/0f1987d2db4f6fccdec912784031c966b066765d/proc/read.go#L574-L576
149,504
ncabatoff/process-exporter
proc/read.go
Next
func (pi *procIterator) Next() bool { pi.idx++ if pi.idx < pi.procs.length() { pi.Proc = pi.procs.get(pi.idx) } else { pi.Proc = nil } return pi.idx < pi.procs.length() }
go
func (pi *procIterator) Next() bool { pi.idx++ if pi.idx < pi.procs.length() { pi.Proc = pi.procs.get(pi.idx) } else { pi.Proc = nil } return pi.idx < pi.procs.length() }
[ "func", "(", "pi", "*", "procIterator", ")", "Next", "(", ")", "bool", "{", "pi", ".", "idx", "++", "\n", "if", "pi", ".", "idx", "<", "pi", ".", "procs", ".", "length", "(", ")", "{", "pi", ".", "Proc", "=", "pi", ".", "procs", ".", "get", "(", "pi", ".", "idx", ")", "\n", "}", "else", "{", "pi", ".", "Proc", "=", "nil", "\n", "}", "\n", "return", "pi", ".", "idx", "<", "pi", ".", "procs", ".", "length", "(", ")", "\n", "}" ]
// Next implements Iter.
[ "Next", "implements", "Iter", "." ]
0f1987d2db4f6fccdec912784031c966b066765d
https://github.com/ncabatoff/process-exporter/blob/0f1987d2db4f6fccdec912784031c966b066765d/proc/read.go#L584-L592
149,505
ncabatoff/process-exporter
proc/read.go
Close
func (pi *procIterator) Close() error { pi.Next() pi.procs = nil pi.Proc = nil return pi.err }
go
func (pi *procIterator) Close() error { pi.Next() pi.procs = nil pi.Proc = nil return pi.err }
[ "func", "(", "pi", "*", "procIterator", ")", "Close", "(", ")", "error", "{", "pi", ".", "Next", "(", ")", "\n", "pi", ".", "procs", "=", "nil", "\n", "pi", ".", "Proc", "=", "nil", "\n", "return", "pi", ".", "err", "\n", "}" ]
// Close implements Iter.
[ "Close", "implements", "Iter", "." ]
0f1987d2db4f6fccdec912784031c966b066765d
https://github.com/ncabatoff/process-exporter/blob/0f1987d2db4f6fccdec912784031c966b066765d/proc/read.go#L595-L600
149,506
ncabatoff/process-exporter
config/config.go
ReadFile
func ReadFile(cfgpath string, debug bool) (*Config, error) { content, err := ioutil.ReadFile(cfgpath) if err != nil { return nil, fmt.Errorf("error reading config file %q: %v", cfgpath, err) } if debug { log.Printf("Config file %q contents:\n%s", cfgpath, content) } return GetConfig(string(content), debug) }
go
func ReadFile(cfgpath string, debug bool) (*Config, error) { content, err := ioutil.ReadFile(cfgpath) if err != nil { return nil, fmt.Errorf("error reading config file %q: %v", cfgpath, err) } if debug { log.Printf("Config file %q contents:\n%s", cfgpath, content) } return GetConfig(string(content), debug) }
[ "func", "ReadFile", "(", "cfgpath", "string", ",", "debug", "bool", ")", "(", "*", "Config", ",", "error", ")", "{", "content", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "cfgpath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "cfgpath", ",", "err", ")", "\n", "}", "\n", "if", "debug", "{", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "cfgpath", ",", "content", ")", "\n", "}", "\n", "return", "GetConfig", "(", "string", "(", "content", ")", ",", "debug", ")", "\n", "}" ]
// ReadRecipesFile opens the named file and extracts recipes from it.
[ "ReadRecipesFile", "opens", "the", "named", "file", "and", "extracts", "recipes", "from", "it", "." ]
0f1987d2db4f6fccdec912784031c966b066765d
https://github.com/ncabatoff/process-exporter/blob/0f1987d2db4f6fccdec912784031c966b066765d/config/config.go#L178-L187
149,507
ncabatoff/process-exporter
config/config.go
GetConfig
func GetConfig(content string, debug bool) (*Config, error) { var yamldata map[string]interface{} err := yaml.Unmarshal([]byte(content), &yamldata) if err != nil { return nil, err } yamlProcnames, ok := yamldata["process_names"] if !ok { return nil, fmt.Errorf("error parsing YAML config: no top-level 'process_names' key") } procnames, ok := yamlProcnames.([]interface{}) if !ok { return nil, fmt.Errorf("error parsing YAML config: 'process_names' is not a list") } var cfg Config for i, procname := range procnames { mn, err := getMatchNamer(procname) if err != nil { return nil, fmt.Errorf("unable to parse process_name entry %d: %v", i, err) } cfg.MatchNamers.matchers = append(cfg.MatchNamers.matchers, mn) } return &cfg, nil }
go
func GetConfig(content string, debug bool) (*Config, error) { var yamldata map[string]interface{} err := yaml.Unmarshal([]byte(content), &yamldata) if err != nil { return nil, err } yamlProcnames, ok := yamldata["process_names"] if !ok { return nil, fmt.Errorf("error parsing YAML config: no top-level 'process_names' key") } procnames, ok := yamlProcnames.([]interface{}) if !ok { return nil, fmt.Errorf("error parsing YAML config: 'process_names' is not a list") } var cfg Config for i, procname := range procnames { mn, err := getMatchNamer(procname) if err != nil { return nil, fmt.Errorf("unable to parse process_name entry %d: %v", i, err) } cfg.MatchNamers.matchers = append(cfg.MatchNamers.matchers, mn) } return &cfg, nil }
[ "func", "GetConfig", "(", "content", "string", ",", "debug", "bool", ")", "(", "*", "Config", ",", "error", ")", "{", "var", "yamldata", "map", "[", "string", "]", "interface", "{", "}", "\n\n", "err", ":=", "yaml", ".", "Unmarshal", "(", "[", "]", "byte", "(", "content", ")", ",", "&", "yamldata", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "yamlProcnames", ",", "ok", ":=", "yamldata", "[", "\"", "\"", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "procnames", ",", "ok", ":=", "yamlProcnames", ".", "(", "[", "]", "interface", "{", "}", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "cfg", "Config", "\n", "for", "i", ",", "procname", ":=", "range", "procnames", "{", "mn", ",", "err", ":=", "getMatchNamer", "(", "procname", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "i", ",", "err", ")", "\n", "}", "\n", "cfg", ".", "MatchNamers", ".", "matchers", "=", "append", "(", "cfg", ".", "MatchNamers", ".", "matchers", ",", "mn", ")", "\n", "}", "\n\n", "return", "&", "cfg", ",", "nil", "\n", "}" ]
// GetConfig extracts Config from content by parsing it as YAML.
[ "GetConfig", "extracts", "Config", "from", "content", "by", "parsing", "it", "as", "YAML", "." ]
0f1987d2db4f6fccdec912784031c966b066765d
https://github.com/ncabatoff/process-exporter/blob/0f1987d2db4f6fccdec912784031c966b066765d/config/config.go#L190-L216
149,508
ncabatoff/process-exporter
cmd/process-exporter/main.go
parseNameMapper
func parseNameMapper(s string) (*nameMapperRegex, error) { mapper := make(map[string]*prefixRegex) if s == "" { return &nameMapperRegex{mapper}, nil } toks := strings.Split(s, ",") if len(toks)%2 == 1 { return nil, fmt.Errorf("bad namemapper: odd number of tokens") } for i, tok := range toks { if tok == "" { return nil, fmt.Errorf("bad namemapper: token %d is empty", i) } if i%2 == 1 { name, regexstr := toks[i-1], tok matchName := name prefix := name + ":" if r, err := regexp.Compile(regexstr); err != nil { return nil, fmt.Errorf("error compiling regexp '%s': %v", regexstr, err) } else { mapper[matchName] = &prefixRegex{prefix: prefix, regex: r} } } } return &nameMapperRegex{mapper}, nil }
go
func parseNameMapper(s string) (*nameMapperRegex, error) { mapper := make(map[string]*prefixRegex) if s == "" { return &nameMapperRegex{mapper}, nil } toks := strings.Split(s, ",") if len(toks)%2 == 1 { return nil, fmt.Errorf("bad namemapper: odd number of tokens") } for i, tok := range toks { if tok == "" { return nil, fmt.Errorf("bad namemapper: token %d is empty", i) } if i%2 == 1 { name, regexstr := toks[i-1], tok matchName := name prefix := name + ":" if r, err := regexp.Compile(regexstr); err != nil { return nil, fmt.Errorf("error compiling regexp '%s': %v", regexstr, err) } else { mapper[matchName] = &prefixRegex{prefix: prefix, regex: r} } } } return &nameMapperRegex{mapper}, nil }
[ "func", "parseNameMapper", "(", "s", "string", ")", "(", "*", "nameMapperRegex", ",", "error", ")", "{", "mapper", ":=", "make", "(", "map", "[", "string", "]", "*", "prefixRegex", ")", "\n", "if", "s", "==", "\"", "\"", "{", "return", "&", "nameMapperRegex", "{", "mapper", "}", ",", "nil", "\n", "}", "\n\n", "toks", ":=", "strings", ".", "Split", "(", "s", ",", "\"", "\"", ")", "\n", "if", "len", "(", "toks", ")", "%", "2", "==", "1", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "for", "i", ",", "tok", ":=", "range", "toks", "{", "if", "tok", "==", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "i", ")", "\n", "}", "\n", "if", "i", "%", "2", "==", "1", "{", "name", ",", "regexstr", ":=", "toks", "[", "i", "-", "1", "]", ",", "tok", "\n", "matchName", ":=", "name", "\n", "prefix", ":=", "name", "+", "\"", "\"", "\n\n", "if", "r", ",", "err", ":=", "regexp", ".", "Compile", "(", "regexstr", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "regexstr", ",", "err", ")", "\n", "}", "else", "{", "mapper", "[", "matchName", "]", "=", "&", "prefixRegex", "{", "prefix", ":", "prefix", ",", "regex", ":", "r", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "&", "nameMapperRegex", "{", "mapper", "}", ",", "nil", "\n", "}" ]
// Create a nameMapperRegex based on a string given as the -namemapper argument.
[ "Create", "a", "nameMapperRegex", "based", "on", "a", "string", "given", "as", "the", "-", "namemapper", "argument", "." ]
0f1987d2db4f6fccdec912784031c966b066765d
https://github.com/ncabatoff/process-exporter/blob/0f1987d2db4f6fccdec912784031c966b066765d/cmd/process-exporter/main.go#L229-L258
149,509
ncabatoff/process-exporter
cmd/process-exporter/main.go
Describe
func (p *NamedProcessCollector) Describe(ch chan<- *prometheus.Desc) { ch <- cpuSecsDesc ch <- numprocsDesc ch <- readBytesDesc ch <- writeBytesDesc ch <- membytesDesc ch <- openFDsDesc ch <- worstFDRatioDesc ch <- startTimeDesc ch <- majorPageFaultsDesc ch <- minorPageFaultsDesc ch <- contextSwitchesDesc ch <- numThreadsDesc ch <- statesDesc ch <- scrapeErrorsDesc ch <- scrapeProcReadErrorsDesc ch <- scrapePartialErrorsDesc ch <- threadWchanDesc ch <- threadCountDesc ch <- threadCpuSecsDesc ch <- threadIoBytesDesc ch <- threadMajorPageFaultsDesc ch <- threadMinorPageFaultsDesc ch <- threadContextSwitchesDesc }
go
func (p *NamedProcessCollector) Describe(ch chan<- *prometheus.Desc) { ch <- cpuSecsDesc ch <- numprocsDesc ch <- readBytesDesc ch <- writeBytesDesc ch <- membytesDesc ch <- openFDsDesc ch <- worstFDRatioDesc ch <- startTimeDesc ch <- majorPageFaultsDesc ch <- minorPageFaultsDesc ch <- contextSwitchesDesc ch <- numThreadsDesc ch <- statesDesc ch <- scrapeErrorsDesc ch <- scrapeProcReadErrorsDesc ch <- scrapePartialErrorsDesc ch <- threadWchanDesc ch <- threadCountDesc ch <- threadCpuSecsDesc ch <- threadIoBytesDesc ch <- threadMajorPageFaultsDesc ch <- threadMinorPageFaultsDesc ch <- threadContextSwitchesDesc }
[ "func", "(", "p", "*", "NamedProcessCollector", ")", "Describe", "(", "ch", "chan", "<-", "*", "prometheus", ".", "Desc", ")", "{", "ch", "<-", "cpuSecsDesc", "\n", "ch", "<-", "numprocsDesc", "\n", "ch", "<-", "readBytesDesc", "\n", "ch", "<-", "writeBytesDesc", "\n", "ch", "<-", "membytesDesc", "\n", "ch", "<-", "openFDsDesc", "\n", "ch", "<-", "worstFDRatioDesc", "\n", "ch", "<-", "startTimeDesc", "\n", "ch", "<-", "majorPageFaultsDesc", "\n", "ch", "<-", "minorPageFaultsDesc", "\n", "ch", "<-", "contextSwitchesDesc", "\n", "ch", "<-", "numThreadsDesc", "\n", "ch", "<-", "statesDesc", "\n", "ch", "<-", "scrapeErrorsDesc", "\n", "ch", "<-", "scrapeProcReadErrorsDesc", "\n", "ch", "<-", "scrapePartialErrorsDesc", "\n", "ch", "<-", "threadWchanDesc", "\n", "ch", "<-", "threadCountDesc", "\n", "ch", "<-", "threadCpuSecsDesc", "\n", "ch", "<-", "threadIoBytesDesc", "\n", "ch", "<-", "threadMajorPageFaultsDesc", "\n", "ch", "<-", "threadMinorPageFaultsDesc", "\n", "ch", "<-", "threadContextSwitchesDesc", "\n", "}" ]
// Describe implements prometheus.Collector.
[ "Describe", "implements", "prometheus", ".", "Collector", "." ]
0f1987d2db4f6fccdec912784031c966b066765d
https://github.com/ncabatoff/process-exporter/blob/0f1987d2db4f6fccdec912784031c966b066765d/cmd/process-exporter/main.go#L446-L470
149,510
ncabatoff/process-exporter
cmd/process-exporter/main.go
Collect
func (p *NamedProcessCollector) Collect(ch chan<- prometheus.Metric) { req := scrapeRequest{results: ch, done: make(chan struct{})} p.scrapeChan <- req <-req.done }
go
func (p *NamedProcessCollector) Collect(ch chan<- prometheus.Metric) { req := scrapeRequest{results: ch, done: make(chan struct{})} p.scrapeChan <- req <-req.done }
[ "func", "(", "p", "*", "NamedProcessCollector", ")", "Collect", "(", "ch", "chan", "<-", "prometheus", ".", "Metric", ")", "{", "req", ":=", "scrapeRequest", "{", "results", ":", "ch", ",", "done", ":", "make", "(", "chan", "struct", "{", "}", ")", "}", "\n", "p", ".", "scrapeChan", "<-", "req", "\n", "<-", "req", ".", "done", "\n", "}" ]
// Collect implements prometheus.Collector.
[ "Collect", "implements", "prometheus", ".", "Collector", "." ]
0f1987d2db4f6fccdec912784031c966b066765d
https://github.com/ncabatoff/process-exporter/blob/0f1987d2db4f6fccdec912784031c966b066765d/cmd/process-exporter/main.go#L473-L477
149,511
ncabatoff/process-exporter
proc/grouper.go
NewGrouper
func NewGrouper(namer common.MatchNamer, trackChildren, trackThreads, alwaysRecheck, debug bool) *Grouper { g := Grouper{ groupAccum: make(map[string]Counts), threadAccum: make(map[string]map[string]Threads), tracker: NewTracker(namer, trackChildren, trackThreads, alwaysRecheck, debug), debug: debug, } return &g }
go
func NewGrouper(namer common.MatchNamer, trackChildren, trackThreads, alwaysRecheck, debug bool) *Grouper { g := Grouper{ groupAccum: make(map[string]Counts), threadAccum: make(map[string]map[string]Threads), tracker: NewTracker(namer, trackChildren, trackThreads, alwaysRecheck, debug), debug: debug, } return &g }
[ "func", "NewGrouper", "(", "namer", "common", ".", "MatchNamer", ",", "trackChildren", ",", "trackThreads", ",", "alwaysRecheck", ",", "debug", "bool", ")", "*", "Grouper", "{", "g", ":=", "Grouper", "{", "groupAccum", ":", "make", "(", "map", "[", "string", "]", "Counts", ")", ",", "threadAccum", ":", "make", "(", "map", "[", "string", "]", "map", "[", "string", "]", "Threads", ")", ",", "tracker", ":", "NewTracker", "(", "namer", ",", "trackChildren", ",", "trackThreads", ",", "alwaysRecheck", ",", "debug", ")", ",", "debug", ":", "debug", ",", "}", "\n", "return", "&", "g", "\n", "}" ]
// NewGrouper creates a grouper.
[ "NewGrouper", "creates", "a", "grouper", "." ]
0f1987d2db4f6fccdec912784031c966b066765d
https://github.com/ncabatoff/process-exporter/blob/0f1987d2db4f6fccdec912784031c966b066765d/proc/grouper.go#L52-L60
149,512
ncabatoff/process-exporter
proc/grouper.go
Update
func (g *Grouper) Update(iter Iter) (CollectErrors, GroupByName, error) { cerrs, tracked, err := g.tracker.Update(iter) if err != nil { return cerrs, nil, err } return cerrs, g.groups(tracked), nil }
go
func (g *Grouper) Update(iter Iter) (CollectErrors, GroupByName, error) { cerrs, tracked, err := g.tracker.Update(iter) if err != nil { return cerrs, nil, err } return cerrs, g.groups(tracked), nil }
[ "func", "(", "g", "*", "Grouper", ")", "Update", "(", "iter", "Iter", ")", "(", "CollectErrors", ",", "GroupByName", ",", "error", ")", "{", "cerrs", ",", "tracked", ",", "err", ":=", "g", ".", "tracker", ".", "Update", "(", "iter", ")", "\n", "if", "err", "!=", "nil", "{", "return", "cerrs", ",", "nil", ",", "err", "\n", "}", "\n", "return", "cerrs", ",", "g", ".", "groups", "(", "tracked", ")", ",", "nil", "\n", "}" ]
// Update asks the tracker to report on each tracked process by name. // These are aggregated by groupname, augmented by accumulated counts // from the past, and returned. Note that while the Tracker reports // only what counts have changed since last cycle, Grouper.Update // returns counts that never decrease. Even once the last process // with name X disappears, name X will still appear in the results // with the same counts as before; of course, all non-count metrics // will be zero.
[ "Update", "asks", "the", "tracker", "to", "report", "on", "each", "tracked", "process", "by", "name", ".", "These", "are", "aggregated", "by", "groupname", "augmented", "by", "accumulated", "counts", "from", "the", "past", "and", "returned", ".", "Note", "that", "while", "the", "Tracker", "reports", "only", "what", "counts", "have", "changed", "since", "last", "cycle", "Grouper", ".", "Update", "returns", "counts", "that", "never", "decrease", ".", "Even", "once", "the", "last", "process", "with", "name", "X", "disappears", "name", "X", "will", "still", "appear", "in", "the", "results", "with", "the", "same", "counts", "as", "before", ";", "of", "course", "all", "non", "-", "count", "metrics", "will", "be", "zero", "." ]
0f1987d2db4f6fccdec912784031c966b066765d
https://github.com/ncabatoff/process-exporter/blob/0f1987d2db4f6fccdec912784031c966b066765d/proc/grouper.go#L101-L107
149,513
ncabatoff/process-exporter
proc/grouper.go
groups
func (g *Grouper) groups(tracked []Update) GroupByName { groups := make(GroupByName) threadsByGroup := make(map[string][]ThreadUpdate) for _, update := range tracked { groups[update.GroupName] = groupadd(groups[update.GroupName], update) if update.Threads != nil { threadsByGroup[update.GroupName] = append(threadsByGroup[update.GroupName], update.Threads...) } } // Add any accumulated counts to what was just observed, // and update the accumulators. for gname, group := range groups { if oldcounts, ok := g.groupAccum[gname]; ok { group.Counts.Add(Delta(oldcounts)) } g.groupAccum[gname] = group.Counts group.Threads = g.threads(gname, threadsByGroup[gname]) groups[gname] = group } // Now add any groups that were observed in the past but aren't running now. for gname, gcounts := range g.groupAccum { if _, ok := groups[gname]; !ok { groups[gname] = Group{Counts: gcounts} } } return groups }
go
func (g *Grouper) groups(tracked []Update) GroupByName { groups := make(GroupByName) threadsByGroup := make(map[string][]ThreadUpdate) for _, update := range tracked { groups[update.GroupName] = groupadd(groups[update.GroupName], update) if update.Threads != nil { threadsByGroup[update.GroupName] = append(threadsByGroup[update.GroupName], update.Threads...) } } // Add any accumulated counts to what was just observed, // and update the accumulators. for gname, group := range groups { if oldcounts, ok := g.groupAccum[gname]; ok { group.Counts.Add(Delta(oldcounts)) } g.groupAccum[gname] = group.Counts group.Threads = g.threads(gname, threadsByGroup[gname]) groups[gname] = group } // Now add any groups that were observed in the past but aren't running now. for gname, gcounts := range g.groupAccum { if _, ok := groups[gname]; !ok { groups[gname] = Group{Counts: gcounts} } } return groups }
[ "func", "(", "g", "*", "Grouper", ")", "groups", "(", "tracked", "[", "]", "Update", ")", "GroupByName", "{", "groups", ":=", "make", "(", "GroupByName", ")", "\n", "threadsByGroup", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "ThreadUpdate", ")", "\n\n", "for", "_", ",", "update", ":=", "range", "tracked", "{", "groups", "[", "update", ".", "GroupName", "]", "=", "groupadd", "(", "groups", "[", "update", ".", "GroupName", "]", ",", "update", ")", "\n", "if", "update", ".", "Threads", "!=", "nil", "{", "threadsByGroup", "[", "update", ".", "GroupName", "]", "=", "append", "(", "threadsByGroup", "[", "update", ".", "GroupName", "]", ",", "update", ".", "Threads", "...", ")", "\n", "}", "\n", "}", "\n\n", "// Add any accumulated counts to what was just observed,", "// and update the accumulators.", "for", "gname", ",", "group", ":=", "range", "groups", "{", "if", "oldcounts", ",", "ok", ":=", "g", ".", "groupAccum", "[", "gname", "]", ";", "ok", "{", "group", ".", "Counts", ".", "Add", "(", "Delta", "(", "oldcounts", ")", ")", "\n", "}", "\n", "g", ".", "groupAccum", "[", "gname", "]", "=", "group", ".", "Counts", "\n", "group", ".", "Threads", "=", "g", ".", "threads", "(", "gname", ",", "threadsByGroup", "[", "gname", "]", ")", "\n", "groups", "[", "gname", "]", "=", "group", "\n", "}", "\n\n", "// Now add any groups that were observed in the past but aren't running now.", "for", "gname", ",", "gcounts", ":=", "range", "g", ".", "groupAccum", "{", "if", "_", ",", "ok", ":=", "groups", "[", "gname", "]", ";", "!", "ok", "{", "groups", "[", "gname", "]", "=", "Group", "{", "Counts", ":", "gcounts", "}", "\n", "}", "\n", "}", "\n\n", "return", "groups", "\n", "}" ]
// Translate the updates into a new GroupByName and update internal history.
[ "Translate", "the", "updates", "into", "a", "new", "GroupByName", "and", "update", "internal", "history", "." ]
0f1987d2db4f6fccdec912784031c966b066765d
https://github.com/ncabatoff/process-exporter/blob/0f1987d2db4f6fccdec912784031c966b066765d/proc/grouper.go#L110-L141
149,514
hashicorp/errwrap
errwrap.go
Contains
func Contains(err error, msg string) bool { return len(GetAll(err, msg)) > 0 }
go
func Contains(err error, msg string) bool { return len(GetAll(err, msg)) > 0 }
[ "func", "Contains", "(", "err", "error", ",", "msg", "string", ")", "bool", "{", "return", "len", "(", "GetAll", "(", "err", ",", "msg", ")", ")", ">", "0", "\n", "}" ]
// Contains checks if the given error contains an error with the // message msg. If err is not a wrapped error, this will always return // false unless the error itself happens to match this msg.
[ "Contains", "checks", "if", "the", "given", "error", "contains", "an", "error", "with", "the", "message", "msg", ".", "If", "err", "is", "not", "a", "wrapped", "error", "this", "will", "always", "return", "false", "unless", "the", "error", "itself", "happens", "to", "match", "this", "msg", "." ]
8a6fb523712970c966eefc6b39ed2c5e74880354
https://github.com/hashicorp/errwrap/blob/8a6fb523712970c966eefc6b39ed2c5e74880354/errwrap.go#L62-L64
149,515
hashicorp/errwrap
errwrap.go
Get
func Get(err error, msg string) error { es := GetAll(err, msg) if len(es) > 0 { return es[len(es)-1] } return nil }
go
func Get(err error, msg string) error { es := GetAll(err, msg) if len(es) > 0 { return es[len(es)-1] } return nil }
[ "func", "Get", "(", "err", "error", ",", "msg", "string", ")", "error", "{", "es", ":=", "GetAll", "(", "err", ",", "msg", ")", "\n", "if", "len", "(", "es", ")", ">", "0", "{", "return", "es", "[", "len", "(", "es", ")", "-", "1", "]", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Get is the same as GetAll but returns the deepest matching error.
[ "Get", "is", "the", "same", "as", "GetAll", "but", "returns", "the", "deepest", "matching", "error", "." ]
8a6fb523712970c966eefc6b39ed2c5e74880354
https://github.com/hashicorp/errwrap/blob/8a6fb523712970c966eefc6b39ed2c5e74880354/errwrap.go#L74-L81
149,516
hashicorp/errwrap
errwrap.go
GetType
func GetType(err error, v interface{}) error { es := GetAllType(err, v) if len(es) > 0 { return es[len(es)-1] } return nil }
go
func GetType(err error, v interface{}) error { es := GetAllType(err, v) if len(es) > 0 { return es[len(es)-1] } return nil }
[ "func", "GetType", "(", "err", "error", ",", "v", "interface", "{", "}", ")", "error", "{", "es", ":=", "GetAllType", "(", "err", ",", "v", ")", "\n", "if", "len", "(", "es", ")", ">", "0", "{", "return", "es", "[", "len", "(", "es", ")", "-", "1", "]", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// GetType is the same as GetAllType but returns the deepest matching error.
[ "GetType", "is", "the", "same", "as", "GetAllType", "but", "returns", "the", "deepest", "matching", "error", "." ]
8a6fb523712970c966eefc6b39ed2c5e74880354
https://github.com/hashicorp/errwrap/blob/8a6fb523712970c966eefc6b39ed2c5e74880354/errwrap.go#L84-L91
149,517
hashicorp/errwrap
errwrap.go
GetAllType
func GetAllType(err error, v interface{}) []error { var result []error var search string if v != nil { search = reflect.TypeOf(v).String() } Walk(err, func(err error) { var needle string if err != nil { needle = reflect.TypeOf(err).String() } if needle == search { result = append(result, err) } }) return result }
go
func GetAllType(err error, v interface{}) []error { var result []error var search string if v != nil { search = reflect.TypeOf(v).String() } Walk(err, func(err error) { var needle string if err != nil { needle = reflect.TypeOf(err).String() } if needle == search { result = append(result, err) } }) return result }
[ "func", "GetAllType", "(", "err", "error", ",", "v", "interface", "{", "}", ")", "[", "]", "error", "{", "var", "result", "[", "]", "error", "\n\n", "var", "search", "string", "\n", "if", "v", "!=", "nil", "{", "search", "=", "reflect", ".", "TypeOf", "(", "v", ")", ".", "String", "(", ")", "\n", "}", "\n", "Walk", "(", "err", ",", "func", "(", "err", "error", ")", "{", "var", "needle", "string", "\n", "if", "err", "!=", "nil", "{", "needle", "=", "reflect", ".", "TypeOf", "(", "err", ")", ".", "String", "(", ")", "\n", "}", "\n\n", "if", "needle", "==", "search", "{", "result", "=", "append", "(", "result", ",", "err", ")", "\n", "}", "\n", "}", ")", "\n\n", "return", "result", "\n", "}" ]
// GetAllType gets all the errors that are the same type as v. // // The order of the return value is the same as described in GetAll.
[ "GetAllType", "gets", "all", "the", "errors", "that", "are", "the", "same", "type", "as", "v", ".", "The", "order", "of", "the", "return", "value", "is", "the", "same", "as", "described", "in", "GetAll", "." ]
8a6fb523712970c966eefc6b39ed2c5e74880354
https://github.com/hashicorp/errwrap/blob/8a6fb523712970c966eefc6b39ed2c5e74880354/errwrap.go#L111-L130
149,518
hashicorp/errwrap
errwrap.go
Walk
func Walk(err error, cb WalkFunc) { if err == nil { return } switch e := err.(type) { case *wrappedError: cb(e.Outer) Walk(e.Inner, cb) case Wrapper: cb(err) for _, err := range e.WrappedErrors() { Walk(err, cb) } default: cb(err) } }
go
func Walk(err error, cb WalkFunc) { if err == nil { return } switch e := err.(type) { case *wrappedError: cb(e.Outer) Walk(e.Inner, cb) case Wrapper: cb(err) for _, err := range e.WrappedErrors() { Walk(err, cb) } default: cb(err) } }
[ "func", "Walk", "(", "err", "error", ",", "cb", "WalkFunc", ")", "{", "if", "err", "==", "nil", "{", "return", "\n", "}", "\n\n", "switch", "e", ":=", "err", ".", "(", "type", ")", "{", "case", "*", "wrappedError", ":", "cb", "(", "e", ".", "Outer", ")", "\n", "Walk", "(", "e", ".", "Inner", ",", "cb", ")", "\n", "case", "Wrapper", ":", "cb", "(", "err", ")", "\n\n", "for", "_", ",", "err", ":=", "range", "e", ".", "WrappedErrors", "(", ")", "{", "Walk", "(", "err", ",", "cb", ")", "\n", "}", "\n", "default", ":", "cb", "(", "err", ")", "\n", "}", "\n", "}" ]
// Walk walks all the wrapped errors in err and calls the callback. If // err isn't a wrapped error, this will be called once for err. If err // is a wrapped error, the callback will be called for both the wrapper // that implements error as well as the wrapped error itself.
[ "Walk", "walks", "all", "the", "wrapped", "errors", "in", "err", "and", "calls", "the", "callback", ".", "If", "err", "isn", "t", "a", "wrapped", "error", "this", "will", "be", "called", "once", "for", "err", ".", "If", "err", "is", "a", "wrapped", "error", "the", "callback", "will", "be", "called", "for", "both", "the", "wrapper", "that", "implements", "error", "as", "well", "as", "the", "wrapped", "error", "itself", "." ]
8a6fb523712970c966eefc6b39ed2c5e74880354
https://github.com/hashicorp/errwrap/blob/8a6fb523712970c966eefc6b39ed2c5e74880354/errwrap.go#L136-L154
149,519
btcsuite/btcutil
gcs/gcs.go
NPBytes
func (f *Filter) NPBytes() ([]byte, error) { var buffer bytes.Buffer buffer.Grow(wire.VarIntSerializeSize(uint64(f.n)) + 1 + len(f.filterData)) err := wire.WriteVarInt(&buffer, varIntProtoVer, uint64(f.n)) if err != nil { return nil, err } err = buffer.WriteByte(f.p) if err != nil { return nil, err } _, err = buffer.Write(f.filterData) if err != nil { return nil, err } return buffer.Bytes(), nil }
go
func (f *Filter) NPBytes() ([]byte, error) { var buffer bytes.Buffer buffer.Grow(wire.VarIntSerializeSize(uint64(f.n)) + 1 + len(f.filterData)) err := wire.WriteVarInt(&buffer, varIntProtoVer, uint64(f.n)) if err != nil { return nil, err } err = buffer.WriteByte(f.p) if err != nil { return nil, err } _, err = buffer.Write(f.filterData) if err != nil { return nil, err } return buffer.Bytes(), nil }
[ "func", "(", "f", "*", "Filter", ")", "NPBytes", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "buffer", "bytes", ".", "Buffer", "\n", "buffer", ".", "Grow", "(", "wire", ".", "VarIntSerializeSize", "(", "uint64", "(", "f", ".", "n", ")", ")", "+", "1", "+", "len", "(", "f", ".", "filterData", ")", ")", "\n\n", "err", ":=", "wire", ".", "WriteVarInt", "(", "&", "buffer", ",", "varIntProtoVer", ",", "uint64", "(", "f", ".", "n", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "err", "=", "buffer", ".", "WriteByte", "(", "f", ".", "p", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "_", ",", "err", "=", "buffer", ".", "Write", "(", "f", ".", "filterData", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "buffer", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// NPBytes returns the serialized format of the GCS filter with N and P, which // does not include the key used by SipHash.
[ "NPBytes", "returns", "the", "serialized", "format", "of", "the", "GCS", "filter", "with", "N", "and", "P", "which", "does", "not", "include", "the", "key", "used", "by", "SipHash", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/gcs/gcs.go#L253-L273
149,520
btcsuite/btcutil
appdata.go
appDataDir
func appDataDir(goos, appName string, roaming bool) string { if appName == "" || appName == "." { return "." } // The caller really shouldn't prepend the appName with a period, but // if they do, handle it gracefully by trimming it. appName = strings.TrimPrefix(appName, ".") appNameUpper := string(unicode.ToUpper(rune(appName[0]))) + appName[1:] appNameLower := string(unicode.ToLower(rune(appName[0]))) + appName[1:] // Get the OS specific home directory via the Go standard lib. var homeDir string usr, err := user.Current() if err == nil { homeDir = usr.HomeDir } // Fall back to standard HOME environment variable that works // for most POSIX OSes if the directory from the Go standard // lib failed. if err != nil || homeDir == "" { homeDir = os.Getenv("HOME") } switch goos { // Attempt to use the LOCALAPPDATA or APPDATA environment variable on // Windows. case "windows": // Windows XP and before didn't have a LOCALAPPDATA, so fallback // to regular APPDATA when LOCALAPPDATA is not set. appData := os.Getenv("LOCALAPPDATA") if roaming || appData == "" { appData = os.Getenv("APPDATA") } if appData != "" { return filepath.Join(appData, appNameUpper) } case "darwin": if homeDir != "" { return filepath.Join(homeDir, "Library", "Application Support", appNameUpper) } case "plan9": if homeDir != "" { return filepath.Join(homeDir, appNameLower) } default: if homeDir != "" { return filepath.Join(homeDir, "."+appNameLower) } } // Fall back to the current directory if all else fails. return "." }
go
func appDataDir(goos, appName string, roaming bool) string { if appName == "" || appName == "." { return "." } // The caller really shouldn't prepend the appName with a period, but // if they do, handle it gracefully by trimming it. appName = strings.TrimPrefix(appName, ".") appNameUpper := string(unicode.ToUpper(rune(appName[0]))) + appName[1:] appNameLower := string(unicode.ToLower(rune(appName[0]))) + appName[1:] // Get the OS specific home directory via the Go standard lib. var homeDir string usr, err := user.Current() if err == nil { homeDir = usr.HomeDir } // Fall back to standard HOME environment variable that works // for most POSIX OSes if the directory from the Go standard // lib failed. if err != nil || homeDir == "" { homeDir = os.Getenv("HOME") } switch goos { // Attempt to use the LOCALAPPDATA or APPDATA environment variable on // Windows. case "windows": // Windows XP and before didn't have a LOCALAPPDATA, so fallback // to regular APPDATA when LOCALAPPDATA is not set. appData := os.Getenv("LOCALAPPDATA") if roaming || appData == "" { appData = os.Getenv("APPDATA") } if appData != "" { return filepath.Join(appData, appNameUpper) } case "darwin": if homeDir != "" { return filepath.Join(homeDir, "Library", "Application Support", appNameUpper) } case "plan9": if homeDir != "" { return filepath.Join(homeDir, appNameLower) } default: if homeDir != "" { return filepath.Join(homeDir, "."+appNameLower) } } // Fall back to the current directory if all else fails. return "." }
[ "func", "appDataDir", "(", "goos", ",", "appName", "string", ",", "roaming", "bool", ")", "string", "{", "if", "appName", "==", "\"", "\"", "||", "appName", "==", "\"", "\"", "{", "return", "\"", "\"", "\n", "}", "\n\n", "// The caller really shouldn't prepend the appName with a period, but", "// if they do, handle it gracefully by trimming it.", "appName", "=", "strings", ".", "TrimPrefix", "(", "appName", ",", "\"", "\"", ")", "\n", "appNameUpper", ":=", "string", "(", "unicode", ".", "ToUpper", "(", "rune", "(", "appName", "[", "0", "]", ")", ")", ")", "+", "appName", "[", "1", ":", "]", "\n", "appNameLower", ":=", "string", "(", "unicode", ".", "ToLower", "(", "rune", "(", "appName", "[", "0", "]", ")", ")", ")", "+", "appName", "[", "1", ":", "]", "\n\n", "// Get the OS specific home directory via the Go standard lib.", "var", "homeDir", "string", "\n", "usr", ",", "err", ":=", "user", ".", "Current", "(", ")", "\n", "if", "err", "==", "nil", "{", "homeDir", "=", "usr", ".", "HomeDir", "\n", "}", "\n\n", "// Fall back to standard HOME environment variable that works", "// for most POSIX OSes if the directory from the Go standard", "// lib failed.", "if", "err", "!=", "nil", "||", "homeDir", "==", "\"", "\"", "{", "homeDir", "=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "}", "\n\n", "switch", "goos", "{", "// Attempt to use the LOCALAPPDATA or APPDATA environment variable on", "// Windows.", "case", "\"", "\"", ":", "// Windows XP and before didn't have a LOCALAPPDATA, so fallback", "// to regular APPDATA when LOCALAPPDATA is not set.", "appData", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "if", "roaming", "||", "appData", "==", "\"", "\"", "{", "appData", "=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "appData", "!=", "\"", "\"", "{", "return", "filepath", ".", "Join", "(", "appData", ",", "appNameUpper", ")", "\n", "}", "\n\n", "case", "\"", "\"", ":", "if", "homeDir", "!=", "\"", "\"", "{", "return", "filepath", ".", "Join", "(", "homeDir", ",", "\"", "\"", ",", "\"", "\"", ",", "appNameUpper", ")", "\n", "}", "\n\n", "case", "\"", "\"", ":", "if", "homeDir", "!=", "\"", "\"", "{", "return", "filepath", ".", "Join", "(", "homeDir", ",", "appNameLower", ")", "\n", "}", "\n\n", "default", ":", "if", "homeDir", "!=", "\"", "\"", "{", "return", "filepath", ".", "Join", "(", "homeDir", ",", "\"", "\"", "+", "appNameLower", ")", "\n", "}", "\n", "}", "\n\n", "// Fall back to the current directory if all else fails.", "return", "\"", "\"", "\n", "}" ]
// appDataDir returns an operating system specific directory to be used for // storing application data for an application. See AppDataDir for more // details. This unexported version takes an operating system argument // primarily to enable the testing package to properly test the function by // forcing an operating system that is not the currently one.
[ "appDataDir", "returns", "an", "operating", "system", "specific", "directory", "to", "be", "used", "for", "storing", "application", "data", "for", "an", "application", ".", "See", "AppDataDir", "for", "more", "details", ".", "This", "unexported", "version", "takes", "an", "operating", "system", "argument", "primarily", "to", "enable", "the", "testing", "package", "to", "properly", "test", "the", "function", "by", "forcing", "an", "operating", "system", "that", "is", "not", "the", "currently", "one", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/appdata.go#L21-L80
149,521
btcsuite/btcutil
hdkeychain/extendedkey.go
NewExtendedKey
func NewExtendedKey(version, key, chainCode, parentFP []byte, depth uint8, childNum uint32, isPrivate bool) *ExtendedKey { // NOTE: The pubKey field is intentionally left nil so it is only // computed and memoized as required. return &ExtendedKey{ key: key, chainCode: chainCode, depth: depth, parentFP: parentFP, childNum: childNum, version: version, isPrivate: isPrivate, } }
go
func NewExtendedKey(version, key, chainCode, parentFP []byte, depth uint8, childNum uint32, isPrivate bool) *ExtendedKey { // NOTE: The pubKey field is intentionally left nil so it is only // computed and memoized as required. return &ExtendedKey{ key: key, chainCode: chainCode, depth: depth, parentFP: parentFP, childNum: childNum, version: version, isPrivate: isPrivate, } }
[ "func", "NewExtendedKey", "(", "version", ",", "key", ",", "chainCode", ",", "parentFP", "[", "]", "byte", ",", "depth", "uint8", ",", "childNum", "uint32", ",", "isPrivate", "bool", ")", "*", "ExtendedKey", "{", "// NOTE: The pubKey field is intentionally left nil so it is only", "// computed and memoized as required.", "return", "&", "ExtendedKey", "{", "key", ":", "key", ",", "chainCode", ":", "chainCode", ",", "depth", ":", "depth", ",", "parentFP", ":", "parentFP", ",", "childNum", ":", "childNum", ",", "version", ":", "version", ",", "isPrivate", ":", "isPrivate", ",", "}", "\n", "}" ]
// NewExtendedKey returns a new instance of an extended key with the given // fields. No error checking is performed here as it's only intended to be a // convenience method used to create a populated struct. This function should // only by used by applications that need to create custom ExtendedKeys. All // other applications should just use NewMaster, Child, or Neuter.
[ "NewExtendedKey", "returns", "a", "new", "instance", "of", "an", "extended", "key", "with", "the", "given", "fields", ".", "No", "error", "checking", "is", "performed", "here", "as", "it", "s", "only", "intended", "to", "be", "a", "convenience", "method", "used", "to", "create", "a", "populated", "struct", ".", "This", "function", "should", "only", "by", "used", "by", "applications", "that", "need", "to", "create", "custom", "ExtendedKeys", ".", "All", "other", "applications", "should", "just", "use", "NewMaster", "Child", "or", "Neuter", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/hdkeychain/extendedkey.go#L124-L138
149,522
btcsuite/btcutil
hdkeychain/extendedkey.go
Neuter
func (k *ExtendedKey) Neuter() (*ExtendedKey, error) { // Already an extended public key. if !k.isPrivate { return k, nil } // Get the associated public extended key version bytes. version, err := chaincfg.HDPrivateKeyToPublicKeyID(k.version) if err != nil { return nil, err } // Convert it to an extended public key. The key for the new extended // key will simply be the pubkey of the current extended private key. // // This is the function N((k,c)) -> (K, c) from [BIP32]. return NewExtendedKey(version, k.pubKeyBytes(), k.chainCode, k.parentFP, k.depth, k.childNum, false), nil }
go
func (k *ExtendedKey) Neuter() (*ExtendedKey, error) { // Already an extended public key. if !k.isPrivate { return k, nil } // Get the associated public extended key version bytes. version, err := chaincfg.HDPrivateKeyToPublicKeyID(k.version) if err != nil { return nil, err } // Convert it to an extended public key. The key for the new extended // key will simply be the pubkey of the current extended private key. // // This is the function N((k,c)) -> (K, c) from [BIP32]. return NewExtendedKey(version, k.pubKeyBytes(), k.chainCode, k.parentFP, k.depth, k.childNum, false), nil }
[ "func", "(", "k", "*", "ExtendedKey", ")", "Neuter", "(", ")", "(", "*", "ExtendedKey", ",", "error", ")", "{", "// Already an extended public key.", "if", "!", "k", ".", "isPrivate", "{", "return", "k", ",", "nil", "\n", "}", "\n\n", "// Get the associated public extended key version bytes.", "version", ",", "err", ":=", "chaincfg", ".", "HDPrivateKeyToPublicKeyID", "(", "k", ".", "version", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Convert it to an extended public key. The key for the new extended", "// key will simply be the pubkey of the current extended private key.", "//", "// This is the function N((k,c)) -> (K, c) from [BIP32].", "return", "NewExtendedKey", "(", "version", ",", "k", ".", "pubKeyBytes", "(", ")", ",", "k", ".", "chainCode", ",", "k", ".", "parentFP", ",", "k", ".", "depth", ",", "k", ".", "childNum", ",", "false", ")", ",", "nil", "\n", "}" ]
// Neuter returns a new extended public key from this extended private key. The // same extended key will be returned unaltered if it is already an extended // public key. // // As the name implies, an extended public key does not have access to the // private key, so it is not capable of signing transactions or deriving // child extended private keys. However, it is capable of deriving further // child extended public keys.
[ "Neuter", "returns", "a", "new", "extended", "public", "key", "from", "this", "extended", "private", "key", ".", "The", "same", "extended", "key", "will", "be", "returned", "unaltered", "if", "it", "is", "already", "an", "extended", "public", "key", ".", "As", "the", "name", "implies", "an", "extended", "public", "key", "does", "not", "have", "access", "to", "the", "private", "key", "so", "it", "is", "not", "capable", "of", "signing", "transactions", "or", "deriving", "child", "extended", "private", "keys", ".", "However", "it", "is", "capable", "of", "deriving", "further", "child", "extended", "public", "keys", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/hdkeychain/extendedkey.go#L340-L358
149,523
btcsuite/btcutil
hdkeychain/extendedkey.go
ECPubKey
func (k *ExtendedKey) ECPubKey() (*btcec.PublicKey, error) { return btcec.ParsePubKey(k.pubKeyBytes(), btcec.S256()) }
go
func (k *ExtendedKey) ECPubKey() (*btcec.PublicKey, error) { return btcec.ParsePubKey(k.pubKeyBytes(), btcec.S256()) }
[ "func", "(", "k", "*", "ExtendedKey", ")", "ECPubKey", "(", ")", "(", "*", "btcec", ".", "PublicKey", ",", "error", ")", "{", "return", "btcec", ".", "ParsePubKey", "(", "k", ".", "pubKeyBytes", "(", ")", ",", "btcec", ".", "S256", "(", ")", ")", "\n", "}" ]
// ECPubKey converts the extended key to a btcec public key and returns it.
[ "ECPubKey", "converts", "the", "extended", "key", "to", "a", "btcec", "public", "key", "and", "returns", "it", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/hdkeychain/extendedkey.go#L361-L363
149,524
btcsuite/btcutil
hdkeychain/extendedkey.go
String
func (k *ExtendedKey) String() string { if len(k.key) == 0 { return "zeroed extended key" } var childNumBytes [4]byte binary.BigEndian.PutUint32(childNumBytes[:], k.childNum) // The serialized format is: // version (4) || depth (1) || parent fingerprint (4)) || // child num (4) || chain code (32) || key data (33) || checksum (4) serializedBytes := make([]byte, 0, serializedKeyLen+4) serializedBytes = append(serializedBytes, k.version...) serializedBytes = append(serializedBytes, k.depth) serializedBytes = append(serializedBytes, k.parentFP...) serializedBytes = append(serializedBytes, childNumBytes[:]...) serializedBytes = append(serializedBytes, k.chainCode...) if k.isPrivate { serializedBytes = append(serializedBytes, 0x00) serializedBytes = paddedAppend(32, serializedBytes, k.key) } else { serializedBytes = append(serializedBytes, k.pubKeyBytes()...) } checkSum := chainhash.DoubleHashB(serializedBytes)[:4] serializedBytes = append(serializedBytes, checkSum...) return base58.Encode(serializedBytes) }
go
func (k *ExtendedKey) String() string { if len(k.key) == 0 { return "zeroed extended key" } var childNumBytes [4]byte binary.BigEndian.PutUint32(childNumBytes[:], k.childNum) // The serialized format is: // version (4) || depth (1) || parent fingerprint (4)) || // child num (4) || chain code (32) || key data (33) || checksum (4) serializedBytes := make([]byte, 0, serializedKeyLen+4) serializedBytes = append(serializedBytes, k.version...) serializedBytes = append(serializedBytes, k.depth) serializedBytes = append(serializedBytes, k.parentFP...) serializedBytes = append(serializedBytes, childNumBytes[:]...) serializedBytes = append(serializedBytes, k.chainCode...) if k.isPrivate { serializedBytes = append(serializedBytes, 0x00) serializedBytes = paddedAppend(32, serializedBytes, k.key) } else { serializedBytes = append(serializedBytes, k.pubKeyBytes()...) } checkSum := chainhash.DoubleHashB(serializedBytes)[:4] serializedBytes = append(serializedBytes, checkSum...) return base58.Encode(serializedBytes) }
[ "func", "(", "k", "*", "ExtendedKey", ")", "String", "(", ")", "string", "{", "if", "len", "(", "k", ".", "key", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n\n", "var", "childNumBytes", "[", "4", "]", "byte", "\n", "binary", ".", "BigEndian", ".", "PutUint32", "(", "childNumBytes", "[", ":", "]", ",", "k", ".", "childNum", ")", "\n\n", "// The serialized format is:", "// version (4) || depth (1) || parent fingerprint (4)) ||", "// child num (4) || chain code (32) || key data (33) || checksum (4)", "serializedBytes", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "serializedKeyLen", "+", "4", ")", "\n", "serializedBytes", "=", "append", "(", "serializedBytes", ",", "k", ".", "version", "...", ")", "\n", "serializedBytes", "=", "append", "(", "serializedBytes", ",", "k", ".", "depth", ")", "\n", "serializedBytes", "=", "append", "(", "serializedBytes", ",", "k", ".", "parentFP", "...", ")", "\n", "serializedBytes", "=", "append", "(", "serializedBytes", ",", "childNumBytes", "[", ":", "]", "...", ")", "\n", "serializedBytes", "=", "append", "(", "serializedBytes", ",", "k", ".", "chainCode", "...", ")", "\n", "if", "k", ".", "isPrivate", "{", "serializedBytes", "=", "append", "(", "serializedBytes", ",", "0x00", ")", "\n", "serializedBytes", "=", "paddedAppend", "(", "32", ",", "serializedBytes", ",", "k", ".", "key", ")", "\n", "}", "else", "{", "serializedBytes", "=", "append", "(", "serializedBytes", ",", "k", ".", "pubKeyBytes", "(", ")", "...", ")", "\n", "}", "\n\n", "checkSum", ":=", "chainhash", ".", "DoubleHashB", "(", "serializedBytes", ")", "[", ":", "4", "]", "\n", "serializedBytes", "=", "append", "(", "serializedBytes", ",", "checkSum", "...", ")", "\n", "return", "base58", ".", "Encode", "(", "serializedBytes", ")", "\n", "}" ]
// String returns the extended key as a human-readable base58-encoded string.
[ "String", "returns", "the", "extended", "key", "as", "a", "human", "-", "readable", "base58", "-", "encoded", "string", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/hdkeychain/extendedkey.go#L396-L423
149,525
btcsuite/btcutil
hdkeychain/extendedkey.go
IsForNet
func (k *ExtendedKey) IsForNet(net *chaincfg.Params) bool { return bytes.Equal(k.version, net.HDPrivateKeyID[:]) || bytes.Equal(k.version, net.HDPublicKeyID[:]) }
go
func (k *ExtendedKey) IsForNet(net *chaincfg.Params) bool { return bytes.Equal(k.version, net.HDPrivateKeyID[:]) || bytes.Equal(k.version, net.HDPublicKeyID[:]) }
[ "func", "(", "k", "*", "ExtendedKey", ")", "IsForNet", "(", "net", "*", "chaincfg", ".", "Params", ")", "bool", "{", "return", "bytes", ".", "Equal", "(", "k", ".", "version", ",", "net", ".", "HDPrivateKeyID", "[", ":", "]", ")", "||", "bytes", ".", "Equal", "(", "k", ".", "version", ",", "net", ".", "HDPublicKeyID", "[", ":", "]", ")", "\n", "}" ]
// IsForNet returns whether or not the extended key is associated with the // passed bitcoin network.
[ "IsForNet", "returns", "whether", "or", "not", "the", "extended", "key", "is", "associated", "with", "the", "passed", "bitcoin", "network", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/hdkeychain/extendedkey.go#L427-L430
149,526
btcsuite/btcutil
hdkeychain/extendedkey.go
SetNet
func (k *ExtendedKey) SetNet(net *chaincfg.Params) { if k.isPrivate { k.version = net.HDPrivateKeyID[:] } else { k.version = net.HDPublicKeyID[:] } }
go
func (k *ExtendedKey) SetNet(net *chaincfg.Params) { if k.isPrivate { k.version = net.HDPrivateKeyID[:] } else { k.version = net.HDPublicKeyID[:] } }
[ "func", "(", "k", "*", "ExtendedKey", ")", "SetNet", "(", "net", "*", "chaincfg", ".", "Params", ")", "{", "if", "k", ".", "isPrivate", "{", "k", ".", "version", "=", "net", ".", "HDPrivateKeyID", "[", ":", "]", "\n", "}", "else", "{", "k", ".", "version", "=", "net", ".", "HDPublicKeyID", "[", ":", "]", "\n", "}", "\n", "}" ]
// SetNet associates the extended key, and any child keys yet to be derived from // it, with the passed network.
[ "SetNet", "associates", "the", "extended", "key", "and", "any", "child", "keys", "yet", "to", "be", "derived", "from", "it", "with", "the", "passed", "network", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/hdkeychain/extendedkey.go#L434-L440
149,527
btcsuite/btcutil
hdkeychain/extendedkey.go
zero
func zero(b []byte) { lenb := len(b) for i := 0; i < lenb; i++ { b[i] = 0 } }
go
func zero(b []byte) { lenb := len(b) for i := 0; i < lenb; i++ { b[i] = 0 } }
[ "func", "zero", "(", "b", "[", "]", "byte", ")", "{", "lenb", ":=", "len", "(", "b", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "lenb", ";", "i", "++", "{", "b", "[", "i", "]", "=", "0", "\n", "}", "\n", "}" ]
// zero sets all bytes in the passed slice to zero. This is used to // explicitly clear private key material from memory.
[ "zero", "sets", "all", "bytes", "in", "the", "passed", "slice", "to", "zero", ".", "This", "is", "used", "to", "explicitly", "clear", "private", "key", "material", "from", "memory", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/hdkeychain/extendedkey.go#L444-L449
149,528
btcsuite/btcutil
hdkeychain/extendedkey.go
Zero
func (k *ExtendedKey) Zero() { zero(k.key) zero(k.pubKey) zero(k.chainCode) zero(k.parentFP) k.version = nil k.key = nil k.depth = 0 k.childNum = 0 k.isPrivate = false }
go
func (k *ExtendedKey) Zero() { zero(k.key) zero(k.pubKey) zero(k.chainCode) zero(k.parentFP) k.version = nil k.key = nil k.depth = 0 k.childNum = 0 k.isPrivate = false }
[ "func", "(", "k", "*", "ExtendedKey", ")", "Zero", "(", ")", "{", "zero", "(", "k", ".", "key", ")", "\n", "zero", "(", "k", ".", "pubKey", ")", "\n", "zero", "(", "k", ".", "chainCode", ")", "\n", "zero", "(", "k", ".", "parentFP", ")", "\n", "k", ".", "version", "=", "nil", "\n", "k", ".", "key", "=", "nil", "\n", "k", ".", "depth", "=", "0", "\n", "k", ".", "childNum", "=", "0", "\n", "k", ".", "isPrivate", "=", "false", "\n", "}" ]
// Zero manually clears all fields and bytes in the extended key. This can be // used to explicitly clear key material from memory for enhanced security // against memory scraping. This function only clears this particular key and // not any children that have already been derived.
[ "Zero", "manually", "clears", "all", "fields", "and", "bytes", "in", "the", "extended", "key", ".", "This", "can", "be", "used", "to", "explicitly", "clear", "key", "material", "from", "memory", "for", "enhanced", "security", "against", "memory", "scraping", ".", "This", "function", "only", "clears", "this", "particular", "key", "and", "not", "any", "children", "that", "have", "already", "been", "derived", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/hdkeychain/extendedkey.go#L455-L465
149,529
btcsuite/btcutil
hdkeychain/extendedkey.go
NewKeyFromString
func NewKeyFromString(key string) (*ExtendedKey, error) { // The base58-decoded extended key must consist of a serialized payload // plus an additional 4 bytes for the checksum. decoded := base58.Decode(key) if len(decoded) != serializedKeyLen+4 { return nil, ErrInvalidKeyLen } // The serialized format is: // version (4) || depth (1) || parent fingerprint (4)) || // child num (4) || chain code (32) || key data (33) || checksum (4) // Split the payload and checksum up and ensure the checksum matches. payload := decoded[:len(decoded)-4] checkSum := decoded[len(decoded)-4:] expectedCheckSum := chainhash.DoubleHashB(payload)[:4] if !bytes.Equal(checkSum, expectedCheckSum) { return nil, ErrBadChecksum } // Deserialize each of the payload fields. version := payload[:4] depth := payload[4:5][0] parentFP := payload[5:9] childNum := binary.BigEndian.Uint32(payload[9:13]) chainCode := payload[13:45] keyData := payload[45:78] // The key data is a private key if it starts with 0x00. Serialized // compressed pubkeys either start with 0x02 or 0x03. isPrivate := keyData[0] == 0x00 if isPrivate { // Ensure the private key is valid. It must be within the range // of the order of the secp256k1 curve and not be 0. keyData = keyData[1:] keyNum := new(big.Int).SetBytes(keyData) if keyNum.Cmp(btcec.S256().N) >= 0 || keyNum.Sign() == 0 { return nil, ErrUnusableSeed } } else { // Ensure the public key parses correctly and is actually on the // secp256k1 curve. _, err := btcec.ParsePubKey(keyData, btcec.S256()) if err != nil { return nil, err } } return NewExtendedKey(version, keyData, chainCode, parentFP, depth, childNum, isPrivate), nil }
go
func NewKeyFromString(key string) (*ExtendedKey, error) { // The base58-decoded extended key must consist of a serialized payload // plus an additional 4 bytes for the checksum. decoded := base58.Decode(key) if len(decoded) != serializedKeyLen+4 { return nil, ErrInvalidKeyLen } // The serialized format is: // version (4) || depth (1) || parent fingerprint (4)) || // child num (4) || chain code (32) || key data (33) || checksum (4) // Split the payload and checksum up and ensure the checksum matches. payload := decoded[:len(decoded)-4] checkSum := decoded[len(decoded)-4:] expectedCheckSum := chainhash.DoubleHashB(payload)[:4] if !bytes.Equal(checkSum, expectedCheckSum) { return nil, ErrBadChecksum } // Deserialize each of the payload fields. version := payload[:4] depth := payload[4:5][0] parentFP := payload[5:9] childNum := binary.BigEndian.Uint32(payload[9:13]) chainCode := payload[13:45] keyData := payload[45:78] // The key data is a private key if it starts with 0x00. Serialized // compressed pubkeys either start with 0x02 or 0x03. isPrivate := keyData[0] == 0x00 if isPrivate { // Ensure the private key is valid. It must be within the range // of the order of the secp256k1 curve and not be 0. keyData = keyData[1:] keyNum := new(big.Int).SetBytes(keyData) if keyNum.Cmp(btcec.S256().N) >= 0 || keyNum.Sign() == 0 { return nil, ErrUnusableSeed } } else { // Ensure the public key parses correctly and is actually on the // secp256k1 curve. _, err := btcec.ParsePubKey(keyData, btcec.S256()) if err != nil { return nil, err } } return NewExtendedKey(version, keyData, chainCode, parentFP, depth, childNum, isPrivate), nil }
[ "func", "NewKeyFromString", "(", "key", "string", ")", "(", "*", "ExtendedKey", ",", "error", ")", "{", "// The base58-decoded extended key must consist of a serialized payload", "// plus an additional 4 bytes for the checksum.", "decoded", ":=", "base58", ".", "Decode", "(", "key", ")", "\n", "if", "len", "(", "decoded", ")", "!=", "serializedKeyLen", "+", "4", "{", "return", "nil", ",", "ErrInvalidKeyLen", "\n", "}", "\n\n", "// The serialized format is:", "// version (4) || depth (1) || parent fingerprint (4)) ||", "// child num (4) || chain code (32) || key data (33) || checksum (4)", "// Split the payload and checksum up and ensure the checksum matches.", "payload", ":=", "decoded", "[", ":", "len", "(", "decoded", ")", "-", "4", "]", "\n", "checkSum", ":=", "decoded", "[", "len", "(", "decoded", ")", "-", "4", ":", "]", "\n", "expectedCheckSum", ":=", "chainhash", ".", "DoubleHashB", "(", "payload", ")", "[", ":", "4", "]", "\n", "if", "!", "bytes", ".", "Equal", "(", "checkSum", ",", "expectedCheckSum", ")", "{", "return", "nil", ",", "ErrBadChecksum", "\n", "}", "\n\n", "// Deserialize each of the payload fields.", "version", ":=", "payload", "[", ":", "4", "]", "\n", "depth", ":=", "payload", "[", "4", ":", "5", "]", "[", "0", "]", "\n", "parentFP", ":=", "payload", "[", "5", ":", "9", "]", "\n", "childNum", ":=", "binary", ".", "BigEndian", ".", "Uint32", "(", "payload", "[", "9", ":", "13", "]", ")", "\n", "chainCode", ":=", "payload", "[", "13", ":", "45", "]", "\n", "keyData", ":=", "payload", "[", "45", ":", "78", "]", "\n\n", "// The key data is a private key if it starts with 0x00. Serialized", "// compressed pubkeys either start with 0x02 or 0x03.", "isPrivate", ":=", "keyData", "[", "0", "]", "==", "0x00", "\n", "if", "isPrivate", "{", "// Ensure the private key is valid. It must be within the range", "// of the order of the secp256k1 curve and not be 0.", "keyData", "=", "keyData", "[", "1", ":", "]", "\n", "keyNum", ":=", "new", "(", "big", ".", "Int", ")", ".", "SetBytes", "(", "keyData", ")", "\n", "if", "keyNum", ".", "Cmp", "(", "btcec", ".", "S256", "(", ")", ".", "N", ")", ">=", "0", "||", "keyNum", ".", "Sign", "(", ")", "==", "0", "{", "return", "nil", ",", "ErrUnusableSeed", "\n", "}", "\n", "}", "else", "{", "// Ensure the public key parses correctly and is actually on the", "// secp256k1 curve.", "_", ",", "err", ":=", "btcec", ".", "ParsePubKey", "(", "keyData", ",", "btcec", ".", "S256", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "NewExtendedKey", "(", "version", ",", "keyData", ",", "chainCode", ",", "parentFP", ",", "depth", ",", "childNum", ",", "isPrivate", ")", ",", "nil", "\n", "}" ]
// NewKeyFromString returns a new extended key instance from a base58-encoded // extended key.
[ "NewKeyFromString", "returns", "a", "new", "extended", "key", "instance", "from", "a", "base58", "-", "encoded", "extended", "key", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/hdkeychain/extendedkey.go#L506-L556
149,530
btcsuite/btcutil
bloom/filter.go
IsLoaded
func (bf *Filter) IsLoaded() bool { bf.mtx.Lock() loaded := bf.msgFilterLoad != nil bf.mtx.Unlock() return loaded }
go
func (bf *Filter) IsLoaded() bool { bf.mtx.Lock() loaded := bf.msgFilterLoad != nil bf.mtx.Unlock() return loaded }
[ "func", "(", "bf", "*", "Filter", ")", "IsLoaded", "(", ")", "bool", "{", "bf", ".", "mtx", ".", "Lock", "(", ")", "\n", "loaded", ":=", "bf", ".", "msgFilterLoad", "!=", "nil", "\n", "bf", ".", "mtx", ".", "Unlock", "(", ")", "\n", "return", "loaded", "\n", "}" ]
// IsLoaded returns true if a filter is loaded, otherwise false. // // This function is safe for concurrent access.
[ "IsLoaded", "returns", "true", "if", "a", "filter", "is", "loaded", "otherwise", "false", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/bloom/filter.go#L90-L95
149,531
btcsuite/btcutil
bloom/filter.go
Reload
func (bf *Filter) Reload(filter *wire.MsgFilterLoad) { bf.mtx.Lock() bf.msgFilterLoad = filter bf.mtx.Unlock() }
go
func (bf *Filter) Reload(filter *wire.MsgFilterLoad) { bf.mtx.Lock() bf.msgFilterLoad = filter bf.mtx.Unlock() }
[ "func", "(", "bf", "*", "Filter", ")", "Reload", "(", "filter", "*", "wire", ".", "MsgFilterLoad", ")", "{", "bf", ".", "mtx", ".", "Lock", "(", ")", "\n", "bf", ".", "msgFilterLoad", "=", "filter", "\n", "bf", ".", "mtx", ".", "Unlock", "(", ")", "\n", "}" ]
// Reload loads a new filter replacing any existing filter. // // This function is safe for concurrent access.
[ "Reload", "loads", "a", "new", "filter", "replacing", "any", "existing", "filter", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/bloom/filter.go#L100-L104
149,532
btcsuite/btcutil
bloom/filter.go
Unload
func (bf *Filter) Unload() { bf.mtx.Lock() bf.msgFilterLoad = nil bf.mtx.Unlock() }
go
func (bf *Filter) Unload() { bf.mtx.Lock() bf.msgFilterLoad = nil bf.mtx.Unlock() }
[ "func", "(", "bf", "*", "Filter", ")", "Unload", "(", ")", "{", "bf", ".", "mtx", ".", "Lock", "(", ")", "\n", "bf", ".", "msgFilterLoad", "=", "nil", "\n", "bf", ".", "mtx", ".", "Unlock", "(", ")", "\n", "}" ]
// Unload unloads the bloom filter. // // This function is safe for concurrent access.
[ "Unload", "unloads", "the", "bloom", "filter", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/bloom/filter.go#L109-L113
149,533
btcsuite/btcutil
bloom/filter.go
hash
func (bf *Filter) hash(hashNum uint32, data []byte) uint32 { // bitcoind: 0xfba4c795 chosen as it guarantees a reasonable bit // difference between hashNum values. // // Note that << 3 is equivalent to multiplying by 8, but is faster. // Thus the returned hash is brought into range of the number of bits // the filter has and returned. mm := MurmurHash3(hashNum*0xfba4c795+bf.msgFilterLoad.Tweak, data) return mm % (uint32(len(bf.msgFilterLoad.Filter)) << 3) }
go
func (bf *Filter) hash(hashNum uint32, data []byte) uint32 { // bitcoind: 0xfba4c795 chosen as it guarantees a reasonable bit // difference between hashNum values. // // Note that << 3 is equivalent to multiplying by 8, but is faster. // Thus the returned hash is brought into range of the number of bits // the filter has and returned. mm := MurmurHash3(hashNum*0xfba4c795+bf.msgFilterLoad.Tweak, data) return mm % (uint32(len(bf.msgFilterLoad.Filter)) << 3) }
[ "func", "(", "bf", "*", "Filter", ")", "hash", "(", "hashNum", "uint32", ",", "data", "[", "]", "byte", ")", "uint32", "{", "// bitcoind: 0xfba4c795 chosen as it guarantees a reasonable bit", "// difference between hashNum values.", "//", "// Note that << 3 is equivalent to multiplying by 8, but is faster.", "// Thus the returned hash is brought into range of the number of bits", "// the filter has and returned.", "mm", ":=", "MurmurHash3", "(", "hashNum", "*", "0xfba4c795", "+", "bf", ".", "msgFilterLoad", ".", "Tweak", ",", "data", ")", "\n", "return", "mm", "%", "(", "uint32", "(", "len", "(", "bf", ".", "msgFilterLoad", ".", "Filter", ")", ")", "<<", "3", ")", "\n", "}" ]
// hash returns the bit offset in the bloom filter which corresponds to the // passed data for the given indepedent hash function number.
[ "hash", "returns", "the", "bit", "offset", "in", "the", "bloom", "filter", "which", "corresponds", "to", "the", "passed", "data", "for", "the", "given", "indepedent", "hash", "function", "number", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/bloom/filter.go#L117-L126
149,534
btcsuite/btcutil
bloom/filter.go
matches
func (bf *Filter) matches(data []byte) bool { if bf.msgFilterLoad == nil { return false } // The bloom filter does not contain the data if any of the bit offsets // which result from hashing the data using each independent hash // function are not set. The shifts and masks below are a faster // equivalent of: // arrayIndex := idx / 8 (idx >> 3) // bitOffset := idx % 8 (idx & 7) /// if filter[arrayIndex] & 1<<bitOffset == 0 { ... } for i := uint32(0); i < bf.msgFilterLoad.HashFuncs; i++ { idx := bf.hash(i, data) if bf.msgFilterLoad.Filter[idx>>3]&(1<<(idx&7)) == 0 { return false } } return true }
go
func (bf *Filter) matches(data []byte) bool { if bf.msgFilterLoad == nil { return false } // The bloom filter does not contain the data if any of the bit offsets // which result from hashing the data using each independent hash // function are not set. The shifts and masks below are a faster // equivalent of: // arrayIndex := idx / 8 (idx >> 3) // bitOffset := idx % 8 (idx & 7) /// if filter[arrayIndex] & 1<<bitOffset == 0 { ... } for i := uint32(0); i < bf.msgFilterLoad.HashFuncs; i++ { idx := bf.hash(i, data) if bf.msgFilterLoad.Filter[idx>>3]&(1<<(idx&7)) == 0 { return false } } return true }
[ "func", "(", "bf", "*", "Filter", ")", "matches", "(", "data", "[", "]", "byte", ")", "bool", "{", "if", "bf", ".", "msgFilterLoad", "==", "nil", "{", "return", "false", "\n", "}", "\n\n", "// The bloom filter does not contain the data if any of the bit offsets", "// which result from hashing the data using each independent hash", "// function are not set. The shifts and masks below are a faster", "// equivalent of:", "// arrayIndex := idx / 8 (idx >> 3)", "// bitOffset := idx % 8 (idx & 7)", "/// if filter[arrayIndex] & 1<<bitOffset == 0 { ... }", "for", "i", ":=", "uint32", "(", "0", ")", ";", "i", "<", "bf", ".", "msgFilterLoad", ".", "HashFuncs", ";", "i", "++", "{", "idx", ":=", "bf", ".", "hash", "(", "i", ",", "data", ")", "\n", "if", "bf", ".", "msgFilterLoad", ".", "Filter", "[", "idx", ">>", "3", "]", "&", "(", "1", "<<", "(", "idx", "&", "7", ")", ")", "==", "0", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// matches returns true if the bloom filter might contain the passed data and // false if it definitely does not. // // This function MUST be called with the filter lock held.
[ "matches", "returns", "true", "if", "the", "bloom", "filter", "might", "contain", "the", "passed", "data", "and", "false", "if", "it", "definitely", "does", "not", ".", "This", "function", "MUST", "be", "called", "with", "the", "filter", "lock", "held", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/bloom/filter.go#L132-L151
149,535
btcsuite/btcutil
bloom/filter.go
Matches
func (bf *Filter) Matches(data []byte) bool { bf.mtx.Lock() match := bf.matches(data) bf.mtx.Unlock() return match }
go
func (bf *Filter) Matches(data []byte) bool { bf.mtx.Lock() match := bf.matches(data) bf.mtx.Unlock() return match }
[ "func", "(", "bf", "*", "Filter", ")", "Matches", "(", "data", "[", "]", "byte", ")", "bool", "{", "bf", ".", "mtx", ".", "Lock", "(", ")", "\n", "match", ":=", "bf", ".", "matches", "(", "data", ")", "\n", "bf", ".", "mtx", ".", "Unlock", "(", ")", "\n", "return", "match", "\n", "}" ]
// Matches returns true if the bloom filter might contain the passed data and // false if it definitely does not. // // This function is safe for concurrent access.
[ "Matches", "returns", "true", "if", "the", "bloom", "filter", "might", "contain", "the", "passed", "data", "and", "false", "if", "it", "definitely", "does", "not", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/bloom/filter.go#L157-L162
149,536
btcsuite/btcutil
bloom/filter.go
matchesOutPoint
func (bf *Filter) matchesOutPoint(outpoint *wire.OutPoint) bool { // Serialize var buf [chainhash.HashSize + 4]byte copy(buf[:], outpoint.Hash[:]) binary.LittleEndian.PutUint32(buf[chainhash.HashSize:], outpoint.Index) return bf.matches(buf[:]) }
go
func (bf *Filter) matchesOutPoint(outpoint *wire.OutPoint) bool { // Serialize var buf [chainhash.HashSize + 4]byte copy(buf[:], outpoint.Hash[:]) binary.LittleEndian.PutUint32(buf[chainhash.HashSize:], outpoint.Index) return bf.matches(buf[:]) }
[ "func", "(", "bf", "*", "Filter", ")", "matchesOutPoint", "(", "outpoint", "*", "wire", ".", "OutPoint", ")", "bool", "{", "// Serialize", "var", "buf", "[", "chainhash", ".", "HashSize", "+", "4", "]", "byte", "\n", "copy", "(", "buf", "[", ":", "]", ",", "outpoint", ".", "Hash", "[", ":", "]", ")", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "buf", "[", "chainhash", ".", "HashSize", ":", "]", ",", "outpoint", ".", "Index", ")", "\n\n", "return", "bf", ".", "matches", "(", "buf", "[", ":", "]", ")", "\n", "}" ]
// matchesOutPoint returns true if the bloom filter might contain the passed // outpoint and false if it definitely does not. // // This function MUST be called with the filter lock held.
[ "matchesOutPoint", "returns", "true", "if", "the", "bloom", "filter", "might", "contain", "the", "passed", "outpoint", "and", "false", "if", "it", "definitely", "does", "not", ".", "This", "function", "MUST", "be", "called", "with", "the", "filter", "lock", "held", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/bloom/filter.go#L168-L175
149,537
btcsuite/btcutil
bloom/filter.go
MatchesOutPoint
func (bf *Filter) MatchesOutPoint(outpoint *wire.OutPoint) bool { bf.mtx.Lock() match := bf.matchesOutPoint(outpoint) bf.mtx.Unlock() return match }
go
func (bf *Filter) MatchesOutPoint(outpoint *wire.OutPoint) bool { bf.mtx.Lock() match := bf.matchesOutPoint(outpoint) bf.mtx.Unlock() return match }
[ "func", "(", "bf", "*", "Filter", ")", "MatchesOutPoint", "(", "outpoint", "*", "wire", ".", "OutPoint", ")", "bool", "{", "bf", ".", "mtx", ".", "Lock", "(", ")", "\n", "match", ":=", "bf", ".", "matchesOutPoint", "(", "outpoint", ")", "\n", "bf", ".", "mtx", ".", "Unlock", "(", ")", "\n", "return", "match", "\n", "}" ]
// MatchesOutPoint returns true if the bloom filter might contain the passed // outpoint and false if it definitely does not. // // This function is safe for concurrent access.
[ "MatchesOutPoint", "returns", "true", "if", "the", "bloom", "filter", "might", "contain", "the", "passed", "outpoint", "and", "false", "if", "it", "definitely", "does", "not", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/bloom/filter.go#L181-L186
149,538
btcsuite/btcutil
bloom/filter.go
add
func (bf *Filter) add(data []byte) { if bf.msgFilterLoad == nil { return } // Adding data to a bloom filter consists of setting all of the bit // offsets which result from hashing the data using each independent // hash function. The shifts and masks below are a faster equivalent // of: // arrayIndex := idx / 8 (idx >> 3) // bitOffset := idx % 8 (idx & 7) /// filter[arrayIndex] |= 1<<bitOffset for i := uint32(0); i < bf.msgFilterLoad.HashFuncs; i++ { idx := bf.hash(i, data) bf.msgFilterLoad.Filter[idx>>3] |= (1 << (7 & idx)) } }
go
func (bf *Filter) add(data []byte) { if bf.msgFilterLoad == nil { return } // Adding data to a bloom filter consists of setting all of the bit // offsets which result from hashing the data using each independent // hash function. The shifts and masks below are a faster equivalent // of: // arrayIndex := idx / 8 (idx >> 3) // bitOffset := idx % 8 (idx & 7) /// filter[arrayIndex] |= 1<<bitOffset for i := uint32(0); i < bf.msgFilterLoad.HashFuncs; i++ { idx := bf.hash(i, data) bf.msgFilterLoad.Filter[idx>>3] |= (1 << (7 & idx)) } }
[ "func", "(", "bf", "*", "Filter", ")", "add", "(", "data", "[", "]", "byte", ")", "{", "if", "bf", ".", "msgFilterLoad", "==", "nil", "{", "return", "\n", "}", "\n\n", "// Adding data to a bloom filter consists of setting all of the bit", "// offsets which result from hashing the data using each independent", "// hash function. The shifts and masks below are a faster equivalent", "// of:", "// arrayIndex := idx / 8 (idx >> 3)", "// bitOffset := idx % 8 (idx & 7)", "/// filter[arrayIndex] |= 1<<bitOffset", "for", "i", ":=", "uint32", "(", "0", ")", ";", "i", "<", "bf", ".", "msgFilterLoad", ".", "HashFuncs", ";", "i", "++", "{", "idx", ":=", "bf", ".", "hash", "(", "i", ",", "data", ")", "\n", "bf", ".", "msgFilterLoad", ".", "Filter", "[", "idx", ">>", "3", "]", "|=", "(", "1", "<<", "(", "7", "&", "idx", ")", ")", "\n", "}", "\n", "}" ]
// add adds the passed byte slice to the bloom filter. // // This function MUST be called with the filter lock held.
[ "add", "adds", "the", "passed", "byte", "slice", "to", "the", "bloom", "filter", ".", "This", "function", "MUST", "be", "called", "with", "the", "filter", "lock", "held", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/bloom/filter.go#L191-L207
149,539
btcsuite/btcutil
bloom/filter.go
Add
func (bf *Filter) Add(data []byte) { bf.mtx.Lock() bf.add(data) bf.mtx.Unlock() }
go
func (bf *Filter) Add(data []byte) { bf.mtx.Lock() bf.add(data) bf.mtx.Unlock() }
[ "func", "(", "bf", "*", "Filter", ")", "Add", "(", "data", "[", "]", "byte", ")", "{", "bf", ".", "mtx", ".", "Lock", "(", ")", "\n", "bf", ".", "add", "(", "data", ")", "\n", "bf", ".", "mtx", ".", "Unlock", "(", ")", "\n", "}" ]
// Add adds the passed byte slice to the bloom filter. // // This function is safe for concurrent access.
[ "Add", "adds", "the", "passed", "byte", "slice", "to", "the", "bloom", "filter", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/bloom/filter.go#L212-L216
149,540
btcsuite/btcutil
bloom/filter.go
AddHash
func (bf *Filter) AddHash(hash *chainhash.Hash) { bf.mtx.Lock() bf.add(hash[:]) bf.mtx.Unlock() }
go
func (bf *Filter) AddHash(hash *chainhash.Hash) { bf.mtx.Lock() bf.add(hash[:]) bf.mtx.Unlock() }
[ "func", "(", "bf", "*", "Filter", ")", "AddHash", "(", "hash", "*", "chainhash", ".", "Hash", ")", "{", "bf", ".", "mtx", ".", "Lock", "(", ")", "\n", "bf", ".", "add", "(", "hash", "[", ":", "]", ")", "\n", "bf", ".", "mtx", ".", "Unlock", "(", ")", "\n", "}" ]
// AddHash adds the passed chainhash.Hash to the Filter. // // This function is safe for concurrent access.
[ "AddHash", "adds", "the", "passed", "chainhash", ".", "Hash", "to", "the", "Filter", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/bloom/filter.go#L221-L225
149,541
btcsuite/btcutil
bloom/filter.go
addOutPoint
func (bf *Filter) addOutPoint(outpoint *wire.OutPoint) { // Serialize var buf [chainhash.HashSize + 4]byte copy(buf[:], outpoint.Hash[:]) binary.LittleEndian.PutUint32(buf[chainhash.HashSize:], outpoint.Index) bf.add(buf[:]) }
go
func (bf *Filter) addOutPoint(outpoint *wire.OutPoint) { // Serialize var buf [chainhash.HashSize + 4]byte copy(buf[:], outpoint.Hash[:]) binary.LittleEndian.PutUint32(buf[chainhash.HashSize:], outpoint.Index) bf.add(buf[:]) }
[ "func", "(", "bf", "*", "Filter", ")", "addOutPoint", "(", "outpoint", "*", "wire", ".", "OutPoint", ")", "{", "// Serialize", "var", "buf", "[", "chainhash", ".", "HashSize", "+", "4", "]", "byte", "\n", "copy", "(", "buf", "[", ":", "]", ",", "outpoint", ".", "Hash", "[", ":", "]", ")", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "buf", "[", "chainhash", ".", "HashSize", ":", "]", ",", "outpoint", ".", "Index", ")", "\n\n", "bf", ".", "add", "(", "buf", "[", ":", "]", ")", "\n", "}" ]
// addOutPoint adds the passed transaction outpoint to the bloom filter. // // This function MUST be called with the filter lock held.
[ "addOutPoint", "adds", "the", "passed", "transaction", "outpoint", "to", "the", "bloom", "filter", ".", "This", "function", "MUST", "be", "called", "with", "the", "filter", "lock", "held", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/bloom/filter.go#L230-L237
149,542
btcsuite/btcutil
bloom/filter.go
AddOutPoint
func (bf *Filter) AddOutPoint(outpoint *wire.OutPoint) { bf.mtx.Lock() bf.addOutPoint(outpoint) bf.mtx.Unlock() }
go
func (bf *Filter) AddOutPoint(outpoint *wire.OutPoint) { bf.mtx.Lock() bf.addOutPoint(outpoint) bf.mtx.Unlock() }
[ "func", "(", "bf", "*", "Filter", ")", "AddOutPoint", "(", "outpoint", "*", "wire", ".", "OutPoint", ")", "{", "bf", ".", "mtx", ".", "Lock", "(", ")", "\n", "bf", ".", "addOutPoint", "(", "outpoint", ")", "\n", "bf", ".", "mtx", ".", "Unlock", "(", ")", "\n", "}" ]
// AddOutPoint adds the passed transaction outpoint to the bloom filter. // // This function is safe for concurrent access.
[ "AddOutPoint", "adds", "the", "passed", "transaction", "outpoint", "to", "the", "bloom", "filter", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/bloom/filter.go#L242-L246
149,543
btcsuite/btcutil
bloom/filter.go
maybeAddOutpoint
func (bf *Filter) maybeAddOutpoint(pkScript []byte, outHash *chainhash.Hash, outIdx uint32) { switch bf.msgFilterLoad.Flags { case wire.BloomUpdateAll: outpoint := wire.NewOutPoint(outHash, outIdx) bf.addOutPoint(outpoint) case wire.BloomUpdateP2PubkeyOnly: class := txscript.GetScriptClass(pkScript) if class == txscript.PubKeyTy || class == txscript.MultiSigTy { outpoint := wire.NewOutPoint(outHash, outIdx) bf.addOutPoint(outpoint) } } }
go
func (bf *Filter) maybeAddOutpoint(pkScript []byte, outHash *chainhash.Hash, outIdx uint32) { switch bf.msgFilterLoad.Flags { case wire.BloomUpdateAll: outpoint := wire.NewOutPoint(outHash, outIdx) bf.addOutPoint(outpoint) case wire.BloomUpdateP2PubkeyOnly: class := txscript.GetScriptClass(pkScript) if class == txscript.PubKeyTy || class == txscript.MultiSigTy { outpoint := wire.NewOutPoint(outHash, outIdx) bf.addOutPoint(outpoint) } } }
[ "func", "(", "bf", "*", "Filter", ")", "maybeAddOutpoint", "(", "pkScript", "[", "]", "byte", ",", "outHash", "*", "chainhash", ".", "Hash", ",", "outIdx", "uint32", ")", "{", "switch", "bf", ".", "msgFilterLoad", ".", "Flags", "{", "case", "wire", ".", "BloomUpdateAll", ":", "outpoint", ":=", "wire", ".", "NewOutPoint", "(", "outHash", ",", "outIdx", ")", "\n", "bf", ".", "addOutPoint", "(", "outpoint", ")", "\n", "case", "wire", ".", "BloomUpdateP2PubkeyOnly", ":", "class", ":=", "txscript", ".", "GetScriptClass", "(", "pkScript", ")", "\n", "if", "class", "==", "txscript", ".", "PubKeyTy", "||", "class", "==", "txscript", ".", "MultiSigTy", "{", "outpoint", ":=", "wire", ".", "NewOutPoint", "(", "outHash", ",", "outIdx", ")", "\n", "bf", ".", "addOutPoint", "(", "outpoint", ")", "\n", "}", "\n", "}", "\n", "}" ]
// maybeAddOutpoint potentially adds the passed outpoint to the bloom filter // depending on the bloom update flags and the type of the passed public key // script. // // This function MUST be called with the filter lock held.
[ "maybeAddOutpoint", "potentially", "adds", "the", "passed", "outpoint", "to", "the", "bloom", "filter", "depending", "on", "the", "bloom", "update", "flags", "and", "the", "type", "of", "the", "passed", "public", "key", "script", ".", "This", "function", "MUST", "be", "called", "with", "the", "filter", "lock", "held", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/bloom/filter.go#L253-L265
149,544
btcsuite/btcutil
bloom/filter.go
matchTxAndUpdate
func (bf *Filter) matchTxAndUpdate(tx *btcutil.Tx) bool { // Check if the filter matches the hash of the transaction. // This is useful for finding transactions when they appear in a block. matched := bf.matches(tx.Hash()[:]) // Check if the filter matches any data elements in the public key // scripts of any of the outputs. When it does, add the outpoint that // matched so transactions which spend from the matched transaction are // also included in the filter. This removes the burden of updating the // filter for this scenario from the client. It is also more efficient // on the network since it avoids the need for another filteradd message // from the client and avoids some potential races that could otherwise // occur. for i, txOut := range tx.MsgTx().TxOut { pushedData, err := txscript.PushedData(txOut.PkScript) if err != nil { continue } for _, data := range pushedData { if !bf.matches(data) { continue } matched = true bf.maybeAddOutpoint(txOut.PkScript, tx.Hash(), uint32(i)) break } } // Nothing more to do if a match has already been made. if matched { return true } // At this point, the transaction and none of the data elements in the // public key scripts of its outputs matched. // Check if the filter matches any outpoints this transaction spends or // any any data elements in the signature scripts of any of the inputs. for _, txin := range tx.MsgTx().TxIn { if bf.matchesOutPoint(&txin.PreviousOutPoint) { return true } pushedData, err := txscript.PushedData(txin.SignatureScript) if err != nil { continue } for _, data := range pushedData { if bf.matches(data) { return true } } } return false }
go
func (bf *Filter) matchTxAndUpdate(tx *btcutil.Tx) bool { // Check if the filter matches the hash of the transaction. // This is useful for finding transactions when they appear in a block. matched := bf.matches(tx.Hash()[:]) // Check if the filter matches any data elements in the public key // scripts of any of the outputs. When it does, add the outpoint that // matched so transactions which spend from the matched transaction are // also included in the filter. This removes the burden of updating the // filter for this scenario from the client. It is also more efficient // on the network since it avoids the need for another filteradd message // from the client and avoids some potential races that could otherwise // occur. for i, txOut := range tx.MsgTx().TxOut { pushedData, err := txscript.PushedData(txOut.PkScript) if err != nil { continue } for _, data := range pushedData { if !bf.matches(data) { continue } matched = true bf.maybeAddOutpoint(txOut.PkScript, tx.Hash(), uint32(i)) break } } // Nothing more to do if a match has already been made. if matched { return true } // At this point, the transaction and none of the data elements in the // public key scripts of its outputs matched. // Check if the filter matches any outpoints this transaction spends or // any any data elements in the signature scripts of any of the inputs. for _, txin := range tx.MsgTx().TxIn { if bf.matchesOutPoint(&txin.PreviousOutPoint) { return true } pushedData, err := txscript.PushedData(txin.SignatureScript) if err != nil { continue } for _, data := range pushedData { if bf.matches(data) { return true } } } return false }
[ "func", "(", "bf", "*", "Filter", ")", "matchTxAndUpdate", "(", "tx", "*", "btcutil", ".", "Tx", ")", "bool", "{", "// Check if the filter matches the hash of the transaction.", "// This is useful for finding transactions when they appear in a block.", "matched", ":=", "bf", ".", "matches", "(", "tx", ".", "Hash", "(", ")", "[", ":", "]", ")", "\n\n", "// Check if the filter matches any data elements in the public key", "// scripts of any of the outputs. When it does, add the outpoint that", "// matched so transactions which spend from the matched transaction are", "// also included in the filter. This removes the burden of updating the", "// filter for this scenario from the client. It is also more efficient", "// on the network since it avoids the need for another filteradd message", "// from the client and avoids some potential races that could otherwise", "// occur.", "for", "i", ",", "txOut", ":=", "range", "tx", ".", "MsgTx", "(", ")", ".", "TxOut", "{", "pushedData", ",", "err", ":=", "txscript", ".", "PushedData", "(", "txOut", ".", "PkScript", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n\n", "for", "_", ",", "data", ":=", "range", "pushedData", "{", "if", "!", "bf", ".", "matches", "(", "data", ")", "{", "continue", "\n", "}", "\n\n", "matched", "=", "true", "\n", "bf", ".", "maybeAddOutpoint", "(", "txOut", ".", "PkScript", ",", "tx", ".", "Hash", "(", ")", ",", "uint32", "(", "i", ")", ")", "\n", "break", "\n", "}", "\n", "}", "\n\n", "// Nothing more to do if a match has already been made.", "if", "matched", "{", "return", "true", "\n", "}", "\n\n", "// At this point, the transaction and none of the data elements in the", "// public key scripts of its outputs matched.", "// Check if the filter matches any outpoints this transaction spends or", "// any any data elements in the signature scripts of any of the inputs.", "for", "_", ",", "txin", ":=", "range", "tx", ".", "MsgTx", "(", ")", ".", "TxIn", "{", "if", "bf", ".", "matchesOutPoint", "(", "&", "txin", ".", "PreviousOutPoint", ")", "{", "return", "true", "\n", "}", "\n\n", "pushedData", ",", "err", ":=", "txscript", ".", "PushedData", "(", "txin", ".", "SignatureScript", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "for", "_", ",", "data", ":=", "range", "pushedData", "{", "if", "bf", ".", "matches", "(", "data", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// matchTxAndUpdate returns true if the bloom filter matches data within the // passed transaction, otherwise false is returned. If the filter does match // the passed transaction, it will also update the filter depending on the bloom // update flags set via the loaded filter if needed. // // This function MUST be called with the filter lock held.
[ "matchTxAndUpdate", "returns", "true", "if", "the", "bloom", "filter", "matches", "data", "within", "the", "passed", "transaction", "otherwise", "false", "is", "returned", ".", "If", "the", "filter", "does", "match", "the", "passed", "transaction", "it", "will", "also", "update", "the", "filter", "depending", "on", "the", "bloom", "update", "flags", "set", "via", "the", "loaded", "filter", "if", "needed", ".", "This", "function", "MUST", "be", "called", "with", "the", "filter", "lock", "held", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/bloom/filter.go#L273-L330
149,545
btcsuite/btcutil
bloom/filter.go
MatchTxAndUpdate
func (bf *Filter) MatchTxAndUpdate(tx *btcutil.Tx) bool { bf.mtx.Lock() match := bf.matchTxAndUpdate(tx) bf.mtx.Unlock() return match }
go
func (bf *Filter) MatchTxAndUpdate(tx *btcutil.Tx) bool { bf.mtx.Lock() match := bf.matchTxAndUpdate(tx) bf.mtx.Unlock() return match }
[ "func", "(", "bf", "*", "Filter", ")", "MatchTxAndUpdate", "(", "tx", "*", "btcutil", ".", "Tx", ")", "bool", "{", "bf", ".", "mtx", ".", "Lock", "(", ")", "\n", "match", ":=", "bf", ".", "matchTxAndUpdate", "(", "tx", ")", "\n", "bf", ".", "mtx", ".", "Unlock", "(", ")", "\n", "return", "match", "\n", "}" ]
// MatchTxAndUpdate returns true if the bloom filter matches data within the // passed transaction, otherwise false is returned. If the filter does match // the passed transaction, it will also update the filter depending on the bloom // update flags set via the loaded filter if needed. // // This function is safe for concurrent access.
[ "MatchTxAndUpdate", "returns", "true", "if", "the", "bloom", "filter", "matches", "data", "within", "the", "passed", "transaction", "otherwise", "false", "is", "returned", ".", "If", "the", "filter", "does", "match", "the", "passed", "transaction", "it", "will", "also", "update", "the", "filter", "depending", "on", "the", "bloom", "update", "flags", "set", "via", "the", "loaded", "filter", "if", "needed", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/bloom/filter.go#L338-L343
149,546
btcsuite/btcutil
bloom/filter.go
MsgFilterLoad
func (bf *Filter) MsgFilterLoad() *wire.MsgFilterLoad { bf.mtx.Lock() msg := bf.msgFilterLoad bf.mtx.Unlock() return msg }
go
func (bf *Filter) MsgFilterLoad() *wire.MsgFilterLoad { bf.mtx.Lock() msg := bf.msgFilterLoad bf.mtx.Unlock() return msg }
[ "func", "(", "bf", "*", "Filter", ")", "MsgFilterLoad", "(", ")", "*", "wire", ".", "MsgFilterLoad", "{", "bf", ".", "mtx", ".", "Lock", "(", ")", "\n", "msg", ":=", "bf", ".", "msgFilterLoad", "\n", "bf", ".", "mtx", ".", "Unlock", "(", ")", "\n", "return", "msg", "\n", "}" ]
// MsgFilterLoad returns the underlying wire.MsgFilterLoad for the bloom // filter. // // This function is safe for concurrent access.
[ "MsgFilterLoad", "returns", "the", "underlying", "wire", ".", "MsgFilterLoad", "for", "the", "bloom", "filter", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/bloom/filter.go#L349-L354
149,547
btcsuite/btcutil
amount.go
String
func (u AmountUnit) String() string { switch u { case AmountMegaBTC: return "MBTC" case AmountKiloBTC: return "kBTC" case AmountBTC: return "BTC" case AmountMilliBTC: return "mBTC" case AmountMicroBTC: return "μBTC" case AmountSatoshi: return "Satoshi" default: return "1e" + strconv.FormatInt(int64(u), 10) + " BTC" } }
go
func (u AmountUnit) String() string { switch u { case AmountMegaBTC: return "MBTC" case AmountKiloBTC: return "kBTC" case AmountBTC: return "BTC" case AmountMilliBTC: return "mBTC" case AmountMicroBTC: return "μBTC" case AmountSatoshi: return "Satoshi" default: return "1e" + strconv.FormatInt(int64(u), 10) + " BTC" } }
[ "func", "(", "u", "AmountUnit", ")", "String", "(", ")", "string", "{", "switch", "u", "{", "case", "AmountMegaBTC", ":", "return", "\"", "\"", "\n", "case", "AmountKiloBTC", ":", "return", "\"", "\"", "\n", "case", "AmountBTC", ":", "return", "\"", "\"", "\n", "case", "AmountMilliBTC", ":", "return", "\"", "\"", "\n", "case", "AmountMicroBTC", ":", "return", "\"", "", "\n", "case", "AmountSatoshi", ":", "return", "\"", "\"", "\n", "default", ":", "return", "\"", "\"", "+", "strconv", ".", "FormatInt", "(", "int64", "(", "u", ")", ",", "10", ")", "+", "\"", "\"", "\n", "}", "\n", "}" ]
// String returns the unit as a string. For recognized units, the SI // prefix is used, or "Satoshi" for the base unit. For all unrecognized // units, "1eN BTC" is returned, where N is the AmountUnit.
[ "String", "returns", "the", "unit", "as", "a", "string", ".", "For", "recognized", "units", "the", "SI", "prefix", "is", "used", "or", "Satoshi", "for", "the", "base", "unit", ".", "For", "all", "unrecognized", "units", "1eN", "BTC", "is", "returned", "where", "N", "is", "the", "AmountUnit", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/amount.go#L33-L50
149,548
btcsuite/btcutil
amount.go
ToUnit
func (a Amount) ToUnit(u AmountUnit) float64 { return float64(a) / math.Pow10(int(u+8)) }
go
func (a Amount) ToUnit(u AmountUnit) float64 { return float64(a) / math.Pow10(int(u+8)) }
[ "func", "(", "a", "Amount", ")", "ToUnit", "(", "u", "AmountUnit", ")", "float64", "{", "return", "float64", "(", "a", ")", "/", "math", ".", "Pow10", "(", "int", "(", "u", "+", "8", ")", ")", "\n", "}" ]
// ToUnit converts a monetary amount counted in bitcoin base units to a // floating point value representing an amount of bitcoin.
[ "ToUnit", "converts", "a", "monetary", "amount", "counted", "in", "bitcoin", "base", "units", "to", "a", "floating", "point", "value", "representing", "an", "amount", "of", "bitcoin", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/amount.go#L93-L95
149,549
btcsuite/btcutil
amount.go
Format
func (a Amount) Format(u AmountUnit) string { units := " " + u.String() return strconv.FormatFloat(a.ToUnit(u), 'f', -int(u+8), 64) + units }
go
func (a Amount) Format(u AmountUnit) string { units := " " + u.String() return strconv.FormatFloat(a.ToUnit(u), 'f', -int(u+8), 64) + units }
[ "func", "(", "a", "Amount", ")", "Format", "(", "u", "AmountUnit", ")", "string", "{", "units", ":=", "\"", "\"", "+", "u", ".", "String", "(", ")", "\n", "return", "strconv", ".", "FormatFloat", "(", "a", ".", "ToUnit", "(", "u", ")", ",", "'f'", ",", "-", "int", "(", "u", "+", "8", ")", ",", "64", ")", "+", "units", "\n", "}" ]
// Format formats a monetary amount counted in bitcoin base units as a // string for a given unit. The conversion will succeed for any unit, // however, known units will be formated with an appended label describing // the units with SI notation, or "Satoshi" for the base unit.
[ "Format", "formats", "a", "monetary", "amount", "counted", "in", "bitcoin", "base", "units", "as", "a", "string", "for", "a", "given", "unit", ".", "The", "conversion", "will", "succeed", "for", "any", "unit", "however", "known", "units", "will", "be", "formated", "with", "an", "appended", "label", "describing", "the", "units", "with", "SI", "notation", "or", "Satoshi", "for", "the", "base", "unit", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/amount.go#L106-L109
149,550
btcsuite/btcutil
bloom/merkleblock.go
calcHash
func (m *merkleBlock) calcHash(height, pos uint32) *chainhash.Hash { if height == 0 { return m.allHashes[pos] } var right *chainhash.Hash left := m.calcHash(height-1, pos*2) if pos*2+1 < m.calcTreeWidth(height-1) { right = m.calcHash(height-1, pos*2+1) } else { right = left } return blockchain.HashMerkleBranches(left, right) }
go
func (m *merkleBlock) calcHash(height, pos uint32) *chainhash.Hash { if height == 0 { return m.allHashes[pos] } var right *chainhash.Hash left := m.calcHash(height-1, pos*2) if pos*2+1 < m.calcTreeWidth(height-1) { right = m.calcHash(height-1, pos*2+1) } else { right = left } return blockchain.HashMerkleBranches(left, right) }
[ "func", "(", "m", "*", "merkleBlock", ")", "calcHash", "(", "height", ",", "pos", "uint32", ")", "*", "chainhash", ".", "Hash", "{", "if", "height", "==", "0", "{", "return", "m", ".", "allHashes", "[", "pos", "]", "\n", "}", "\n\n", "var", "right", "*", "chainhash", ".", "Hash", "\n", "left", ":=", "m", ".", "calcHash", "(", "height", "-", "1", ",", "pos", "*", "2", ")", "\n", "if", "pos", "*", "2", "+", "1", "<", "m", ".", "calcTreeWidth", "(", "height", "-", "1", ")", "{", "right", "=", "m", ".", "calcHash", "(", "height", "-", "1", ",", "pos", "*", "2", "+", "1", ")", "\n", "}", "else", "{", "right", "=", "left", "\n", "}", "\n", "return", "blockchain", ".", "HashMerkleBranches", "(", "left", ",", "right", ")", "\n", "}" ]
// calcHash returns the hash for a sub-tree given a depth-first height and // node position.
[ "calcHash", "returns", "the", "hash", "for", "a", "sub", "-", "tree", "given", "a", "depth", "-", "first", "height", "and", "node", "position", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/bloom/merkleblock.go#L32-L45
149,551
btcsuite/btcutil
bloom/merkleblock.go
traverseAndBuild
func (m *merkleBlock) traverseAndBuild(height, pos uint32) { // Determine whether this node is a parent of a matched node. var isParent byte for i := pos << height; i < (pos+1)<<height && i < m.numTx; i++ { isParent |= m.matchedBits[i] } m.bits = append(m.bits, isParent) // When the node is a leaf node or not a parent of a matched node, // append the hash to the list that will be part of the final merkle // block. if height == 0 || isParent == 0x00 { m.finalHashes = append(m.finalHashes, m.calcHash(height, pos)) return } // At this point, the node is an internal node and it is the parent of // of an included leaf node. // Descend into the left child and process its sub-tree. m.traverseAndBuild(height-1, pos*2) // Descend into the right child and process its sub-tree if // there is one. if pos*2+1 < m.calcTreeWidth(height-1) { m.traverseAndBuild(height-1, pos*2+1) } }
go
func (m *merkleBlock) traverseAndBuild(height, pos uint32) { // Determine whether this node is a parent of a matched node. var isParent byte for i := pos << height; i < (pos+1)<<height && i < m.numTx; i++ { isParent |= m.matchedBits[i] } m.bits = append(m.bits, isParent) // When the node is a leaf node or not a parent of a matched node, // append the hash to the list that will be part of the final merkle // block. if height == 0 || isParent == 0x00 { m.finalHashes = append(m.finalHashes, m.calcHash(height, pos)) return } // At this point, the node is an internal node and it is the parent of // of an included leaf node. // Descend into the left child and process its sub-tree. m.traverseAndBuild(height-1, pos*2) // Descend into the right child and process its sub-tree if // there is one. if pos*2+1 < m.calcTreeWidth(height-1) { m.traverseAndBuild(height-1, pos*2+1) } }
[ "func", "(", "m", "*", "merkleBlock", ")", "traverseAndBuild", "(", "height", ",", "pos", "uint32", ")", "{", "// Determine whether this node is a parent of a matched node.", "var", "isParent", "byte", "\n", "for", "i", ":=", "pos", "<<", "height", ";", "i", "<", "(", "pos", "+", "1", ")", "<<", "height", "&&", "i", "<", "m", ".", "numTx", ";", "i", "++", "{", "isParent", "|=", "m", ".", "matchedBits", "[", "i", "]", "\n", "}", "\n", "m", ".", "bits", "=", "append", "(", "m", ".", "bits", ",", "isParent", ")", "\n\n", "// When the node is a leaf node or not a parent of a matched node,", "// append the hash to the list that will be part of the final merkle", "// block.", "if", "height", "==", "0", "||", "isParent", "==", "0x00", "{", "m", ".", "finalHashes", "=", "append", "(", "m", ".", "finalHashes", ",", "m", ".", "calcHash", "(", "height", ",", "pos", ")", ")", "\n", "return", "\n", "}", "\n\n", "// At this point, the node is an internal node and it is the parent of", "// of an included leaf node.", "// Descend into the left child and process its sub-tree.", "m", ".", "traverseAndBuild", "(", "height", "-", "1", ",", "pos", "*", "2", ")", "\n\n", "// Descend into the right child and process its sub-tree if", "// there is one.", "if", "pos", "*", "2", "+", "1", "<", "m", ".", "calcTreeWidth", "(", "height", "-", "1", ")", "{", "m", ".", "traverseAndBuild", "(", "height", "-", "1", ",", "pos", "*", "2", "+", "1", ")", "\n", "}", "\n", "}" ]
// traverseAndBuild builds a partial merkle tree using a recursive depth-first // approach. As it calculates the hashes, it also saves whether or not each // node is a parent node and a list of final hashes to be included in the // merkle block.
[ "traverseAndBuild", "builds", "a", "partial", "merkle", "tree", "using", "a", "recursive", "depth", "-", "first", "approach", ".", "As", "it", "calculates", "the", "hashes", "it", "also", "saves", "whether", "or", "not", "each", "node", "is", "a", "parent", "node", "and", "a", "list", "of", "final", "hashes", "to", "be", "included", "in", "the", "merkle", "block", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/bloom/merkleblock.go#L51-L78
149,552
btcsuite/btcutil
address.go
encodeSegWitAddress
func encodeSegWitAddress(hrp string, witnessVersion byte, witnessProgram []byte) (string, error) { // Group the address bytes into 5 bit groups, as this is what is used to // encode each character in the address string. converted, err := bech32.ConvertBits(witnessProgram, 8, 5, true) if err != nil { return "", err } // Concatenate the witness version and program, and encode the resulting // bytes using bech32 encoding. combined := make([]byte, len(converted)+1) combined[0] = witnessVersion copy(combined[1:], converted) bech, err := bech32.Encode(hrp, combined) if err != nil { return "", err } // Check validity by decoding the created address. version, program, err := decodeSegWitAddress(bech) if err != nil { return "", fmt.Errorf("invalid segwit address: %v", err) } if version != witnessVersion || !bytes.Equal(program, witnessProgram) { return "", fmt.Errorf("invalid segwit address") } return bech, nil }
go
func encodeSegWitAddress(hrp string, witnessVersion byte, witnessProgram []byte) (string, error) { // Group the address bytes into 5 bit groups, as this is what is used to // encode each character in the address string. converted, err := bech32.ConvertBits(witnessProgram, 8, 5, true) if err != nil { return "", err } // Concatenate the witness version and program, and encode the resulting // bytes using bech32 encoding. combined := make([]byte, len(converted)+1) combined[0] = witnessVersion copy(combined[1:], converted) bech, err := bech32.Encode(hrp, combined) if err != nil { return "", err } // Check validity by decoding the created address. version, program, err := decodeSegWitAddress(bech) if err != nil { return "", fmt.Errorf("invalid segwit address: %v", err) } if version != witnessVersion || !bytes.Equal(program, witnessProgram) { return "", fmt.Errorf("invalid segwit address") } return bech, nil }
[ "func", "encodeSegWitAddress", "(", "hrp", "string", ",", "witnessVersion", "byte", ",", "witnessProgram", "[", "]", "byte", ")", "(", "string", ",", "error", ")", "{", "// Group the address bytes into 5 bit groups, as this is what is used to", "// encode each character in the address string.", "converted", ",", "err", ":=", "bech32", ".", "ConvertBits", "(", "witnessProgram", ",", "8", ",", "5", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "// Concatenate the witness version and program, and encode the resulting", "// bytes using bech32 encoding.", "combined", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "converted", ")", "+", "1", ")", "\n", "combined", "[", "0", "]", "=", "witnessVersion", "\n", "copy", "(", "combined", "[", "1", ":", "]", ",", "converted", ")", "\n", "bech", ",", "err", ":=", "bech32", ".", "Encode", "(", "hrp", ",", "combined", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "// Check validity by decoding the created address.", "version", ",", "program", ",", "err", ":=", "decodeSegWitAddress", "(", "bech", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "version", "!=", "witnessVersion", "||", "!", "bytes", ".", "Equal", "(", "program", ",", "witnessProgram", ")", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "bech", ",", "nil", "\n", "}" ]
// encodeSegWitAddress creates a bech32 encoded address string representation // from witness version and witness program.
[ "encodeSegWitAddress", "creates", "a", "bech32", "encoded", "address", "string", "representation", "from", "witness", "version", "and", "witness", "program", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/address.go#L69-L98
149,553
btcsuite/btcutil
address.go
decodeSegWitAddress
func decodeSegWitAddress(address string) (byte, []byte, error) { // Decode the bech32 encoded address. _, data, err := bech32.Decode(address) if err != nil { return 0, nil, err } // The first byte of the decoded address is the witness version, it must // exist. if len(data) < 1 { return 0, nil, fmt.Errorf("no witness version") } // ...and be <= 16. version := data[0] if version > 16 { return 0, nil, fmt.Errorf("invalid witness version: %v", version) } // The remaining characters of the address returned are grouped into // words of 5 bits. In order to restore the original witness program // bytes, we'll need to regroup into 8 bit words. regrouped, err := bech32.ConvertBits(data[1:], 5, 8, false) if err != nil { return 0, nil, err } // The regrouped data must be between 2 and 40 bytes. if len(regrouped) < 2 || len(regrouped) > 40 { return 0, nil, fmt.Errorf("invalid data length") } // For witness version 0, address MUST be exactly 20 or 32 bytes. if version == 0 && len(regrouped) != 20 && len(regrouped) != 32 { return 0, nil, fmt.Errorf("invalid data length for witness "+ "version 0: %v", len(regrouped)) } return version, regrouped, nil }
go
func decodeSegWitAddress(address string) (byte, []byte, error) { // Decode the bech32 encoded address. _, data, err := bech32.Decode(address) if err != nil { return 0, nil, err } // The first byte of the decoded address is the witness version, it must // exist. if len(data) < 1 { return 0, nil, fmt.Errorf("no witness version") } // ...and be <= 16. version := data[0] if version > 16 { return 0, nil, fmt.Errorf("invalid witness version: %v", version) } // The remaining characters of the address returned are grouped into // words of 5 bits. In order to restore the original witness program // bytes, we'll need to regroup into 8 bit words. regrouped, err := bech32.ConvertBits(data[1:], 5, 8, false) if err != nil { return 0, nil, err } // The regrouped data must be between 2 and 40 bytes. if len(regrouped) < 2 || len(regrouped) > 40 { return 0, nil, fmt.Errorf("invalid data length") } // For witness version 0, address MUST be exactly 20 or 32 bytes. if version == 0 && len(regrouped) != 20 && len(regrouped) != 32 { return 0, nil, fmt.Errorf("invalid data length for witness "+ "version 0: %v", len(regrouped)) } return version, regrouped, nil }
[ "func", "decodeSegWitAddress", "(", "address", "string", ")", "(", "byte", ",", "[", "]", "byte", ",", "error", ")", "{", "// Decode the bech32 encoded address.", "_", ",", "data", ",", "err", ":=", "bech32", ".", "Decode", "(", "address", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "nil", ",", "err", "\n", "}", "\n\n", "// The first byte of the decoded address is the witness version, it must", "// exist.", "if", "len", "(", "data", ")", "<", "1", "{", "return", "0", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// ...and be <= 16.", "version", ":=", "data", "[", "0", "]", "\n", "if", "version", ">", "16", "{", "return", "0", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "version", ")", "\n", "}", "\n\n", "// The remaining characters of the address returned are grouped into", "// words of 5 bits. In order to restore the original witness program", "// bytes, we'll need to regroup into 8 bit words.", "regrouped", ",", "err", ":=", "bech32", ".", "ConvertBits", "(", "data", "[", "1", ":", "]", ",", "5", ",", "8", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "nil", ",", "err", "\n", "}", "\n\n", "// The regrouped data must be between 2 and 40 bytes.", "if", "len", "(", "regrouped", ")", "<", "2", "||", "len", "(", "regrouped", ")", ">", "40", "{", "return", "0", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// For witness version 0, address MUST be exactly 20 or 32 bytes.", "if", "version", "==", "0", "&&", "len", "(", "regrouped", ")", "!=", "20", "&&", "len", "(", "regrouped", ")", "!=", "32", "{", "return", "0", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "len", "(", "regrouped", ")", ")", "\n", "}", "\n\n", "return", "version", ",", "regrouped", ",", "nil", "\n", "}" ]
// decodeSegWitAddress parses a bech32 encoded segwit address string and // returns the witness version and witness program byte representation.
[ "decodeSegWitAddress", "parses", "a", "bech32", "encoded", "segwit", "address", "string", "and", "returns", "the", "witness", "version", "and", "witness", "program", "byte", "representation", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/address.go#L211-L250
149,554
btcsuite/btcutil
address.go
NewAddressPubKeyHash
func NewAddressPubKeyHash(pkHash []byte, net *chaincfg.Params) (*AddressPubKeyHash, error) { return newAddressPubKeyHash(pkHash, net.PubKeyHashAddrID) }
go
func NewAddressPubKeyHash(pkHash []byte, net *chaincfg.Params) (*AddressPubKeyHash, error) { return newAddressPubKeyHash(pkHash, net.PubKeyHashAddrID) }
[ "func", "NewAddressPubKeyHash", "(", "pkHash", "[", "]", "byte", ",", "net", "*", "chaincfg", ".", "Params", ")", "(", "*", "AddressPubKeyHash", ",", "error", ")", "{", "return", "newAddressPubKeyHash", "(", "pkHash", ",", "net", ".", "PubKeyHashAddrID", ")", "\n", "}" ]
// NewAddressPubKeyHash returns a new AddressPubKeyHash. pkHash mustbe 20 // bytes.
[ "NewAddressPubKeyHash", "returns", "a", "new", "AddressPubKeyHash", ".", "pkHash", "mustbe", "20", "bytes", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/address.go#L261-L263
149,555
btcsuite/btcutil
address.go
newAddressPubKeyHash
func newAddressPubKeyHash(pkHash []byte, netID byte) (*AddressPubKeyHash, error) { // Check for a valid pubkey hash length. if len(pkHash) != ripemd160.Size { return nil, errors.New("pkHash must be 20 bytes") } addr := &AddressPubKeyHash{netID: netID} copy(addr.hash[:], pkHash) return addr, nil }
go
func newAddressPubKeyHash(pkHash []byte, netID byte) (*AddressPubKeyHash, error) { // Check for a valid pubkey hash length. if len(pkHash) != ripemd160.Size { return nil, errors.New("pkHash must be 20 bytes") } addr := &AddressPubKeyHash{netID: netID} copy(addr.hash[:], pkHash) return addr, nil }
[ "func", "newAddressPubKeyHash", "(", "pkHash", "[", "]", "byte", ",", "netID", "byte", ")", "(", "*", "AddressPubKeyHash", ",", "error", ")", "{", "// Check for a valid pubkey hash length.", "if", "len", "(", "pkHash", ")", "!=", "ripemd160", ".", "Size", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "addr", ":=", "&", "AddressPubKeyHash", "{", "netID", ":", "netID", "}", "\n", "copy", "(", "addr", ".", "hash", "[", ":", "]", ",", "pkHash", ")", "\n", "return", "addr", ",", "nil", "\n", "}" ]
// newAddressPubKeyHash is the internal API to create a pubkey hash address // with a known leading identifier byte for a network, rather than looking // it up through its parameters. This is useful when creating a new address // structure from a string encoding where the identifer byte is already // known.
[ "newAddressPubKeyHash", "is", "the", "internal", "API", "to", "create", "a", "pubkey", "hash", "address", "with", "a", "known", "leading", "identifier", "byte", "for", "a", "network", "rather", "than", "looking", "it", "up", "through", "its", "parameters", ".", "This", "is", "useful", "when", "creating", "a", "new", "address", "structure", "from", "a", "string", "encoding", "where", "the", "identifer", "byte", "is", "already", "known", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/address.go#L270-L279
149,556
btcsuite/btcutil
address.go
IsForNet
func (a *AddressPubKeyHash) IsForNet(net *chaincfg.Params) bool { return a.netID == net.PubKeyHashAddrID }
go
func (a *AddressPubKeyHash) IsForNet(net *chaincfg.Params) bool { return a.netID == net.PubKeyHashAddrID }
[ "func", "(", "a", "*", "AddressPubKeyHash", ")", "IsForNet", "(", "net", "*", "chaincfg", ".", "Params", ")", "bool", "{", "return", "a", ".", "netID", "==", "net", ".", "PubKeyHashAddrID", "\n", "}" ]
// IsForNet returns whether or not the pay-to-pubkey-hash address is associated // with the passed bitcoin network.
[ "IsForNet", "returns", "whether", "or", "not", "the", "pay", "-", "to", "-", "pubkey", "-", "hash", "address", "is", "associated", "with", "the", "passed", "bitcoin", "network", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/address.go#L295-L297
149,557
btcsuite/btcutil
address.go
NewAddressScriptHash
func NewAddressScriptHash(serializedScript []byte, net *chaincfg.Params) (*AddressScriptHash, error) { scriptHash := Hash160(serializedScript) return newAddressScriptHashFromHash(scriptHash, net.ScriptHashAddrID) }
go
func NewAddressScriptHash(serializedScript []byte, net *chaincfg.Params) (*AddressScriptHash, error) { scriptHash := Hash160(serializedScript) return newAddressScriptHashFromHash(scriptHash, net.ScriptHashAddrID) }
[ "func", "NewAddressScriptHash", "(", "serializedScript", "[", "]", "byte", ",", "net", "*", "chaincfg", ".", "Params", ")", "(", "*", "AddressScriptHash", ",", "error", ")", "{", "scriptHash", ":=", "Hash160", "(", "serializedScript", ")", "\n", "return", "newAddressScriptHashFromHash", "(", "scriptHash", ",", "net", ".", "ScriptHashAddrID", ")", "\n", "}" ]
// NewAddressScriptHash returns a new AddressScriptHash.
[ "NewAddressScriptHash", "returns", "a", "new", "AddressScriptHash", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/address.go#L321-L324
149,558
btcsuite/btcutil
address.go
NewAddressScriptHashFromHash
func NewAddressScriptHashFromHash(scriptHash []byte, net *chaincfg.Params) (*AddressScriptHash, error) { return newAddressScriptHashFromHash(scriptHash, net.ScriptHashAddrID) }
go
func NewAddressScriptHashFromHash(scriptHash []byte, net *chaincfg.Params) (*AddressScriptHash, error) { return newAddressScriptHashFromHash(scriptHash, net.ScriptHashAddrID) }
[ "func", "NewAddressScriptHashFromHash", "(", "scriptHash", "[", "]", "byte", ",", "net", "*", "chaincfg", ".", "Params", ")", "(", "*", "AddressScriptHash", ",", "error", ")", "{", "return", "newAddressScriptHashFromHash", "(", "scriptHash", ",", "net", ".", "ScriptHashAddrID", ")", "\n", "}" ]
// NewAddressScriptHashFromHash returns a new AddressScriptHash. scriptHash // must be 20 bytes.
[ "NewAddressScriptHashFromHash", "returns", "a", "new", "AddressScriptHash", ".", "scriptHash", "must", "be", "20", "bytes", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/address.go#L328-L330
149,559
btcsuite/btcutil
address.go
newAddressScriptHashFromHash
func newAddressScriptHashFromHash(scriptHash []byte, netID byte) (*AddressScriptHash, error) { // Check for a valid script hash length. if len(scriptHash) != ripemd160.Size { return nil, errors.New("scriptHash must be 20 bytes") } addr := &AddressScriptHash{netID: netID} copy(addr.hash[:], scriptHash) return addr, nil }
go
func newAddressScriptHashFromHash(scriptHash []byte, netID byte) (*AddressScriptHash, error) { // Check for a valid script hash length. if len(scriptHash) != ripemd160.Size { return nil, errors.New("scriptHash must be 20 bytes") } addr := &AddressScriptHash{netID: netID} copy(addr.hash[:], scriptHash) return addr, nil }
[ "func", "newAddressScriptHashFromHash", "(", "scriptHash", "[", "]", "byte", ",", "netID", "byte", ")", "(", "*", "AddressScriptHash", ",", "error", ")", "{", "// Check for a valid script hash length.", "if", "len", "(", "scriptHash", ")", "!=", "ripemd160", ".", "Size", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "addr", ":=", "&", "AddressScriptHash", "{", "netID", ":", "netID", "}", "\n", "copy", "(", "addr", ".", "hash", "[", ":", "]", ",", "scriptHash", ")", "\n", "return", "addr", ",", "nil", "\n", "}" ]
// newAddressScriptHashFromHash is the internal API to create a script hash // address with a known leading identifier byte for a network, rather than // looking it up through its parameters. This is useful when creating a new // address structure from a string encoding where the identifer byte is already // known.
[ "newAddressScriptHashFromHash", "is", "the", "internal", "API", "to", "create", "a", "script", "hash", "address", "with", "a", "known", "leading", "identifier", "byte", "for", "a", "network", "rather", "than", "looking", "it", "up", "through", "its", "parameters", ".", "This", "is", "useful", "when", "creating", "a", "new", "address", "structure", "from", "a", "string", "encoding", "where", "the", "identifer", "byte", "is", "already", "known", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/address.go#L337-L346
149,560
btcsuite/btcutil
address.go
IsForNet
func (a *AddressScriptHash) IsForNet(net *chaincfg.Params) bool { return a.netID == net.ScriptHashAddrID }
go
func (a *AddressScriptHash) IsForNet(net *chaincfg.Params) bool { return a.netID == net.ScriptHashAddrID }
[ "func", "(", "a", "*", "AddressScriptHash", ")", "IsForNet", "(", "net", "*", "chaincfg", ".", "Params", ")", "bool", "{", "return", "a", ".", "netID", "==", "net", ".", "ScriptHashAddrID", "\n", "}" ]
// IsForNet returns whether or not the pay-to-script-hash address is associated // with the passed bitcoin network.
[ "IsForNet", "returns", "whether", "or", "not", "the", "pay", "-", "to", "-", "script", "-", "hash", "address", "is", "associated", "with", "the", "passed", "bitcoin", "network", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/address.go#L362-L364
149,561
btcsuite/btcutil
address.go
serialize
func (a *AddressPubKey) serialize() []byte { switch a.pubKeyFormat { default: fallthrough case PKFUncompressed: return a.pubKey.SerializeUncompressed() case PKFCompressed: return a.pubKey.SerializeCompressed() case PKFHybrid: return a.pubKey.SerializeHybrid() } }
go
func (a *AddressPubKey) serialize() []byte { switch a.pubKeyFormat { default: fallthrough case PKFUncompressed: return a.pubKey.SerializeUncompressed() case PKFCompressed: return a.pubKey.SerializeCompressed() case PKFHybrid: return a.pubKey.SerializeHybrid() } }
[ "func", "(", "a", "*", "AddressPubKey", ")", "serialize", "(", ")", "[", "]", "byte", "{", "switch", "a", ".", "pubKeyFormat", "{", "default", ":", "fallthrough", "\n", "case", "PKFUncompressed", ":", "return", "a", ".", "pubKey", ".", "SerializeUncompressed", "(", ")", "\n\n", "case", "PKFCompressed", ":", "return", "a", ".", "pubKey", ".", "SerializeCompressed", "(", ")", "\n\n", "case", "PKFHybrid", ":", "return", "a", ".", "pubKey", ".", "SerializeHybrid", "(", ")", "\n", "}", "\n", "}" ]
// serialize returns the serialization of the public key according to the // format associated with the address.
[ "serialize", "returns", "the", "serialization", "of", "the", "public", "key", "according", "to", "the", "format", "associated", "with", "the", "address", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/address.go#L434-L447
149,562
btcsuite/btcutil
address.go
IsForNet
func (a *AddressPubKey) IsForNet(net *chaincfg.Params) bool { return a.pubKeyHashID == net.PubKeyHashAddrID }
go
func (a *AddressPubKey) IsForNet(net *chaincfg.Params) bool { return a.pubKeyHashID == net.PubKeyHashAddrID }
[ "func", "(", "a", "*", "AddressPubKey", ")", "IsForNet", "(", "net", "*", "chaincfg", ".", "Params", ")", "bool", "{", "return", "a", ".", "pubKeyHashID", "==", "net", ".", "PubKeyHashAddrID", "\n", "}" ]
// IsForNet returns whether or not the pay-to-pubkey address is associated // with the passed bitcoin network.
[ "IsForNet", "returns", "whether", "or", "not", "the", "pay", "-", "to", "-", "pubkey", "address", "is", "associated", "with", "the", "passed", "bitcoin", "network", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/address.go#L470-L472
149,563
btcsuite/btcutil
address.go
NewAddressWitnessPubKeyHash
func NewAddressWitnessPubKeyHash(witnessProg []byte, net *chaincfg.Params) (*AddressWitnessPubKeyHash, error) { return newAddressWitnessPubKeyHash(net.Bech32HRPSegwit, witnessProg) }
go
func NewAddressWitnessPubKeyHash(witnessProg []byte, net *chaincfg.Params) (*AddressWitnessPubKeyHash, error) { return newAddressWitnessPubKeyHash(net.Bech32HRPSegwit, witnessProg) }
[ "func", "NewAddressWitnessPubKeyHash", "(", "witnessProg", "[", "]", "byte", ",", "net", "*", "chaincfg", ".", "Params", ")", "(", "*", "AddressWitnessPubKeyHash", ",", "error", ")", "{", "return", "newAddressWitnessPubKeyHash", "(", "net", ".", "Bech32HRPSegwit", ",", "witnessProg", ")", "\n", "}" ]
// NewAddressWitnessPubKeyHash returns a new AddressWitnessPubKeyHash.
[ "NewAddressWitnessPubKeyHash", "returns", "a", "new", "AddressWitnessPubKeyHash", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/address.go#L520-L522
149,564
btcsuite/btcutil
address.go
newAddressWitnessPubKeyHash
func newAddressWitnessPubKeyHash(hrp string, witnessProg []byte) (*AddressWitnessPubKeyHash, error) { // Check for valid program length for witness version 0, which is 20 // for P2WPKH. if len(witnessProg) != 20 { return nil, errors.New("witness program must be 20 " + "bytes for p2wpkh") } addr := &AddressWitnessPubKeyHash{ hrp: strings.ToLower(hrp), witnessVersion: 0x00, } copy(addr.witnessProgram[:], witnessProg) return addr, nil }
go
func newAddressWitnessPubKeyHash(hrp string, witnessProg []byte) (*AddressWitnessPubKeyHash, error) { // Check for valid program length for witness version 0, which is 20 // for P2WPKH. if len(witnessProg) != 20 { return nil, errors.New("witness program must be 20 " + "bytes for p2wpkh") } addr := &AddressWitnessPubKeyHash{ hrp: strings.ToLower(hrp), witnessVersion: 0x00, } copy(addr.witnessProgram[:], witnessProg) return addr, nil }
[ "func", "newAddressWitnessPubKeyHash", "(", "hrp", "string", ",", "witnessProg", "[", "]", "byte", ")", "(", "*", "AddressWitnessPubKeyHash", ",", "error", ")", "{", "// Check for valid program length for witness version 0, which is 20", "// for P2WPKH.", "if", "len", "(", "witnessProg", ")", "!=", "20", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", "+", "\"", "\"", ")", "\n", "}", "\n\n", "addr", ":=", "&", "AddressWitnessPubKeyHash", "{", "hrp", ":", "strings", ".", "ToLower", "(", "hrp", ")", ",", "witnessVersion", ":", "0x00", ",", "}", "\n\n", "copy", "(", "addr", ".", "witnessProgram", "[", ":", "]", ",", "witnessProg", ")", "\n\n", "return", "addr", ",", "nil", "\n", "}" ]
// newAddressWitnessPubKeyHash is an internal helper function to create an // AddressWitnessPubKeyHash with a known human-readable part, rather than // looking it up through its parameters.
[ "newAddressWitnessPubKeyHash", "is", "an", "internal", "helper", "function", "to", "create", "an", "AddressWitnessPubKeyHash", "with", "a", "known", "human", "-", "readable", "part", "rather", "than", "looking", "it", "up", "through", "its", "parameters", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/address.go#L527-L543
149,565
btcsuite/btcutil
address.go
EncodeAddress
func (a *AddressWitnessPubKeyHash) EncodeAddress() string { str, err := encodeSegWitAddress(a.hrp, a.witnessVersion, a.witnessProgram[:]) if err != nil { return "" } return str }
go
func (a *AddressWitnessPubKeyHash) EncodeAddress() string { str, err := encodeSegWitAddress(a.hrp, a.witnessVersion, a.witnessProgram[:]) if err != nil { return "" } return str }
[ "func", "(", "a", "*", "AddressWitnessPubKeyHash", ")", "EncodeAddress", "(", ")", "string", "{", "str", ",", "err", ":=", "encodeSegWitAddress", "(", "a", ".", "hrp", ",", "a", ".", "witnessVersion", ",", "a", ".", "witnessProgram", "[", ":", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "str", "\n", "}" ]
// EncodeAddress returns the bech32 string encoding of an // AddressWitnessPubKeyHash. // Part of the Address interface.
[ "EncodeAddress", "returns", "the", "bech32", "string", "encoding", "of", "an", "AddressWitnessPubKeyHash", ".", "Part", "of", "the", "Address", "interface", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/address.go#L548-L555
149,566
btcsuite/btcutil
address.go
IsForNet
func (a *AddressWitnessPubKeyHash) IsForNet(net *chaincfg.Params) bool { return a.hrp == net.Bech32HRPSegwit }
go
func (a *AddressWitnessPubKeyHash) IsForNet(net *chaincfg.Params) bool { return a.hrp == net.Bech32HRPSegwit }
[ "func", "(", "a", "*", "AddressWitnessPubKeyHash", ")", "IsForNet", "(", "net", "*", "chaincfg", ".", "Params", ")", "bool", "{", "return", "a", ".", "hrp", "==", "net", ".", "Bech32HRPSegwit", "\n", "}" ]
// IsForNet returns whether or not the AddressWitnessPubKeyHash is associated // with the passed bitcoin network. // Part of the Address interface.
[ "IsForNet", "returns", "whether", "or", "not", "the", "AddressWitnessPubKeyHash", "is", "associated", "with", "the", "passed", "bitcoin", "network", ".", "Part", "of", "the", "Address", "interface", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/address.go#L566-L568
149,567
btcsuite/btcutil
address.go
NewAddressWitnessScriptHash
func NewAddressWitnessScriptHash(witnessProg []byte, net *chaincfg.Params) (*AddressWitnessScriptHash, error) { return newAddressWitnessScriptHash(net.Bech32HRPSegwit, witnessProg) }
go
func NewAddressWitnessScriptHash(witnessProg []byte, net *chaincfg.Params) (*AddressWitnessScriptHash, error) { return newAddressWitnessScriptHash(net.Bech32HRPSegwit, witnessProg) }
[ "func", "NewAddressWitnessScriptHash", "(", "witnessProg", "[", "]", "byte", ",", "net", "*", "chaincfg", ".", "Params", ")", "(", "*", "AddressWitnessScriptHash", ",", "error", ")", "{", "return", "newAddressWitnessScriptHash", "(", "net", ".", "Bech32HRPSegwit", ",", "witnessProg", ")", "\n", "}" ]
// NewAddressWitnessScriptHash returns a new AddressWitnessPubKeyHash.
[ "NewAddressWitnessScriptHash", "returns", "a", "new", "AddressWitnessPubKeyHash", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/address.go#L611-L613
149,568
btcsuite/btcutil
address.go
newAddressWitnessScriptHash
func newAddressWitnessScriptHash(hrp string, witnessProg []byte) (*AddressWitnessScriptHash, error) { // Check for valid program length for witness version 0, which is 32 // for P2WSH. if len(witnessProg) != 32 { return nil, errors.New("witness program must be 32 " + "bytes for p2wsh") } addr := &AddressWitnessScriptHash{ hrp: strings.ToLower(hrp), witnessVersion: 0x00, } copy(addr.witnessProgram[:], witnessProg) return addr, nil }
go
func newAddressWitnessScriptHash(hrp string, witnessProg []byte) (*AddressWitnessScriptHash, error) { // Check for valid program length for witness version 0, which is 32 // for P2WSH. if len(witnessProg) != 32 { return nil, errors.New("witness program must be 32 " + "bytes for p2wsh") } addr := &AddressWitnessScriptHash{ hrp: strings.ToLower(hrp), witnessVersion: 0x00, } copy(addr.witnessProgram[:], witnessProg) return addr, nil }
[ "func", "newAddressWitnessScriptHash", "(", "hrp", "string", ",", "witnessProg", "[", "]", "byte", ")", "(", "*", "AddressWitnessScriptHash", ",", "error", ")", "{", "// Check for valid program length for witness version 0, which is 32", "// for P2WSH.", "if", "len", "(", "witnessProg", ")", "!=", "32", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", "+", "\"", "\"", ")", "\n", "}", "\n\n", "addr", ":=", "&", "AddressWitnessScriptHash", "{", "hrp", ":", "strings", ".", "ToLower", "(", "hrp", ")", ",", "witnessVersion", ":", "0x00", ",", "}", "\n\n", "copy", "(", "addr", ".", "witnessProgram", "[", ":", "]", ",", "witnessProg", ")", "\n\n", "return", "addr", ",", "nil", "\n", "}" ]
// newAddressWitnessScriptHash is an internal helper function to create an // AddressWitnessScriptHash with a known human-readable part, rather than // looking it up through its parameters.
[ "newAddressWitnessScriptHash", "is", "an", "internal", "helper", "function", "to", "create", "an", "AddressWitnessScriptHash", "with", "a", "known", "human", "-", "readable", "part", "rather", "than", "looking", "it", "up", "through", "its", "parameters", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/address.go#L618-L634
149,569
btcsuite/btcutil
base58/base58check.go
CheckEncode
func CheckEncode(input []byte, version byte) string { b := make([]byte, 0, 1+len(input)+4) b = append(b, version) b = append(b, input[:]...) cksum := checksum(b) b = append(b, cksum[:]...) return Encode(b) }
go
func CheckEncode(input []byte, version byte) string { b := make([]byte, 0, 1+len(input)+4) b = append(b, version) b = append(b, input[:]...) cksum := checksum(b) b = append(b, cksum[:]...) return Encode(b) }
[ "func", "CheckEncode", "(", "input", "[", "]", "byte", ",", "version", "byte", ")", "string", "{", "b", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "1", "+", "len", "(", "input", ")", "+", "4", ")", "\n", "b", "=", "append", "(", "b", ",", "version", ")", "\n", "b", "=", "append", "(", "b", ",", "input", "[", ":", "]", "...", ")", "\n", "cksum", ":=", "checksum", "(", "b", ")", "\n", "b", "=", "append", "(", "b", ",", "cksum", "[", ":", "]", "...", ")", "\n", "return", "Encode", "(", "b", ")", "\n", "}" ]
// CheckEncode prepends a version byte and appends a four byte checksum.
[ "CheckEncode", "prepends", "a", "version", "byte", "and", "appends", "a", "four", "byte", "checksum", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/base58/base58check.go#L28-L35
149,570
btcsuite/btcutil
base58/base58check.go
CheckDecode
func CheckDecode(input string) (result []byte, version byte, err error) { decoded := Decode(input) if len(decoded) < 5 { return nil, 0, ErrInvalidFormat } version = decoded[0] var cksum [4]byte copy(cksum[:], decoded[len(decoded)-4:]) if checksum(decoded[:len(decoded)-4]) != cksum { return nil, 0, ErrChecksum } payload := decoded[1 : len(decoded)-4] result = append(result, payload...) return }
go
func CheckDecode(input string) (result []byte, version byte, err error) { decoded := Decode(input) if len(decoded) < 5 { return nil, 0, ErrInvalidFormat } version = decoded[0] var cksum [4]byte copy(cksum[:], decoded[len(decoded)-4:]) if checksum(decoded[:len(decoded)-4]) != cksum { return nil, 0, ErrChecksum } payload := decoded[1 : len(decoded)-4] result = append(result, payload...) return }
[ "func", "CheckDecode", "(", "input", "string", ")", "(", "result", "[", "]", "byte", ",", "version", "byte", ",", "err", "error", ")", "{", "decoded", ":=", "Decode", "(", "input", ")", "\n", "if", "len", "(", "decoded", ")", "<", "5", "{", "return", "nil", ",", "0", ",", "ErrInvalidFormat", "\n", "}", "\n", "version", "=", "decoded", "[", "0", "]", "\n", "var", "cksum", "[", "4", "]", "byte", "\n", "copy", "(", "cksum", "[", ":", "]", ",", "decoded", "[", "len", "(", "decoded", ")", "-", "4", ":", "]", ")", "\n", "if", "checksum", "(", "decoded", "[", ":", "len", "(", "decoded", ")", "-", "4", "]", ")", "!=", "cksum", "{", "return", "nil", ",", "0", ",", "ErrChecksum", "\n", "}", "\n", "payload", ":=", "decoded", "[", "1", ":", "len", "(", "decoded", ")", "-", "4", "]", "\n", "result", "=", "append", "(", "result", ",", "payload", "...", ")", "\n", "return", "\n", "}" ]
// CheckDecode decodes a string that was encoded with CheckEncode and verifies the checksum.
[ "CheckDecode", "decodes", "a", "string", "that", "was", "encoded", "with", "CheckEncode", "and", "verifies", "the", "checksum", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/base58/base58check.go#L38-L52
149,571
btcsuite/btcutil
bloom/murmurhash3.go
MurmurHash3
func MurmurHash3(seed uint32, data []byte) uint32 { dataLen := uint32(len(data)) hash := seed k := uint32(0) numBlocks := dataLen / 4 // Calculate the hash in 4-byte chunks. for i := uint32(0); i < numBlocks; i++ { k = binary.LittleEndian.Uint32(data[i*4:]) k *= murmurC1 k = (k << murmurR1) | (k >> (32 - murmurR1)) k *= murmurC2 hash ^= k hash = (hash << murmurR2) | (hash >> (32 - murmurR2)) hash = hash*murmurM + murmurN } // Handle remaining bytes. tailIdx := numBlocks * 4 k = 0 switch dataLen & 3 { case 3: k ^= uint32(data[tailIdx+2]) << 16 fallthrough case 2: k ^= uint32(data[tailIdx+1]) << 8 fallthrough case 1: k ^= uint32(data[tailIdx]) k *= murmurC1 k = (k << murmurR1) | (k >> (32 - murmurR1)) k *= murmurC2 hash ^= k } // Finalization. hash ^= dataLen hash ^= hash >> 16 hash *= 0x85ebca6b hash ^= hash >> 13 hash *= 0xc2b2ae35 hash ^= hash >> 16 return hash }
go
func MurmurHash3(seed uint32, data []byte) uint32 { dataLen := uint32(len(data)) hash := seed k := uint32(0) numBlocks := dataLen / 4 // Calculate the hash in 4-byte chunks. for i := uint32(0); i < numBlocks; i++ { k = binary.LittleEndian.Uint32(data[i*4:]) k *= murmurC1 k = (k << murmurR1) | (k >> (32 - murmurR1)) k *= murmurC2 hash ^= k hash = (hash << murmurR2) | (hash >> (32 - murmurR2)) hash = hash*murmurM + murmurN } // Handle remaining bytes. tailIdx := numBlocks * 4 k = 0 switch dataLen & 3 { case 3: k ^= uint32(data[tailIdx+2]) << 16 fallthrough case 2: k ^= uint32(data[tailIdx+1]) << 8 fallthrough case 1: k ^= uint32(data[tailIdx]) k *= murmurC1 k = (k << murmurR1) | (k >> (32 - murmurR1)) k *= murmurC2 hash ^= k } // Finalization. hash ^= dataLen hash ^= hash >> 16 hash *= 0x85ebca6b hash ^= hash >> 13 hash *= 0xc2b2ae35 hash ^= hash >> 16 return hash }
[ "func", "MurmurHash3", "(", "seed", "uint32", ",", "data", "[", "]", "byte", ")", "uint32", "{", "dataLen", ":=", "uint32", "(", "len", "(", "data", ")", ")", "\n", "hash", ":=", "seed", "\n", "k", ":=", "uint32", "(", "0", ")", "\n", "numBlocks", ":=", "dataLen", "/", "4", "\n\n", "// Calculate the hash in 4-byte chunks.", "for", "i", ":=", "uint32", "(", "0", ")", ";", "i", "<", "numBlocks", ";", "i", "++", "{", "k", "=", "binary", ".", "LittleEndian", ".", "Uint32", "(", "data", "[", "i", "*", "4", ":", "]", ")", "\n", "k", "*=", "murmurC1", "\n", "k", "=", "(", "k", "<<", "murmurR1", ")", "|", "(", "k", ">>", "(", "32", "-", "murmurR1", ")", ")", "\n", "k", "*=", "murmurC2", "\n\n", "hash", "^=", "k", "\n", "hash", "=", "(", "hash", "<<", "murmurR2", ")", "|", "(", "hash", ">>", "(", "32", "-", "murmurR2", ")", ")", "\n", "hash", "=", "hash", "*", "murmurM", "+", "murmurN", "\n", "}", "\n\n", "// Handle remaining bytes.", "tailIdx", ":=", "numBlocks", "*", "4", "\n", "k", "=", "0", "\n\n", "switch", "dataLen", "&", "3", "{", "case", "3", ":", "k", "^=", "uint32", "(", "data", "[", "tailIdx", "+", "2", "]", ")", "<<", "16", "\n", "fallthrough", "\n", "case", "2", ":", "k", "^=", "uint32", "(", "data", "[", "tailIdx", "+", "1", "]", ")", "<<", "8", "\n", "fallthrough", "\n", "case", "1", ":", "k", "^=", "uint32", "(", "data", "[", "tailIdx", "]", ")", "\n", "k", "*=", "murmurC1", "\n", "k", "=", "(", "k", "<<", "murmurR1", ")", "|", "(", "k", ">>", "(", "32", "-", "murmurR1", ")", ")", "\n", "k", "*=", "murmurC2", "\n", "hash", "^=", "k", "\n", "}", "\n\n", "// Finalization.", "hash", "^=", "dataLen", "\n", "hash", "^=", "hash", ">>", "16", "\n", "hash", "*=", "0x85ebca6b", "\n", "hash", "^=", "hash", ">>", "13", "\n", "hash", "*=", "0xc2b2ae35", "\n", "hash", "^=", "hash", ">>", "16", "\n\n", "return", "hash", "\n", "}" ]
// MurmurHash3 implements a non-cryptographic hash function using the // MurmurHash3 algorithm. This implementation yields a 32-bit hash value which // is suitable for general hash-based lookups. The seed can be used to // effectively randomize the hash function. This makes it ideal for use in // bloom filters which need multiple independent hash functions.
[ "MurmurHash3", "implements", "a", "non", "-", "cryptographic", "hash", "function", "using", "the", "MurmurHash3", "algorithm", ".", "This", "implementation", "yields", "a", "32", "-", "bit", "hash", "value", "which", "is", "suitable", "for", "general", "hash", "-", "based", "lookups", ".", "The", "seed", "can", "be", "used", "to", "effectively", "randomize", "the", "hash", "function", ".", "This", "makes", "it", "ideal", "for", "use", "in", "bloom", "filters", "which", "need", "multiple", "independent", "hash", "functions", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/bloom/murmurhash3.go#L26-L72
149,572
btcsuite/btcutil
coinset/coins.go
NewCoinSet
func NewCoinSet(coins []Coin) *CoinSet { newCoinSet := &CoinSet{ coinList: list.New(), totalValue: 0, totalValueAge: 0, } for _, coin := range coins { newCoinSet.PushCoin(coin) } return newCoinSet }
go
func NewCoinSet(coins []Coin) *CoinSet { newCoinSet := &CoinSet{ coinList: list.New(), totalValue: 0, totalValueAge: 0, } for _, coin := range coins { newCoinSet.PushCoin(coin) } return newCoinSet }
[ "func", "NewCoinSet", "(", "coins", "[", "]", "Coin", ")", "*", "CoinSet", "{", "newCoinSet", ":=", "&", "CoinSet", "{", "coinList", ":", "list", ".", "New", "(", ")", ",", "totalValue", ":", "0", ",", "totalValueAge", ":", "0", ",", "}", "\n", "for", "_", ",", "coin", ":=", "range", "coins", "{", "newCoinSet", ".", "PushCoin", "(", "coin", ")", "\n", "}", "\n", "return", "newCoinSet", "\n", "}" ]
// NewCoinSet creates a CoinSet containing the coins provided. // To create an empty CoinSet, you may pass null as the coins input parameter.
[ "NewCoinSet", "creates", "a", "CoinSet", "containing", "the", "coins", "provided", ".", "To", "create", "an", "empty", "CoinSet", "you", "may", "pass", "null", "as", "the", "coins", "input", "parameter", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/coinset/coins.go#L51-L61
149,573
btcsuite/btcutil
coinset/coins.go
Coins
func (cs *CoinSet) Coins() []Coin { coins := make([]Coin, cs.coinList.Len()) for i, e := 0, cs.coinList.Front(); e != nil; i, e = i+1, e.Next() { coins[i] = e.Value.(Coin) } return coins }
go
func (cs *CoinSet) Coins() []Coin { coins := make([]Coin, cs.coinList.Len()) for i, e := 0, cs.coinList.Front(); e != nil; i, e = i+1, e.Next() { coins[i] = e.Value.(Coin) } return coins }
[ "func", "(", "cs", "*", "CoinSet", ")", "Coins", "(", ")", "[", "]", "Coin", "{", "coins", ":=", "make", "(", "[", "]", "Coin", ",", "cs", ".", "coinList", ".", "Len", "(", ")", ")", "\n", "for", "i", ",", "e", ":=", "0", ",", "cs", ".", "coinList", ".", "Front", "(", ")", ";", "e", "!=", "nil", ";", "i", ",", "e", "=", "i", "+", "1", ",", "e", ".", "Next", "(", ")", "{", "coins", "[", "i", "]", "=", "e", ".", "Value", ".", "(", "Coin", ")", "\n", "}", "\n", "return", "coins", "\n", "}" ]
// Coins returns a new slice of the coins contained in the set.
[ "Coins", "returns", "a", "new", "slice", "of", "the", "coins", "contained", "in", "the", "set", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/coinset/coins.go#L64-L70
149,574
btcsuite/btcutil
coinset/coins.go
PushCoin
func (cs *CoinSet) PushCoin(c Coin) { cs.coinList.PushBack(c) cs.totalValue += c.Value() cs.totalValueAge += c.ValueAge() }
go
func (cs *CoinSet) PushCoin(c Coin) { cs.coinList.PushBack(c) cs.totalValue += c.Value() cs.totalValueAge += c.ValueAge() }
[ "func", "(", "cs", "*", "CoinSet", ")", "PushCoin", "(", "c", "Coin", ")", "{", "cs", ".", "coinList", ".", "PushBack", "(", "c", ")", "\n", "cs", ".", "totalValue", "+=", "c", ".", "Value", "(", ")", "\n", "cs", ".", "totalValueAge", "+=", "c", ".", "ValueAge", "(", ")", "\n", "}" ]
// PushCoin adds a coin to the end of the list and updates // the cached value amounts.
[ "PushCoin", "adds", "a", "coin", "to", "the", "end", "of", "the", "list", "and", "updates", "the", "cached", "value", "amounts", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/coinset/coins.go#L90-L94
149,575
btcsuite/btcutil
coinset/coins.go
PopCoin
func (cs *CoinSet) PopCoin() Coin { back := cs.coinList.Back() if back == nil { return nil } return cs.removeElement(back) }
go
func (cs *CoinSet) PopCoin() Coin { back := cs.coinList.Back() if back == nil { return nil } return cs.removeElement(back) }
[ "func", "(", "cs", "*", "CoinSet", ")", "PopCoin", "(", ")", "Coin", "{", "back", ":=", "cs", ".", "coinList", ".", "Back", "(", ")", "\n", "if", "back", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "cs", ".", "removeElement", "(", "back", ")", "\n", "}" ]
// PopCoin removes the last coin on the list and returns it.
[ "PopCoin", "removes", "the", "last", "coin", "on", "the", "list", "and", "returns", "it", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/coinset/coins.go#L97-L103
149,576
btcsuite/btcutil
coinset/coins.go
ShiftCoin
func (cs *CoinSet) ShiftCoin() Coin { front := cs.coinList.Front() if front == nil { return nil } return cs.removeElement(front) }
go
func (cs *CoinSet) ShiftCoin() Coin { front := cs.coinList.Front() if front == nil { return nil } return cs.removeElement(front) }
[ "func", "(", "cs", "*", "CoinSet", ")", "ShiftCoin", "(", ")", "Coin", "{", "front", ":=", "cs", ".", "coinList", ".", "Front", "(", ")", "\n", "if", "front", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "cs", ".", "removeElement", "(", "front", ")", "\n", "}" ]
// ShiftCoin removes the first coin on the list and returns it.
[ "ShiftCoin", "removes", "the", "first", "coin", "on", "the", "list", "and", "returns", "it", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/coinset/coins.go#L106-L112
149,577
btcsuite/btcutil
coinset/coins.go
removeElement
func (cs *CoinSet) removeElement(e *list.Element) Coin { c := e.Value.(Coin) cs.coinList.Remove(e) cs.totalValue -= c.Value() cs.totalValueAge -= c.ValueAge() return c }
go
func (cs *CoinSet) removeElement(e *list.Element) Coin { c := e.Value.(Coin) cs.coinList.Remove(e) cs.totalValue -= c.Value() cs.totalValueAge -= c.ValueAge() return c }
[ "func", "(", "cs", "*", "CoinSet", ")", "removeElement", "(", "e", "*", "list", ".", "Element", ")", "Coin", "{", "c", ":=", "e", ".", "Value", ".", "(", "Coin", ")", "\n", "cs", ".", "coinList", ".", "Remove", "(", "e", ")", "\n", "cs", ".", "totalValue", "-=", "c", ".", "Value", "(", ")", "\n", "cs", ".", "totalValueAge", "-=", "c", ".", "ValueAge", "(", ")", "\n", "return", "c", "\n", "}" ]
// removeElement updates the cached value amounts in the CoinSet, // removes the element from the list, then returns the Coin that // was removed to the caller.
[ "removeElement", "updates", "the", "cached", "value", "amounts", "in", "the", "CoinSet", "removes", "the", "element", "from", "the", "list", "then", "returns", "the", "Coin", "that", "was", "removed", "to", "the", "caller", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/coinset/coins.go#L117-L123
149,578
btcsuite/btcutil
coinset/coins.go
NewMsgTxWithInputCoins
func NewMsgTxWithInputCoins(txVersion int32, inputCoins Coins) *wire.MsgTx { msgTx := wire.NewMsgTx(txVersion) coins := inputCoins.Coins() msgTx.TxIn = make([]*wire.TxIn, len(coins)) for i, coin := range coins { msgTx.TxIn[i] = &wire.TxIn{ PreviousOutPoint: wire.OutPoint{ Hash: *coin.Hash(), Index: coin.Index(), }, SignatureScript: nil, Sequence: wire.MaxTxInSequenceNum, } } return msgTx }
go
func NewMsgTxWithInputCoins(txVersion int32, inputCoins Coins) *wire.MsgTx { msgTx := wire.NewMsgTx(txVersion) coins := inputCoins.Coins() msgTx.TxIn = make([]*wire.TxIn, len(coins)) for i, coin := range coins { msgTx.TxIn[i] = &wire.TxIn{ PreviousOutPoint: wire.OutPoint{ Hash: *coin.Hash(), Index: coin.Index(), }, SignatureScript: nil, Sequence: wire.MaxTxInSequenceNum, } } return msgTx }
[ "func", "NewMsgTxWithInputCoins", "(", "txVersion", "int32", ",", "inputCoins", "Coins", ")", "*", "wire", ".", "MsgTx", "{", "msgTx", ":=", "wire", ".", "NewMsgTx", "(", "txVersion", ")", "\n", "coins", ":=", "inputCoins", ".", "Coins", "(", ")", "\n", "msgTx", ".", "TxIn", "=", "make", "(", "[", "]", "*", "wire", ".", "TxIn", ",", "len", "(", "coins", ")", ")", "\n", "for", "i", ",", "coin", ":=", "range", "coins", "{", "msgTx", ".", "TxIn", "[", "i", "]", "=", "&", "wire", ".", "TxIn", "{", "PreviousOutPoint", ":", "wire", ".", "OutPoint", "{", "Hash", ":", "*", "coin", ".", "Hash", "(", ")", ",", "Index", ":", "coin", ".", "Index", "(", ")", ",", "}", ",", "SignatureScript", ":", "nil", ",", "Sequence", ":", "wire", ".", "MaxTxInSequenceNum", ",", "}", "\n", "}", "\n", "return", "msgTx", "\n", "}" ]
// NewMsgTxWithInputCoins takes the coins in the CoinSet and makes them // the inputs to a new wire.MsgTx which is returned.
[ "NewMsgTxWithInputCoins", "takes", "the", "coins", "in", "the", "CoinSet", "and", "makes", "them", "the", "inputs", "to", "a", "new", "wire", ".", "MsgTx", "which", "is", "returned", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/coinset/coins.go#L127-L142
149,579
btcsuite/btcutil
coinset/coins.go
CoinSelect
func (s MinIndexCoinSelector) CoinSelect(targetValue btcutil.Amount, coins []Coin) (Coins, error) { cs := NewCoinSet(nil) for n := 0; n < len(coins) && n < s.MaxInputs; n++ { cs.PushCoin(coins[n]) if satisfiesTargetValue(targetValue, s.MinChangeAmount, cs.TotalValue()) { return cs, nil } } return nil, ErrCoinsNoSelectionAvailable }
go
func (s MinIndexCoinSelector) CoinSelect(targetValue btcutil.Amount, coins []Coin) (Coins, error) { cs := NewCoinSet(nil) for n := 0; n < len(coins) && n < s.MaxInputs; n++ { cs.PushCoin(coins[n]) if satisfiesTargetValue(targetValue, s.MinChangeAmount, cs.TotalValue()) { return cs, nil } } return nil, ErrCoinsNoSelectionAvailable }
[ "func", "(", "s", "MinIndexCoinSelector", ")", "CoinSelect", "(", "targetValue", "btcutil", ".", "Amount", ",", "coins", "[", "]", "Coin", ")", "(", "Coins", ",", "error", ")", "{", "cs", ":=", "NewCoinSet", "(", "nil", ")", "\n", "for", "n", ":=", "0", ";", "n", "<", "len", "(", "coins", ")", "&&", "n", "<", "s", ".", "MaxInputs", ";", "n", "++", "{", "cs", ".", "PushCoin", "(", "coins", "[", "n", "]", ")", "\n", "if", "satisfiesTargetValue", "(", "targetValue", ",", "s", ".", "MinChangeAmount", ",", "cs", ".", "TotalValue", "(", ")", ")", "{", "return", "cs", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "ErrCoinsNoSelectionAvailable", "\n", "}" ]
// CoinSelect will attempt to select coins using the algorithm described // in the MinIndexCoinSelector struct.
[ "CoinSelect", "will", "attempt", "to", "select", "coins", "using", "the", "algorithm", "described", "in", "the", "MinIndexCoinSelector", "struct", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/coinset/coins.go#L181-L190
149,580
btcsuite/btcutil
coinset/coins.go
CoinSelect
func (s MinNumberCoinSelector) CoinSelect(targetValue btcutil.Amount, coins []Coin) (Coins, error) { sortedCoins := make([]Coin, 0, len(coins)) sortedCoins = append(sortedCoins, coins...) sort.Sort(sort.Reverse(byAmount(sortedCoins))) return MinIndexCoinSelector(s).CoinSelect(targetValue, sortedCoins) }
go
func (s MinNumberCoinSelector) CoinSelect(targetValue btcutil.Amount, coins []Coin) (Coins, error) { sortedCoins := make([]Coin, 0, len(coins)) sortedCoins = append(sortedCoins, coins...) sort.Sort(sort.Reverse(byAmount(sortedCoins))) return MinIndexCoinSelector(s).CoinSelect(targetValue, sortedCoins) }
[ "func", "(", "s", "MinNumberCoinSelector", ")", "CoinSelect", "(", "targetValue", "btcutil", ".", "Amount", ",", "coins", "[", "]", "Coin", ")", "(", "Coins", ",", "error", ")", "{", "sortedCoins", ":=", "make", "(", "[", "]", "Coin", ",", "0", ",", "len", "(", "coins", ")", ")", "\n", "sortedCoins", "=", "append", "(", "sortedCoins", ",", "coins", "...", ")", "\n", "sort", ".", "Sort", "(", "sort", ".", "Reverse", "(", "byAmount", "(", "sortedCoins", ")", ")", ")", "\n\n", "return", "MinIndexCoinSelector", "(", "s", ")", ".", "CoinSelect", "(", "targetValue", ",", "sortedCoins", ")", "\n", "}" ]
// CoinSelect will attempt to select coins using the algorithm described // in the MinNumberCoinSelector struct.
[ "CoinSelect", "will", "attempt", "to", "select", "coins", "using", "the", "algorithm", "described", "in", "the", "MinNumberCoinSelector", "struct", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/coinset/coins.go#L202-L208
149,581
btcsuite/btcutil
coinset/coins.go
CoinSelect
func (s MinPriorityCoinSelector) CoinSelect(targetValue btcutil.Amount, coins []Coin) (Coins, error) { possibleCoins := make([]Coin, 0, len(coins)) possibleCoins = append(possibleCoins, coins...) sort.Sort(byValueAge(possibleCoins)) // find the first coin with sufficient valueAge cutoffIndex := -1 for i := 0; i < len(possibleCoins); i++ { if possibleCoins[i].ValueAge() >= s.MinAvgValueAgePerInput { cutoffIndex = i break } } if cutoffIndex < 0 { return nil, ErrCoinsNoSelectionAvailable } // create sets of input coins that will obey minimum average valueAge for i := cutoffIndex; i < len(possibleCoins); i++ { possibleHighCoins := possibleCoins[cutoffIndex : i+1] // choose a set of high-enough valueAge coins highSelect, err := (&MinNumberCoinSelector{ MaxInputs: s.MaxInputs, MinChangeAmount: s.MinChangeAmount, }).CoinSelect(targetValue, possibleHighCoins) if err != nil { // attempt to add available low priority to make a solution for numLow := 1; numLow <= cutoffIndex && numLow+(i-cutoffIndex) <= s.MaxInputs; numLow++ { allHigh := NewCoinSet(possibleCoins[cutoffIndex : i+1]) newTargetValue := targetValue - allHigh.TotalValue() newMaxInputs := allHigh.Num() + numLow if newMaxInputs > numLow { newMaxInputs = numLow } newMinAvgValueAge := ((s.MinAvgValueAgePerInput * int64(allHigh.Num()+numLow)) - allHigh.TotalValueAge()) / int64(numLow) // find the minimum priority that can be added to set lowSelect, err := (&MinPriorityCoinSelector{ MaxInputs: newMaxInputs, MinChangeAmount: s.MinChangeAmount, MinAvgValueAgePerInput: newMinAvgValueAge, }).CoinSelect(newTargetValue, possibleCoins[0:cutoffIndex]) if err != nil { continue } for _, coin := range lowSelect.Coins() { allHigh.PushCoin(coin) } return allHigh, nil } // oh well, couldn't fix, try to add more high priority to the set. } else { extendedCoins := NewCoinSet(highSelect.Coins()) // attempt to lower priority towards target with lowest ones first for n := 0; n < cutoffIndex; n++ { if extendedCoins.Num() >= s.MaxInputs { break } if possibleCoins[n].ValueAge() == 0 { continue } extendedCoins.PushCoin(possibleCoins[n]) if extendedCoins.TotalValueAge()/int64(extendedCoins.Num()) < s.MinAvgValueAgePerInput { extendedCoins.PopCoin() continue } } return extendedCoins, nil } } return nil, ErrCoinsNoSelectionAvailable }
go
func (s MinPriorityCoinSelector) CoinSelect(targetValue btcutil.Amount, coins []Coin) (Coins, error) { possibleCoins := make([]Coin, 0, len(coins)) possibleCoins = append(possibleCoins, coins...) sort.Sort(byValueAge(possibleCoins)) // find the first coin with sufficient valueAge cutoffIndex := -1 for i := 0; i < len(possibleCoins); i++ { if possibleCoins[i].ValueAge() >= s.MinAvgValueAgePerInput { cutoffIndex = i break } } if cutoffIndex < 0 { return nil, ErrCoinsNoSelectionAvailable } // create sets of input coins that will obey minimum average valueAge for i := cutoffIndex; i < len(possibleCoins); i++ { possibleHighCoins := possibleCoins[cutoffIndex : i+1] // choose a set of high-enough valueAge coins highSelect, err := (&MinNumberCoinSelector{ MaxInputs: s.MaxInputs, MinChangeAmount: s.MinChangeAmount, }).CoinSelect(targetValue, possibleHighCoins) if err != nil { // attempt to add available low priority to make a solution for numLow := 1; numLow <= cutoffIndex && numLow+(i-cutoffIndex) <= s.MaxInputs; numLow++ { allHigh := NewCoinSet(possibleCoins[cutoffIndex : i+1]) newTargetValue := targetValue - allHigh.TotalValue() newMaxInputs := allHigh.Num() + numLow if newMaxInputs > numLow { newMaxInputs = numLow } newMinAvgValueAge := ((s.MinAvgValueAgePerInput * int64(allHigh.Num()+numLow)) - allHigh.TotalValueAge()) / int64(numLow) // find the minimum priority that can be added to set lowSelect, err := (&MinPriorityCoinSelector{ MaxInputs: newMaxInputs, MinChangeAmount: s.MinChangeAmount, MinAvgValueAgePerInput: newMinAvgValueAge, }).CoinSelect(newTargetValue, possibleCoins[0:cutoffIndex]) if err != nil { continue } for _, coin := range lowSelect.Coins() { allHigh.PushCoin(coin) } return allHigh, nil } // oh well, couldn't fix, try to add more high priority to the set. } else { extendedCoins := NewCoinSet(highSelect.Coins()) // attempt to lower priority towards target with lowest ones first for n := 0; n < cutoffIndex; n++ { if extendedCoins.Num() >= s.MaxInputs { break } if possibleCoins[n].ValueAge() == 0 { continue } extendedCoins.PushCoin(possibleCoins[n]) if extendedCoins.TotalValueAge()/int64(extendedCoins.Num()) < s.MinAvgValueAgePerInput { extendedCoins.PopCoin() continue } } return extendedCoins, nil } } return nil, ErrCoinsNoSelectionAvailable }
[ "func", "(", "s", "MinPriorityCoinSelector", ")", "CoinSelect", "(", "targetValue", "btcutil", ".", "Amount", ",", "coins", "[", "]", "Coin", ")", "(", "Coins", ",", "error", ")", "{", "possibleCoins", ":=", "make", "(", "[", "]", "Coin", ",", "0", ",", "len", "(", "coins", ")", ")", "\n", "possibleCoins", "=", "append", "(", "possibleCoins", ",", "coins", "...", ")", "\n\n", "sort", ".", "Sort", "(", "byValueAge", "(", "possibleCoins", ")", ")", "\n\n", "// find the first coin with sufficient valueAge", "cutoffIndex", ":=", "-", "1", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "possibleCoins", ")", ";", "i", "++", "{", "if", "possibleCoins", "[", "i", "]", ".", "ValueAge", "(", ")", ">=", "s", ".", "MinAvgValueAgePerInput", "{", "cutoffIndex", "=", "i", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "cutoffIndex", "<", "0", "{", "return", "nil", ",", "ErrCoinsNoSelectionAvailable", "\n", "}", "\n\n", "// create sets of input coins that will obey minimum average valueAge", "for", "i", ":=", "cutoffIndex", ";", "i", "<", "len", "(", "possibleCoins", ")", ";", "i", "++", "{", "possibleHighCoins", ":=", "possibleCoins", "[", "cutoffIndex", ":", "i", "+", "1", "]", "\n\n", "// choose a set of high-enough valueAge coins", "highSelect", ",", "err", ":=", "(", "&", "MinNumberCoinSelector", "{", "MaxInputs", ":", "s", ".", "MaxInputs", ",", "MinChangeAmount", ":", "s", ".", "MinChangeAmount", ",", "}", ")", ".", "CoinSelect", "(", "targetValue", ",", "possibleHighCoins", ")", "\n\n", "if", "err", "!=", "nil", "{", "// attempt to add available low priority to make a solution", "for", "numLow", ":=", "1", ";", "numLow", "<=", "cutoffIndex", "&&", "numLow", "+", "(", "i", "-", "cutoffIndex", ")", "<=", "s", ".", "MaxInputs", ";", "numLow", "++", "{", "allHigh", ":=", "NewCoinSet", "(", "possibleCoins", "[", "cutoffIndex", ":", "i", "+", "1", "]", ")", "\n", "newTargetValue", ":=", "targetValue", "-", "allHigh", ".", "TotalValue", "(", ")", "\n", "newMaxInputs", ":=", "allHigh", ".", "Num", "(", ")", "+", "numLow", "\n", "if", "newMaxInputs", ">", "numLow", "{", "newMaxInputs", "=", "numLow", "\n", "}", "\n", "newMinAvgValueAge", ":=", "(", "(", "s", ".", "MinAvgValueAgePerInput", "*", "int64", "(", "allHigh", ".", "Num", "(", ")", "+", "numLow", ")", ")", "-", "allHigh", ".", "TotalValueAge", "(", ")", ")", "/", "int64", "(", "numLow", ")", "\n\n", "// find the minimum priority that can be added to set", "lowSelect", ",", "err", ":=", "(", "&", "MinPriorityCoinSelector", "{", "MaxInputs", ":", "newMaxInputs", ",", "MinChangeAmount", ":", "s", ".", "MinChangeAmount", ",", "MinAvgValueAgePerInput", ":", "newMinAvgValueAge", ",", "}", ")", ".", "CoinSelect", "(", "newTargetValue", ",", "possibleCoins", "[", "0", ":", "cutoffIndex", "]", ")", "\n\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n\n", "for", "_", ",", "coin", ":=", "range", "lowSelect", ".", "Coins", "(", ")", "{", "allHigh", ".", "PushCoin", "(", "coin", ")", "\n", "}", "\n\n", "return", "allHigh", ",", "nil", "\n", "}", "\n", "// oh well, couldn't fix, try to add more high priority to the set.", "}", "else", "{", "extendedCoins", ":=", "NewCoinSet", "(", "highSelect", ".", "Coins", "(", ")", ")", "\n\n", "// attempt to lower priority towards target with lowest ones first", "for", "n", ":=", "0", ";", "n", "<", "cutoffIndex", ";", "n", "++", "{", "if", "extendedCoins", ".", "Num", "(", ")", ">=", "s", ".", "MaxInputs", "{", "break", "\n", "}", "\n", "if", "possibleCoins", "[", "n", "]", ".", "ValueAge", "(", ")", "==", "0", "{", "continue", "\n", "}", "\n\n", "extendedCoins", ".", "PushCoin", "(", "possibleCoins", "[", "n", "]", ")", "\n", "if", "extendedCoins", ".", "TotalValueAge", "(", ")", "/", "int64", "(", "extendedCoins", ".", "Num", "(", ")", ")", "<", "s", ".", "MinAvgValueAgePerInput", "{", "extendedCoins", ".", "PopCoin", "(", ")", "\n", "continue", "\n", "}", "\n", "}", "\n", "return", "extendedCoins", ",", "nil", "\n", "}", "\n", "}", "\n\n", "return", "nil", ",", "ErrCoinsNoSelectionAvailable", "\n", "}" ]
// CoinSelect will attempt to select coins using the algorithm described // in the MinPriorityCoinSelector struct.
[ "CoinSelect", "will", "attempt", "to", "select", "coins", "using", "the", "algorithm", "described", "in", "the", "MinPriorityCoinSelector", "struct", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/coinset/coins.go#L250-L331
149,582
btcsuite/btcutil
coinset/coins.go
txOut
func (c *SimpleCoin) txOut() *wire.TxOut { return c.Tx.MsgTx().TxOut[c.TxIndex] }
go
func (c *SimpleCoin) txOut() *wire.TxOut { return c.Tx.MsgTx().TxOut[c.TxIndex] }
[ "func", "(", "c", "*", "SimpleCoin", ")", "txOut", "(", ")", "*", "wire", ".", "TxOut", "{", "return", "c", ".", "Tx", ".", "MsgTx", "(", ")", ".", "TxOut", "[", "c", ".", "TxIndex", "]", "\n", "}" ]
// txOut returns the TxOut of the transaction the Coin represents
[ "txOut", "returns", "the", "TxOut", "of", "the", "transaction", "the", "Coin", "represents" ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/coinset/coins.go#L368-L370
149,583
btcsuite/btcutil
gcs/builder/builder.go
DeriveKey
func DeriveKey(keyHash *chainhash.Hash) [gcs.KeySize]byte { var key [gcs.KeySize]byte copy(key[:], keyHash.CloneBytes()[:]) return key }
go
func DeriveKey(keyHash *chainhash.Hash) [gcs.KeySize]byte { var key [gcs.KeySize]byte copy(key[:], keyHash.CloneBytes()[:]) return key }
[ "func", "DeriveKey", "(", "keyHash", "*", "chainhash", ".", "Hash", ")", "[", "gcs", ".", "KeySize", "]", "byte", "{", "var", "key", "[", "gcs", ".", "KeySize", "]", "byte", "\n", "copy", "(", "key", "[", ":", "]", ",", "keyHash", ".", "CloneBytes", "(", ")", "[", ":", "]", ")", "\n", "return", "key", "\n", "}" ]
// DeriveKey is a utility function that derives a key from a chainhash.Hash by // truncating the bytes of the hash to the appopriate key size.
[ "DeriveKey", "is", "a", "utility", "function", "that", "derives", "a", "key", "from", "a", "chainhash", ".", "Hash", "by", "truncating", "the", "bytes", "of", "the", "hash", "to", "the", "appopriate", "key", "size", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/gcs/builder/builder.go#L63-L67
149,584
btcsuite/btcutil
gcs/builder/builder.go
Key
func (b *GCSBuilder) Key() ([gcs.KeySize]byte, error) { // Do nothing if the builder's errored out. if b.err != nil { return [gcs.KeySize]byte{}, b.err } return b.key, nil }
go
func (b *GCSBuilder) Key() ([gcs.KeySize]byte, error) { // Do nothing if the builder's errored out. if b.err != nil { return [gcs.KeySize]byte{}, b.err } return b.key, nil }
[ "func", "(", "b", "*", "GCSBuilder", ")", "Key", "(", ")", "(", "[", "gcs", ".", "KeySize", "]", "byte", ",", "error", ")", "{", "// Do nothing if the builder's errored out.", "if", "b", ".", "err", "!=", "nil", "{", "return", "[", "gcs", ".", "KeySize", "]", "byte", "{", "}", ",", "b", ".", "err", "\n", "}", "\n\n", "return", "b", ".", "key", ",", "nil", "\n", "}" ]
// Key retrieves the key with which the builder will build a filter. This is // useful if the builder is created with a random initial key.
[ "Key", "retrieves", "the", "key", "with", "which", "the", "builder", "will", "build", "a", "filter", ".", "This", "is", "useful", "if", "the", "builder", "is", "created", "with", "a", "random", "initial", "key", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/gcs/builder/builder.go#L71-L78
149,585
btcsuite/btcutil
gcs/builder/builder.go
AddHash
func (b *GCSBuilder) AddHash(hash *chainhash.Hash) *GCSBuilder { // Do nothing if the builder's already errored out. if b.err != nil { return b } return b.AddEntry(hash.CloneBytes()) }
go
func (b *GCSBuilder) AddHash(hash *chainhash.Hash) *GCSBuilder { // Do nothing if the builder's already errored out. if b.err != nil { return b } return b.AddEntry(hash.CloneBytes()) }
[ "func", "(", "b", "*", "GCSBuilder", ")", "AddHash", "(", "hash", "*", "chainhash", ".", "Hash", ")", "*", "GCSBuilder", "{", "// Do nothing if the builder's already errored out.", "if", "b", ".", "err", "!=", "nil", "{", "return", "b", "\n", "}", "\n\n", "return", "b", ".", "AddEntry", "(", "hash", ".", "CloneBytes", "(", ")", ")", "\n", "}" ]
// AddHash adds a chainhash.Hash to the list of entries to be included in the // GCS filter when it's built.
[ "AddHash", "adds", "a", "chainhash", ".", "Hash", "to", "the", "list", "of", "entries", "to", "be", "included", "in", "the", "GCS", "filter", "when", "it", "s", "built", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/gcs/builder/builder.go#L181-L188
149,586
btcsuite/btcutil
gcs/builder/builder.go
AddWitness
func (b *GCSBuilder) AddWitness(witness wire.TxWitness) *GCSBuilder { // Do nothing if the builder's already errored out. if b.err != nil { return b } return b.AddEntries(witness) }
go
func (b *GCSBuilder) AddWitness(witness wire.TxWitness) *GCSBuilder { // Do nothing if the builder's already errored out. if b.err != nil { return b } return b.AddEntries(witness) }
[ "func", "(", "b", "*", "GCSBuilder", ")", "AddWitness", "(", "witness", "wire", ".", "TxWitness", ")", "*", "GCSBuilder", "{", "// Do nothing if the builder's already errored out.", "if", "b", ".", "err", "!=", "nil", "{", "return", "b", "\n", "}", "\n\n", "return", "b", ".", "AddEntries", "(", "witness", ")", "\n", "}" ]
// AddWitness adds each item of the passed filter stack to the filter, and then // adds each item as a script.
[ "AddWitness", "adds", "each", "item", "of", "the", "passed", "filter", "stack", "to", "the", "filter", "and", "then", "adds", "each", "item", "as", "a", "script", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/gcs/builder/builder.go#L192-L199
149,587
btcsuite/btcutil
gcs/builder/builder.go
Build
func (b *GCSBuilder) Build() (*gcs.Filter, error) { // Do nothing if the builder's already errored out. if b.err != nil { return nil, b.err } // We'll ensure that all the parmaters we need to actually build the // filter properly are set. if b.p == 0 { return nil, fmt.Errorf("p value is not set, cannot build") } if b.m == 0 { return nil, fmt.Errorf("m value is not set, cannot build") } dataSlice := make([][]byte, 0, len(b.data)) for item := range b.data { dataSlice = append(dataSlice, []byte(item)) } return gcs.BuildGCSFilter(b.p, b.m, b.key, dataSlice) }
go
func (b *GCSBuilder) Build() (*gcs.Filter, error) { // Do nothing if the builder's already errored out. if b.err != nil { return nil, b.err } // We'll ensure that all the parmaters we need to actually build the // filter properly are set. if b.p == 0 { return nil, fmt.Errorf("p value is not set, cannot build") } if b.m == 0 { return nil, fmt.Errorf("m value is not set, cannot build") } dataSlice := make([][]byte, 0, len(b.data)) for item := range b.data { dataSlice = append(dataSlice, []byte(item)) } return gcs.BuildGCSFilter(b.p, b.m, b.key, dataSlice) }
[ "func", "(", "b", "*", "GCSBuilder", ")", "Build", "(", ")", "(", "*", "gcs", ".", "Filter", ",", "error", ")", "{", "// Do nothing if the builder's already errored out.", "if", "b", ".", "err", "!=", "nil", "{", "return", "nil", ",", "b", ".", "err", "\n", "}", "\n\n", "// We'll ensure that all the parmaters we need to actually build the", "// filter properly are set.", "if", "b", ".", "p", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "b", ".", "m", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "dataSlice", ":=", "make", "(", "[", "]", "[", "]", "byte", ",", "0", ",", "len", "(", "b", ".", "data", ")", ")", "\n", "for", "item", ":=", "range", "b", ".", "data", "{", "dataSlice", "=", "append", "(", "dataSlice", ",", "[", "]", "byte", "(", "item", ")", ")", "\n", "}", "\n\n", "return", "gcs", ".", "BuildGCSFilter", "(", "b", ".", "p", ",", "b", ".", "m", ",", "b", ".", "key", ",", "dataSlice", ")", "\n", "}" ]
// Build returns a function which builds a GCS filter with the given parameters // and data.
[ "Build", "returns", "a", "function", "which", "builds", "a", "GCS", "filter", "with", "the", "given", "parameters", "and", "data", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/gcs/builder/builder.go#L203-L224
149,588
btcsuite/btcutil
gcs/builder/builder.go
WithKeyPNM
func WithKeyPNM(key [gcs.KeySize]byte, p uint8, n uint32, m uint64) *GCSBuilder { b := GCSBuilder{} return b.SetKey(key).SetP(p).SetM(m).Preallocate(n) }
go
func WithKeyPNM(key [gcs.KeySize]byte, p uint8, n uint32, m uint64) *GCSBuilder { b := GCSBuilder{} return b.SetKey(key).SetP(p).SetM(m).Preallocate(n) }
[ "func", "WithKeyPNM", "(", "key", "[", "gcs", ".", "KeySize", "]", "byte", ",", "p", "uint8", ",", "n", "uint32", ",", "m", "uint64", ")", "*", "GCSBuilder", "{", "b", ":=", "GCSBuilder", "{", "}", "\n", "return", "b", ".", "SetKey", "(", "key", ")", ".", "SetP", "(", "p", ")", ".", "SetM", "(", "m", ")", ".", "Preallocate", "(", "n", ")", "\n", "}" ]
// WithKeyPNM creates a GCSBuilder with specified key and the passed // probability, modulus and estimated filter size.
[ "WithKeyPNM", "creates", "a", "GCSBuilder", "with", "specified", "key", "and", "the", "passed", "probability", "modulus", "and", "estimated", "filter", "size", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/gcs/builder/builder.go#L228-L231
149,589
btcsuite/btcutil
gcs/builder/builder.go
WithKeyPM
func WithKeyPM(key [gcs.KeySize]byte, p uint8, m uint64) *GCSBuilder { return WithKeyPNM(key, p, 0, m) }
go
func WithKeyPM(key [gcs.KeySize]byte, p uint8, m uint64) *GCSBuilder { return WithKeyPNM(key, p, 0, m) }
[ "func", "WithKeyPM", "(", "key", "[", "gcs", ".", "KeySize", "]", "byte", ",", "p", "uint8", ",", "m", "uint64", ")", "*", "GCSBuilder", "{", "return", "WithKeyPNM", "(", "key", ",", "p", ",", "0", ",", "m", ")", "\n", "}" ]
// WithKeyPM creates a GCSBuilder with specified key and the passed // probability. Estimated filter size is set to zero, which means more // reallocations are done when building the filter.
[ "WithKeyPM", "creates", "a", "GCSBuilder", "with", "specified", "key", "and", "the", "passed", "probability", ".", "Estimated", "filter", "size", "is", "set", "to", "zero", "which", "means", "more", "reallocations", "are", "done", "when", "building", "the", "filter", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/gcs/builder/builder.go#L236-L238
149,590
btcsuite/btcutil
gcs/builder/builder.go
WithKeyHashPNM
func WithKeyHashPNM(keyHash *chainhash.Hash, p uint8, n uint32, m uint64) *GCSBuilder { return WithKeyPNM(DeriveKey(keyHash), p, n, m) }
go
func WithKeyHashPNM(keyHash *chainhash.Hash, p uint8, n uint32, m uint64) *GCSBuilder { return WithKeyPNM(DeriveKey(keyHash), p, n, m) }
[ "func", "WithKeyHashPNM", "(", "keyHash", "*", "chainhash", ".", "Hash", ",", "p", "uint8", ",", "n", "uint32", ",", "m", "uint64", ")", "*", "GCSBuilder", "{", "return", "WithKeyPNM", "(", "DeriveKey", "(", "keyHash", ")", ",", "p", ",", "n", ",", "m", ")", "\n", "}" ]
// WithKeyHashPNM creates a GCSBuilder with key derived from the specified // chainhash.Hash and the passed probability and estimated filter size.
[ "WithKeyHashPNM", "creates", "a", "GCSBuilder", "with", "key", "derived", "from", "the", "specified", "chainhash", ".", "Hash", "and", "the", "passed", "probability", "and", "estimated", "filter", "size", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/gcs/builder/builder.go#L249-L253
149,591
btcsuite/btcutil
gcs/builder/builder.go
WithKeyHashPM
func WithKeyHashPM(keyHash *chainhash.Hash, p uint8, m uint64) *GCSBuilder { return WithKeyHashPNM(keyHash, p, 0, m) }
go
func WithKeyHashPM(keyHash *chainhash.Hash, p uint8, m uint64) *GCSBuilder { return WithKeyHashPNM(keyHash, p, 0, m) }
[ "func", "WithKeyHashPM", "(", "keyHash", "*", "chainhash", ".", "Hash", ",", "p", "uint8", ",", "m", "uint64", ")", "*", "GCSBuilder", "{", "return", "WithKeyHashPNM", "(", "keyHash", ",", "p", ",", "0", ",", "m", ")", "\n", "}" ]
// WithKeyHashPM creates a GCSBuilder with key derived from the specified // chainhash.Hash and the passed probability. Estimated filter size is set to // zero, which means more reallocations are done when building the filter.
[ "WithKeyHashPM", "creates", "a", "GCSBuilder", "with", "key", "derived", "from", "the", "specified", "chainhash", ".", "Hash", "and", "the", "passed", "probability", ".", "Estimated", "filter", "size", "is", "set", "to", "zero", "which", "means", "more", "reallocations", "are", "done", "when", "building", "the", "filter", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/gcs/builder/builder.go#L258-L260
149,592
btcsuite/btcutil
gcs/builder/builder.go
WithRandomKeyPNM
func WithRandomKeyPNM(p uint8, n uint32, m uint64) *GCSBuilder { key, err := RandomKey() if err != nil { b := GCSBuilder{err: err} return &b } return WithKeyPNM(key, p, n, m) }
go
func WithRandomKeyPNM(p uint8, n uint32, m uint64) *GCSBuilder { key, err := RandomKey() if err != nil { b := GCSBuilder{err: err} return &b } return WithKeyPNM(key, p, n, m) }
[ "func", "WithRandomKeyPNM", "(", "p", "uint8", ",", "n", "uint32", ",", "m", "uint64", ")", "*", "GCSBuilder", "{", "key", ",", "err", ":=", "RandomKey", "(", ")", "\n", "if", "err", "!=", "nil", "{", "b", ":=", "GCSBuilder", "{", "err", ":", "err", "}", "\n", "return", "&", "b", "\n", "}", "\n", "return", "WithKeyPNM", "(", "key", ",", "p", ",", "n", ",", "m", ")", "\n", "}" ]
// WithRandomKeyPNM creates a GCSBuilder with a cryptographically random key and // the passed probability and estimated filter size.
[ "WithRandomKeyPNM", "creates", "a", "GCSBuilder", "with", "a", "cryptographically", "random", "key", "and", "the", "passed", "probability", "and", "estimated", "filter", "size", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/gcs/builder/builder.go#L272-L279
149,593
btcsuite/btcutil
gcs/builder/builder.go
BuildBasicFilter
func BuildBasicFilter(block *wire.MsgBlock, prevOutScripts [][]byte) (*gcs.Filter, error) { blockHash := block.BlockHash() b := WithKeyHash(&blockHash) // If the filter had an issue with the specified key, then we force it // to bubble up here by calling the Key() function. _, err := b.Key() if err != nil { return nil, err } // In order to build a basic filter, we'll range over the entire block, // adding each whole script itself. for _, tx := range block.Transactions { // For each output in a transaction, we'll add each of the // individual data pushes within the script. for _, txOut := range tx.TxOut { if len(txOut.PkScript) == 0 { continue } // In order to allow the filters to later be committed // to within an OP_RETURN output, we ignore all // OP_RETURNs to avoid a circular dependency. if txOut.PkScript[0] == txscript.OP_RETURN { continue } b.AddEntry(txOut.PkScript) } } // In the second pass, we'll also add all the prevOutScripts // individually as elements. for _, prevScript := range prevOutScripts { if len(prevScript) == 0 { continue } b.AddEntry(prevScript) } return b.Build() }
go
func BuildBasicFilter(block *wire.MsgBlock, prevOutScripts [][]byte) (*gcs.Filter, error) { blockHash := block.BlockHash() b := WithKeyHash(&blockHash) // If the filter had an issue with the specified key, then we force it // to bubble up here by calling the Key() function. _, err := b.Key() if err != nil { return nil, err } // In order to build a basic filter, we'll range over the entire block, // adding each whole script itself. for _, tx := range block.Transactions { // For each output in a transaction, we'll add each of the // individual data pushes within the script. for _, txOut := range tx.TxOut { if len(txOut.PkScript) == 0 { continue } // In order to allow the filters to later be committed // to within an OP_RETURN output, we ignore all // OP_RETURNs to avoid a circular dependency. if txOut.PkScript[0] == txscript.OP_RETURN { continue } b.AddEntry(txOut.PkScript) } } // In the second pass, we'll also add all the prevOutScripts // individually as elements. for _, prevScript := range prevOutScripts { if len(prevScript) == 0 { continue } b.AddEntry(prevScript) } return b.Build() }
[ "func", "BuildBasicFilter", "(", "block", "*", "wire", ".", "MsgBlock", ",", "prevOutScripts", "[", "]", "[", "]", "byte", ")", "(", "*", "gcs", ".", "Filter", ",", "error", ")", "{", "blockHash", ":=", "block", ".", "BlockHash", "(", ")", "\n", "b", ":=", "WithKeyHash", "(", "&", "blockHash", ")", "\n\n", "// If the filter had an issue with the specified key, then we force it", "// to bubble up here by calling the Key() function.", "_", ",", "err", ":=", "b", ".", "Key", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// In order to build a basic filter, we'll range over the entire block,", "// adding each whole script itself.", "for", "_", ",", "tx", ":=", "range", "block", ".", "Transactions", "{", "// For each output in a transaction, we'll add each of the", "// individual data pushes within the script.", "for", "_", ",", "txOut", ":=", "range", "tx", ".", "TxOut", "{", "if", "len", "(", "txOut", ".", "PkScript", ")", "==", "0", "{", "continue", "\n", "}", "\n\n", "// In order to allow the filters to later be committed", "// to within an OP_RETURN output, we ignore all", "// OP_RETURNs to avoid a circular dependency.", "if", "txOut", ".", "PkScript", "[", "0", "]", "==", "txscript", ".", "OP_RETURN", "{", "continue", "\n", "}", "\n\n", "b", ".", "AddEntry", "(", "txOut", ".", "PkScript", ")", "\n", "}", "\n", "}", "\n\n", "// In the second pass, we'll also add all the prevOutScripts", "// individually as elements.", "for", "_", ",", "prevScript", ":=", "range", "prevOutScripts", "{", "if", "len", "(", "prevScript", ")", "==", "0", "{", "continue", "\n", "}", "\n\n", "b", ".", "AddEntry", "(", "prevScript", ")", "\n", "}", "\n\n", "return", "b", ".", "Build", "(", ")", "\n", "}" ]
// BuildBasicFilter builds a basic GCS filter from a block. A basic GCS filter // will contain all the previous output scripts spent by inputs within a block, // as well as the data pushes within all the outputs created within a block.
[ "BuildBasicFilter", "builds", "a", "basic", "GCS", "filter", "from", "a", "block", ".", "A", "basic", "GCS", "filter", "will", "contain", "all", "the", "previous", "output", "scripts", "spent", "by", "inputs", "within", "a", "block", "as", "well", "as", "the", "data", "pushes", "within", "all", "the", "outputs", "created", "within", "a", "block", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/gcs/builder/builder.go#L299-L342
149,594
btcsuite/btcutil
gcs/builder/builder.go
GetFilterHash
func GetFilterHash(filter *gcs.Filter) (chainhash.Hash, error) { filterData, err := filter.NBytes() if err != nil { return chainhash.Hash{}, err } return chainhash.DoubleHashH(filterData), nil }
go
func GetFilterHash(filter *gcs.Filter) (chainhash.Hash, error) { filterData, err := filter.NBytes() if err != nil { return chainhash.Hash{}, err } return chainhash.DoubleHashH(filterData), nil }
[ "func", "GetFilterHash", "(", "filter", "*", "gcs", ".", "Filter", ")", "(", "chainhash", ".", "Hash", ",", "error", ")", "{", "filterData", ",", "err", ":=", "filter", ".", "NBytes", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "chainhash", ".", "Hash", "{", "}", ",", "err", "\n", "}", "\n\n", "return", "chainhash", ".", "DoubleHashH", "(", "filterData", ")", ",", "nil", "\n", "}" ]
// GetFilterHash returns the double-SHA256 of the filter.
[ "GetFilterHash", "returns", "the", "double", "-", "SHA256", "of", "the", "filter", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/gcs/builder/builder.go#L345-L352
149,595
btcsuite/btcutil
gcs/builder/builder.go
MakeHeaderForFilter
func MakeHeaderForFilter(filter *gcs.Filter, prevHeader chainhash.Hash) (chainhash.Hash, error) { filterTip := make([]byte, 2*chainhash.HashSize) filterHash, err := GetFilterHash(filter) if err != nil { return chainhash.Hash{}, err } // In the buffer we created above we'll compute hash || prevHash as an // intermediate value. copy(filterTip, filterHash[:]) copy(filterTip[chainhash.HashSize:], prevHeader[:]) // The final filter hash is the double-sha256 of the hash computed // above. return chainhash.DoubleHashH(filterTip), nil }
go
func MakeHeaderForFilter(filter *gcs.Filter, prevHeader chainhash.Hash) (chainhash.Hash, error) { filterTip := make([]byte, 2*chainhash.HashSize) filterHash, err := GetFilterHash(filter) if err != nil { return chainhash.Hash{}, err } // In the buffer we created above we'll compute hash || prevHash as an // intermediate value. copy(filterTip, filterHash[:]) copy(filterTip[chainhash.HashSize:], prevHeader[:]) // The final filter hash is the double-sha256 of the hash computed // above. return chainhash.DoubleHashH(filterTip), nil }
[ "func", "MakeHeaderForFilter", "(", "filter", "*", "gcs", ".", "Filter", ",", "prevHeader", "chainhash", ".", "Hash", ")", "(", "chainhash", ".", "Hash", ",", "error", ")", "{", "filterTip", ":=", "make", "(", "[", "]", "byte", ",", "2", "*", "chainhash", ".", "HashSize", ")", "\n", "filterHash", ",", "err", ":=", "GetFilterHash", "(", "filter", ")", "\n", "if", "err", "!=", "nil", "{", "return", "chainhash", ".", "Hash", "{", "}", ",", "err", "\n", "}", "\n\n", "// In the buffer we created above we'll compute hash || prevHash as an", "// intermediate value.", "copy", "(", "filterTip", ",", "filterHash", "[", ":", "]", ")", "\n", "copy", "(", "filterTip", "[", "chainhash", ".", "HashSize", ":", "]", ",", "prevHeader", "[", ":", "]", ")", "\n\n", "// The final filter hash is the double-sha256 of the hash computed", "// above.", "return", "chainhash", ".", "DoubleHashH", "(", "filterTip", ")", ",", "nil", "\n", "}" ]
// MakeHeaderForFilter makes a filter chain header for a filter, given the // filter and the previous filter chain header.
[ "MakeHeaderForFilter", "makes", "a", "filter", "chain", "header", "for", "a", "filter", "given", "the", "filter", "and", "the", "previous", "filter", "chain", "header", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/gcs/builder/builder.go#L356-L371
149,596
btcsuite/btcutil
block.go
Bytes
func (b *Block) Bytes() ([]byte, error) { // Return the cached serialized bytes if it has already been generated. if len(b.serializedBlock) != 0 { return b.serializedBlock, nil } // Serialize the MsgBlock. w := bytes.NewBuffer(make([]byte, 0, b.msgBlock.SerializeSize())) err := b.msgBlock.Serialize(w) if err != nil { return nil, err } serializedBlock := w.Bytes() // Cache the serialized bytes and return them. b.serializedBlock = serializedBlock return serializedBlock, nil }
go
func (b *Block) Bytes() ([]byte, error) { // Return the cached serialized bytes if it has already been generated. if len(b.serializedBlock) != 0 { return b.serializedBlock, nil } // Serialize the MsgBlock. w := bytes.NewBuffer(make([]byte, 0, b.msgBlock.SerializeSize())) err := b.msgBlock.Serialize(w) if err != nil { return nil, err } serializedBlock := w.Bytes() // Cache the serialized bytes and return them. b.serializedBlock = serializedBlock return serializedBlock, nil }
[ "func", "(", "b", "*", "Block", ")", "Bytes", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// Return the cached serialized bytes if it has already been generated.", "if", "len", "(", "b", ".", "serializedBlock", ")", "!=", "0", "{", "return", "b", ".", "serializedBlock", ",", "nil", "\n", "}", "\n\n", "// Serialize the MsgBlock.", "w", ":=", "bytes", ".", "NewBuffer", "(", "make", "(", "[", "]", "byte", ",", "0", ",", "b", ".", "msgBlock", ".", "SerializeSize", "(", ")", ")", ")", "\n", "err", ":=", "b", ".", "msgBlock", ".", "Serialize", "(", "w", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "serializedBlock", ":=", "w", ".", "Bytes", "(", ")", "\n\n", "// Cache the serialized bytes and return them.", "b", ".", "serializedBlock", "=", "serializedBlock", "\n", "return", "serializedBlock", ",", "nil", "\n", "}" ]
// Bytes returns the serialized bytes for the Block. This is equivalent to // calling Serialize on the underlying wire.MsgBlock, however it caches the // result so subsequent calls are more efficient.
[ "Bytes", "returns", "the", "serialized", "bytes", "for", "the", "Block", ".", "This", "is", "equivalent", "to", "calling", "Serialize", "on", "the", "underlying", "wire", ".", "MsgBlock", "however", "it", "caches", "the", "result", "so", "subsequent", "calls", "are", "more", "efficient", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/block.go#L53-L70
149,597
btcsuite/btcutil
block.go
BytesNoWitness
func (b *Block) BytesNoWitness() ([]byte, error) { // Return the cached serialized bytes if it has already been generated. if len(b.serializedBlockNoWitness) != 0 { return b.serializedBlockNoWitness, nil } // Serialize the MsgBlock. var w bytes.Buffer err := b.msgBlock.SerializeNoWitness(&w) if err != nil { return nil, err } serializedBlock := w.Bytes() // Cache the serialized bytes and return them. b.serializedBlockNoWitness = serializedBlock return serializedBlock, nil }
go
func (b *Block) BytesNoWitness() ([]byte, error) { // Return the cached serialized bytes if it has already been generated. if len(b.serializedBlockNoWitness) != 0 { return b.serializedBlockNoWitness, nil } // Serialize the MsgBlock. var w bytes.Buffer err := b.msgBlock.SerializeNoWitness(&w) if err != nil { return nil, err } serializedBlock := w.Bytes() // Cache the serialized bytes and return them. b.serializedBlockNoWitness = serializedBlock return serializedBlock, nil }
[ "func", "(", "b", "*", "Block", ")", "BytesNoWitness", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// Return the cached serialized bytes if it has already been generated.", "if", "len", "(", "b", ".", "serializedBlockNoWitness", ")", "!=", "0", "{", "return", "b", ".", "serializedBlockNoWitness", ",", "nil", "\n", "}", "\n\n", "// Serialize the MsgBlock.", "var", "w", "bytes", ".", "Buffer", "\n", "err", ":=", "b", ".", "msgBlock", ".", "SerializeNoWitness", "(", "&", "w", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "serializedBlock", ":=", "w", ".", "Bytes", "(", ")", "\n\n", "// Cache the serialized bytes and return them.", "b", ".", "serializedBlockNoWitness", "=", "serializedBlock", "\n", "return", "serializedBlock", ",", "nil", "\n", "}" ]
// BytesNoWitness returns the serialized bytes for the block with transactions // encoded without any witness data.
[ "BytesNoWitness", "returns", "the", "serialized", "bytes", "for", "the", "block", "with", "transactions", "encoded", "without", "any", "witness", "data", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/block.go#L74-L91
149,598
btcsuite/btcutil
block.go
Hash
func (b *Block) Hash() *chainhash.Hash { // Return the cached block hash if it has already been generated. if b.blockHash != nil { return b.blockHash } // Cache the block hash and return it. hash := b.msgBlock.BlockHash() b.blockHash = &hash return &hash }
go
func (b *Block) Hash() *chainhash.Hash { // Return the cached block hash if it has already been generated. if b.blockHash != nil { return b.blockHash } // Cache the block hash and return it. hash := b.msgBlock.BlockHash() b.blockHash = &hash return &hash }
[ "func", "(", "b", "*", "Block", ")", "Hash", "(", ")", "*", "chainhash", ".", "Hash", "{", "// Return the cached block hash if it has already been generated.", "if", "b", ".", "blockHash", "!=", "nil", "{", "return", "b", ".", "blockHash", "\n", "}", "\n\n", "// Cache the block hash and return it.", "hash", ":=", "b", ".", "msgBlock", ".", "BlockHash", "(", ")", "\n", "b", ".", "blockHash", "=", "&", "hash", "\n", "return", "&", "hash", "\n", "}" ]
// Hash returns the block identifier hash for the Block. This is equivalent to // calling BlockHash on the underlying wire.MsgBlock, however it caches the // result so subsequent calls are more efficient.
[ "Hash", "returns", "the", "block", "identifier", "hash", "for", "the", "Block", ".", "This", "is", "equivalent", "to", "calling", "BlockHash", "on", "the", "underlying", "wire", ".", "MsgBlock", "however", "it", "caches", "the", "result", "so", "subsequent", "calls", "are", "more", "efficient", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/block.go#L96-L106
149,599
btcsuite/btcutil
block.go
TxHash
func (b *Block) TxHash(txNum int) (*chainhash.Hash, error) { // Attempt to get a wrapped transaction for the specified index. It // will be created lazily if needed or simply return the cached version // if it has already been generated. tx, err := b.Tx(txNum) if err != nil { return nil, err } // Defer to the wrapped transaction which will return the cached hash if // it has already been generated. return tx.Hash(), nil }
go
func (b *Block) TxHash(txNum int) (*chainhash.Hash, error) { // Attempt to get a wrapped transaction for the specified index. It // will be created lazily if needed or simply return the cached version // if it has already been generated. tx, err := b.Tx(txNum) if err != nil { return nil, err } // Defer to the wrapped transaction which will return the cached hash if // it has already been generated. return tx.Hash(), nil }
[ "func", "(", "b", "*", "Block", ")", "TxHash", "(", "txNum", "int", ")", "(", "*", "chainhash", ".", "Hash", ",", "error", ")", "{", "// Attempt to get a wrapped transaction for the specified index. It", "// will be created lazily if needed or simply return the cached version", "// if it has already been generated.", "tx", ",", "err", ":=", "b", ".", "Tx", "(", "txNum", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Defer to the wrapped transaction which will return the cached hash if", "// it has already been generated.", "return", "tx", ".", "Hash", "(", ")", ",", "nil", "\n", "}" ]
// TxHash returns the hash for the requested transaction number in the Block. // The supplied index is 0 based. That is to say, the first transaction in the // block is txNum 0. This is equivalent to calling TxHash on the underlying // wire.MsgTx, however it caches the result so subsequent calls are more // efficient.
[ "TxHash", "returns", "the", "hash", "for", "the", "requested", "transaction", "number", "in", "the", "Block", ".", "The", "supplied", "index", "is", "0", "based", ".", "That", "is", "to", "say", "the", "first", "transaction", "in", "the", "block", "is", "txNum", "0", ".", "This", "is", "equivalent", "to", "calling", "TxHash", "on", "the", "underlying", "wire", ".", "MsgTx", "however", "it", "caches", "the", "result", "so", "subsequent", "calls", "are", "more", "efficient", "." ]
9e5f4b9a998d263e3ce9c56664a7816001ac8000
https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/block.go#L176-L188