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
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
btcsuite/btcd
mining/cpuminer/cpuminer.go
New
func New(cfg *Config) *CPUMiner { return &CPUMiner{ g: cfg.BlockTemplateGenerator, cfg: *cfg, numWorkers: defaultNumWorkers, updateNumWorkers: make(chan struct{}), queryHashesPerSec: make(chan float64), updateHashes: make(chan uint64), } }
go
func New(cfg *Config) *CPUMiner { return &CPUMiner{ g: cfg.BlockTemplateGenerator, cfg: *cfg, numWorkers: defaultNumWorkers, updateNumWorkers: make(chan struct{}), queryHashesPerSec: make(chan float64), updateHashes: make(chan uint64), } }
[ "func", "New", "(", "cfg", "*", "Config", ")", "*", "CPUMiner", "{", "return", "&", "CPUMiner", "{", "g", ":", "cfg", ".", "BlockTemplateGenerator", ",", "cfg", ":", "*", "cfg", ",", "numWorkers", ":", "defaultNumWorkers", ",", "updateNumWorkers", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "queryHashesPerSec", ":", "make", "(", "chan", "float64", ")", ",", "updateHashes", ":", "make", "(", "chan", "uint64", ")", ",", "}", "\n", "}" ]
// New returns a new instance of a CPU miner for the provided configuration. // Use Start to begin the mining process. See the documentation for CPUMiner // type for more details.
[ "New", "returns", "a", "new", "instance", "of", "a", "CPU", "miner", "for", "the", "provided", "configuration", ".", "Use", "Start", "to", "begin", "the", "mining", "process", ".", "See", "the", "documentation", "for", "CPUMiner", "type", "for", "more", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/cpuminer/cpuminer.go#L633-L642
train
btcsuite/btcd
btcjson/help.go
reflectTypeToJSONType
func reflectTypeToJSONType(xT descLookupFunc, rt reflect.Type) string { kind := rt.Kind() if isNumeric(kind) { return xT("json-type-numeric") } switch kind { case reflect.String: return xT("json-type-string") case reflect.Bool: return xT("json-type-bool") case reflect.Array, reflect.Slice: return xT("json-type-array") + reflectTypeToJSONType(xT, rt.Elem()) case reflect.Struct: return xT("json-type-object") case reflect.Map: return xT("json-type-object") } return xT("json-type-value") }
go
func reflectTypeToJSONType(xT descLookupFunc, rt reflect.Type) string { kind := rt.Kind() if isNumeric(kind) { return xT("json-type-numeric") } switch kind { case reflect.String: return xT("json-type-string") case reflect.Bool: return xT("json-type-bool") case reflect.Array, reflect.Slice: return xT("json-type-array") + reflectTypeToJSONType(xT, rt.Elem()) case reflect.Struct: return xT("json-type-object") case reflect.Map: return xT("json-type-object") } return xT("json-type-value") }
[ "func", "reflectTypeToJSONType", "(", "xT", "descLookupFunc", ",", "rt", "reflect", ".", "Type", ")", "string", "{", "kind", ":=", "rt", ".", "Kind", "(", ")", "\n", "if", "isNumeric", "(", "kind", ")", "{", "return", "xT", "(", "\"", "\"", ")", "\n", "}", "\n\n", "switch", "kind", "{", "case", "reflect", ".", "String", ":", "return", "xT", "(", "\"", "\"", ")", "\n\n", "case", "reflect", ".", "Bool", ":", "return", "xT", "(", "\"", "\"", ")", "\n\n", "case", "reflect", ".", "Array", ",", "reflect", ".", "Slice", ":", "return", "xT", "(", "\"", "\"", ")", "+", "reflectTypeToJSONType", "(", "xT", ",", "rt", ".", "Elem", "(", ")", ")", "\n\n", "case", "reflect", ".", "Struct", ":", "return", "xT", "(", "\"", "\"", ")", "\n\n", "case", "reflect", ".", "Map", ":", "return", "xT", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "xT", "(", "\"", "\"", ")", "\n", "}" ]
// reflectTypeToJSONType returns a string that represents the JSON type // associated with the provided Go type.
[ "reflectTypeToJSONType", "returns", "a", "string", "that", "represents", "the", "JSON", "type", "associated", "with", "the", "provided", "Go", "type", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/help.go#L49-L74
train
btcsuite/btcd
btcjson/help.go
reflectTypeToJSONExample
func reflectTypeToJSONExample(xT descLookupFunc, rt reflect.Type, indentLevel int, fieldDescKey string) ([]string, bool) { // Indirect pointer if needed. if rt.Kind() == reflect.Ptr { rt = rt.Elem() } kind := rt.Kind() if isNumeric(kind) { if kind == reflect.Float32 || kind == reflect.Float64 { return []string{"n.nnn"}, false } return []string{"n"}, false } switch kind { case reflect.String: return []string{`"` + xT("json-example-string") + `"`}, false case reflect.Bool: return []string{xT("json-example-bool")}, false case reflect.Struct: indent := strings.Repeat(" ", indentLevel) results := resultStructHelp(xT, rt, indentLevel+1) // An opening brace is needed for the first indent level. For // all others, it will be included as a part of the previous // field. if indentLevel == 0 { newResults := make([]string, len(results)+1) newResults[0] = "{" copy(newResults[1:], results) results = newResults } // The closing brace has a comma after it except for the first // indent level. The final tabs are necessary so the tab writer // lines things up properly. closingBrace := indent + "}" if indentLevel > 0 { closingBrace += "," } results = append(results, closingBrace+"\t\t") return results, true case reflect.Array, reflect.Slice: results, isComplex := reflectTypeToJSONExample(xT, rt.Elem(), indentLevel, fieldDescKey) // When the result is complex, it is because this is an array of // objects. if isComplex { // When this is at indent level zero, there is no // previous field to house the opening array bracket, so // replace the opening object brace with the array // syntax. Also, replace the final closing object brace // with the variadiac array closing syntax. indent := strings.Repeat(" ", indentLevel) if indentLevel == 0 { results[0] = indent + "[{" results[len(results)-1] = indent + "},...]" return results, true } // At this point, the indent level is greater than 0, so // the opening array bracket and object brace are // already a part of the previous field. However, the // closing entry is a simple object brace, so replace it // with the variadiac array closing syntax. The final // tabs are necessary so the tab writer lines things up // properly. results[len(results)-1] = indent + "},...],\t\t" return results, true } // It's an array of primitives, so return the formatted text // accordingly. return []string{fmt.Sprintf("[%s,...]", results[0])}, false case reflect.Map: indent := strings.Repeat(" ", indentLevel) results := make([]string, 0, 3) // An opening brace is needed for the first indent level. For // all others, it will be included as a part of the previous // field. if indentLevel == 0 { results = append(results, indent+"{") } // Maps are a bit special in that they need to have the key, // value, and description of the object entry specifically // called out. innerIndent := strings.Repeat(" ", indentLevel+1) result := fmt.Sprintf("%s%q: %s, (%s) %s", innerIndent, xT(fieldDescKey+"--key"), xT(fieldDescKey+"--value"), reflectTypeToJSONType(xT, rt), xT(fieldDescKey+"--desc")) results = append(results, result) results = append(results, innerIndent+"...") results = append(results, indent+"}") return results, true } return []string{xT("json-example-unknown")}, false }
go
func reflectTypeToJSONExample(xT descLookupFunc, rt reflect.Type, indentLevel int, fieldDescKey string) ([]string, bool) { // Indirect pointer if needed. if rt.Kind() == reflect.Ptr { rt = rt.Elem() } kind := rt.Kind() if isNumeric(kind) { if kind == reflect.Float32 || kind == reflect.Float64 { return []string{"n.nnn"}, false } return []string{"n"}, false } switch kind { case reflect.String: return []string{`"` + xT("json-example-string") + `"`}, false case reflect.Bool: return []string{xT("json-example-bool")}, false case reflect.Struct: indent := strings.Repeat(" ", indentLevel) results := resultStructHelp(xT, rt, indentLevel+1) // An opening brace is needed for the first indent level. For // all others, it will be included as a part of the previous // field. if indentLevel == 0 { newResults := make([]string, len(results)+1) newResults[0] = "{" copy(newResults[1:], results) results = newResults } // The closing brace has a comma after it except for the first // indent level. The final tabs are necessary so the tab writer // lines things up properly. closingBrace := indent + "}" if indentLevel > 0 { closingBrace += "," } results = append(results, closingBrace+"\t\t") return results, true case reflect.Array, reflect.Slice: results, isComplex := reflectTypeToJSONExample(xT, rt.Elem(), indentLevel, fieldDescKey) // When the result is complex, it is because this is an array of // objects. if isComplex { // When this is at indent level zero, there is no // previous field to house the opening array bracket, so // replace the opening object brace with the array // syntax. Also, replace the final closing object brace // with the variadiac array closing syntax. indent := strings.Repeat(" ", indentLevel) if indentLevel == 0 { results[0] = indent + "[{" results[len(results)-1] = indent + "},...]" return results, true } // At this point, the indent level is greater than 0, so // the opening array bracket and object brace are // already a part of the previous field. However, the // closing entry is a simple object brace, so replace it // with the variadiac array closing syntax. The final // tabs are necessary so the tab writer lines things up // properly. results[len(results)-1] = indent + "},...],\t\t" return results, true } // It's an array of primitives, so return the formatted text // accordingly. return []string{fmt.Sprintf("[%s,...]", results[0])}, false case reflect.Map: indent := strings.Repeat(" ", indentLevel) results := make([]string, 0, 3) // An opening brace is needed for the first indent level. For // all others, it will be included as a part of the previous // field. if indentLevel == 0 { results = append(results, indent+"{") } // Maps are a bit special in that they need to have the key, // value, and description of the object entry specifically // called out. innerIndent := strings.Repeat(" ", indentLevel+1) result := fmt.Sprintf("%s%q: %s, (%s) %s", innerIndent, xT(fieldDescKey+"--key"), xT(fieldDescKey+"--value"), reflectTypeToJSONType(xT, rt), xT(fieldDescKey+"--desc")) results = append(results, result) results = append(results, innerIndent+"...") results = append(results, indent+"}") return results, true } return []string{xT("json-example-unknown")}, false }
[ "func", "reflectTypeToJSONExample", "(", "xT", "descLookupFunc", ",", "rt", "reflect", ".", "Type", ",", "indentLevel", "int", ",", "fieldDescKey", "string", ")", "(", "[", "]", "string", ",", "bool", ")", "{", "// Indirect pointer if needed.", "if", "rt", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "rt", "=", "rt", ".", "Elem", "(", ")", "\n", "}", "\n", "kind", ":=", "rt", ".", "Kind", "(", ")", "\n", "if", "isNumeric", "(", "kind", ")", "{", "if", "kind", "==", "reflect", ".", "Float32", "||", "kind", "==", "reflect", ".", "Float64", "{", "return", "[", "]", "string", "{", "\"", "\"", "}", ",", "false", "\n", "}", "\n\n", "return", "[", "]", "string", "{", "\"", "\"", "}", ",", "false", "\n", "}", "\n\n", "switch", "kind", "{", "case", "reflect", ".", "String", ":", "return", "[", "]", "string", "{", "`\"`", "+", "xT", "(", "\"", "\"", ")", "+", "`\"`", "}", ",", "false", "\n\n", "case", "reflect", ".", "Bool", ":", "return", "[", "]", "string", "{", "xT", "(", "\"", "\"", ")", "}", ",", "false", "\n\n", "case", "reflect", ".", "Struct", ":", "indent", ":=", "strings", ".", "Repeat", "(", "\"", "\"", ",", "indentLevel", ")", "\n", "results", ":=", "resultStructHelp", "(", "xT", ",", "rt", ",", "indentLevel", "+", "1", ")", "\n\n", "// An opening brace is needed for the first indent level. For", "// all others, it will be included as a part of the previous", "// field.", "if", "indentLevel", "==", "0", "{", "newResults", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "results", ")", "+", "1", ")", "\n", "newResults", "[", "0", "]", "=", "\"", "\"", "\n", "copy", "(", "newResults", "[", "1", ":", "]", ",", "results", ")", "\n", "results", "=", "newResults", "\n", "}", "\n\n", "// The closing brace has a comma after it except for the first", "// indent level. The final tabs are necessary so the tab writer", "// lines things up properly.", "closingBrace", ":=", "indent", "+", "\"", "\"", "\n", "if", "indentLevel", ">", "0", "{", "closingBrace", "+=", "\"", "\"", "\n", "}", "\n", "results", "=", "append", "(", "results", ",", "closingBrace", "+", "\"", "\\t", "\\t", "\"", ")", "\n", "return", "results", ",", "true", "\n\n", "case", "reflect", ".", "Array", ",", "reflect", ".", "Slice", ":", "results", ",", "isComplex", ":=", "reflectTypeToJSONExample", "(", "xT", ",", "rt", ".", "Elem", "(", ")", ",", "indentLevel", ",", "fieldDescKey", ")", "\n\n", "// When the result is complex, it is because this is an array of", "// objects.", "if", "isComplex", "{", "// When this is at indent level zero, there is no", "// previous field to house the opening array bracket, so", "// replace the opening object brace with the array", "// syntax. Also, replace the final closing object brace", "// with the variadiac array closing syntax.", "indent", ":=", "strings", ".", "Repeat", "(", "\"", "\"", ",", "indentLevel", ")", "\n", "if", "indentLevel", "==", "0", "{", "results", "[", "0", "]", "=", "indent", "+", "\"", "\"", "\n", "results", "[", "len", "(", "results", ")", "-", "1", "]", "=", "indent", "+", "\"", "\"", "\n", "return", "results", ",", "true", "\n", "}", "\n\n", "// At this point, the indent level is greater than 0, so", "// the opening array bracket and object brace are", "// already a part of the previous field. However, the", "// closing entry is a simple object brace, so replace it", "// with the variadiac array closing syntax. The final", "// tabs are necessary so the tab writer lines things up", "// properly.", "results", "[", "len", "(", "results", ")", "-", "1", "]", "=", "indent", "+", "\"", "\\t", "\\t", "\"", "\n", "return", "results", ",", "true", "\n", "}", "\n\n", "// It's an array of primitives, so return the formatted text", "// accordingly.", "return", "[", "]", "string", "{", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "results", "[", "0", "]", ")", "}", ",", "false", "\n\n", "case", "reflect", ".", "Map", ":", "indent", ":=", "strings", ".", "Repeat", "(", "\"", "\"", ",", "indentLevel", ")", "\n", "results", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "3", ")", "\n\n", "// An opening brace is needed for the first indent level. For", "// all others, it will be included as a part of the previous", "// field.", "if", "indentLevel", "==", "0", "{", "results", "=", "append", "(", "results", ",", "indent", "+", "\"", "\"", ")", "\n", "}", "\n\n", "// Maps are a bit special in that they need to have the key,", "// value, and description of the object entry specifically", "// called out.", "innerIndent", ":=", "strings", ".", "Repeat", "(", "\"", "\"", ",", "indentLevel", "+", "1", ")", "\n", "result", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "innerIndent", ",", "xT", "(", "fieldDescKey", "+", "\"", "\"", ")", ",", "xT", "(", "fieldDescKey", "+", "\"", "\"", ")", ",", "reflectTypeToJSONType", "(", "xT", ",", "rt", ")", ",", "xT", "(", "fieldDescKey", "+", "\"", "\"", ")", ")", "\n", "results", "=", "append", "(", "results", ",", "result", ")", "\n", "results", "=", "append", "(", "results", ",", "innerIndent", "+", "\"", "\"", ")", "\n\n", "results", "=", "append", "(", "results", ",", "indent", "+", "\"", "\"", ")", "\n", "return", "results", ",", "true", "\n", "}", "\n\n", "return", "[", "]", "string", "{", "xT", "(", "\"", "\"", ")", "}", ",", "false", "\n", "}" ]
// reflectTypeToJSONExample generates example usage in the format used by the // help output. It handles arrays, slices and structs recursively. The output // is returned as a slice of lines so the final help can be nicely aligned via // a tab writer. A bool is also returned which specifies whether or not the // type results in a complex JSON object since they need to be handled // differently.
[ "reflectTypeToJSONExample", "generates", "example", "usage", "in", "the", "format", "used", "by", "the", "help", "output", ".", "It", "handles", "arrays", "slices", "and", "structs", "recursively", ".", "The", "output", "is", "returned", "as", "a", "slice", "of", "lines", "so", "the", "final", "help", "can", "be", "nicely", "aligned", "via", "a", "tab", "writer", ".", "A", "bool", "is", "also", "returned", "which", "specifies", "whether", "or", "not", "the", "type", "results", "in", "a", "complex", "JSON", "object", "since", "they", "need", "to", "be", "handled", "differently", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/help.go#L143-L248
train
btcsuite/btcd
btcjson/help.go
resultTypeHelp
func resultTypeHelp(xT descLookupFunc, rt reflect.Type, fieldDescKey string) string { // Generate the JSON example for the result type. results, isComplex := reflectTypeToJSONExample(xT, rt, 0, fieldDescKey) // When this is a primitive type, add the associated JSON type and // result description into the final string, format it accordingly, // and return it. if !isComplex { return fmt.Sprintf("%s (%s) %s", results[0], reflectTypeToJSONType(xT, rt), xT(fieldDescKey)) } // At this point, this is a complex type that already has the JSON types // and descriptions in the results. Thus, use a tab writer to nicely // align the help text. var formatted bytes.Buffer w := new(tabwriter.Writer) w.Init(&formatted, 0, 4, 1, ' ', 0) for i, text := range results { if i == len(results)-1 { fmt.Fprintf(w, text) } else { fmt.Fprintln(w, text) } } w.Flush() return formatted.String() }
go
func resultTypeHelp(xT descLookupFunc, rt reflect.Type, fieldDescKey string) string { // Generate the JSON example for the result type. results, isComplex := reflectTypeToJSONExample(xT, rt, 0, fieldDescKey) // When this is a primitive type, add the associated JSON type and // result description into the final string, format it accordingly, // and return it. if !isComplex { return fmt.Sprintf("%s (%s) %s", results[0], reflectTypeToJSONType(xT, rt), xT(fieldDescKey)) } // At this point, this is a complex type that already has the JSON types // and descriptions in the results. Thus, use a tab writer to nicely // align the help text. var formatted bytes.Buffer w := new(tabwriter.Writer) w.Init(&formatted, 0, 4, 1, ' ', 0) for i, text := range results { if i == len(results)-1 { fmt.Fprintf(w, text) } else { fmt.Fprintln(w, text) } } w.Flush() return formatted.String() }
[ "func", "resultTypeHelp", "(", "xT", "descLookupFunc", ",", "rt", "reflect", ".", "Type", ",", "fieldDescKey", "string", ")", "string", "{", "// Generate the JSON example for the result type.", "results", ",", "isComplex", ":=", "reflectTypeToJSONExample", "(", "xT", ",", "rt", ",", "0", ",", "fieldDescKey", ")", "\n\n", "// When this is a primitive type, add the associated JSON type and", "// result description into the final string, format it accordingly,", "// and return it.", "if", "!", "isComplex", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "results", "[", "0", "]", ",", "reflectTypeToJSONType", "(", "xT", ",", "rt", ")", ",", "xT", "(", "fieldDescKey", ")", ")", "\n", "}", "\n\n", "// At this point, this is a complex type that already has the JSON types", "// and descriptions in the results. Thus, use a tab writer to nicely", "// align the help text.", "var", "formatted", "bytes", ".", "Buffer", "\n", "w", ":=", "new", "(", "tabwriter", ".", "Writer", ")", "\n", "w", ".", "Init", "(", "&", "formatted", ",", "0", ",", "4", ",", "1", ",", "' '", ",", "0", ")", "\n", "for", "i", ",", "text", ":=", "range", "results", "{", "if", "i", "==", "len", "(", "results", ")", "-", "1", "{", "fmt", ".", "Fprintf", "(", "w", ",", "text", ")", "\n", "}", "else", "{", "fmt", ".", "Fprintln", "(", "w", ",", "text", ")", "\n", "}", "\n", "}", "\n", "w", ".", "Flush", "(", ")", "\n", "return", "formatted", ".", "String", "(", ")", "\n", "}" ]
// resultTypeHelp generates and returns formatted help for the provided result // type.
[ "resultTypeHelp", "generates", "and", "returns", "formatted", "help", "for", "the", "provided", "result", "type", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/help.go#L252-L279
train
btcsuite/btcd
btcjson/help.go
argHelp
func argHelp(xT descLookupFunc, rtp reflect.Type, defaults map[int]reflect.Value, method string) string { // Return now if the command has no arguments. rt := rtp.Elem() numFields := rt.NumField() if numFields == 0 { return "" } // Generate the help for each argument in the command. Several // simplifying assumptions are made here because the RegisterCmd // function has already rigorously enforced the layout. args := make([]string, 0, numFields) for i := 0; i < numFields; i++ { rtf := rt.Field(i) var defaultVal *reflect.Value if defVal, ok := defaults[i]; ok { defaultVal = &defVal } fieldName := strings.ToLower(rtf.Name) helpText := fmt.Sprintf("%d.\t%s\t(%s)\t%s", i+1, fieldName, argTypeHelp(xT, rtf, defaultVal), xT(method+"-"+fieldName)) args = append(args, helpText) // For types which require a JSON object, or an array of JSON // objects, generate the full syntax for the argument. fieldType := rtf.Type if fieldType.Kind() == reflect.Ptr { fieldType = fieldType.Elem() } kind := fieldType.Kind() switch kind { case reflect.Struct: fieldDescKey := fmt.Sprintf("%s-%s", method, fieldName) resultText := resultTypeHelp(xT, fieldType, fieldDescKey) args = append(args, resultText) case reflect.Map: fieldDescKey := fmt.Sprintf("%s-%s", method, fieldName) resultText := resultTypeHelp(xT, fieldType, fieldDescKey) args = append(args, resultText) case reflect.Array, reflect.Slice: fieldDescKey := fmt.Sprintf("%s-%s", method, fieldName) if rtf.Type.Elem().Kind() == reflect.Struct { resultText := resultTypeHelp(xT, fieldType, fieldDescKey) args = append(args, resultText) } } } // Add argument names, types, and descriptions if there are any. Use a // tab writer to nicely align the help text. var formatted bytes.Buffer w := new(tabwriter.Writer) w.Init(&formatted, 0, 4, 1, ' ', 0) for _, text := range args { fmt.Fprintln(w, text) } w.Flush() return formatted.String() }
go
func argHelp(xT descLookupFunc, rtp reflect.Type, defaults map[int]reflect.Value, method string) string { // Return now if the command has no arguments. rt := rtp.Elem() numFields := rt.NumField() if numFields == 0 { return "" } // Generate the help for each argument in the command. Several // simplifying assumptions are made here because the RegisterCmd // function has already rigorously enforced the layout. args := make([]string, 0, numFields) for i := 0; i < numFields; i++ { rtf := rt.Field(i) var defaultVal *reflect.Value if defVal, ok := defaults[i]; ok { defaultVal = &defVal } fieldName := strings.ToLower(rtf.Name) helpText := fmt.Sprintf("%d.\t%s\t(%s)\t%s", i+1, fieldName, argTypeHelp(xT, rtf, defaultVal), xT(method+"-"+fieldName)) args = append(args, helpText) // For types which require a JSON object, or an array of JSON // objects, generate the full syntax for the argument. fieldType := rtf.Type if fieldType.Kind() == reflect.Ptr { fieldType = fieldType.Elem() } kind := fieldType.Kind() switch kind { case reflect.Struct: fieldDescKey := fmt.Sprintf("%s-%s", method, fieldName) resultText := resultTypeHelp(xT, fieldType, fieldDescKey) args = append(args, resultText) case reflect.Map: fieldDescKey := fmt.Sprintf("%s-%s", method, fieldName) resultText := resultTypeHelp(xT, fieldType, fieldDescKey) args = append(args, resultText) case reflect.Array, reflect.Slice: fieldDescKey := fmt.Sprintf("%s-%s", method, fieldName) if rtf.Type.Elem().Kind() == reflect.Struct { resultText := resultTypeHelp(xT, fieldType, fieldDescKey) args = append(args, resultText) } } } // Add argument names, types, and descriptions if there are any. Use a // tab writer to nicely align the help text. var formatted bytes.Buffer w := new(tabwriter.Writer) w.Init(&formatted, 0, 4, 1, ' ', 0) for _, text := range args { fmt.Fprintln(w, text) } w.Flush() return formatted.String() }
[ "func", "argHelp", "(", "xT", "descLookupFunc", ",", "rtp", "reflect", ".", "Type", ",", "defaults", "map", "[", "int", "]", "reflect", ".", "Value", ",", "method", "string", ")", "string", "{", "// Return now if the command has no arguments.", "rt", ":=", "rtp", ".", "Elem", "(", ")", "\n", "numFields", ":=", "rt", ".", "NumField", "(", ")", "\n", "if", "numFields", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n\n", "// Generate the help for each argument in the command. Several", "// simplifying assumptions are made here because the RegisterCmd", "// function has already rigorously enforced the layout.", "args", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "numFields", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "numFields", ";", "i", "++", "{", "rtf", ":=", "rt", ".", "Field", "(", "i", ")", "\n", "var", "defaultVal", "*", "reflect", ".", "Value", "\n", "if", "defVal", ",", "ok", ":=", "defaults", "[", "i", "]", ";", "ok", "{", "defaultVal", "=", "&", "defVal", "\n", "}", "\n\n", "fieldName", ":=", "strings", ".", "ToLower", "(", "rtf", ".", "Name", ")", "\n", "helpText", ":=", "fmt", ".", "Sprintf", "(", "\"", "\\t", "\\t", "\\t", "\"", ",", "i", "+", "1", ",", "fieldName", ",", "argTypeHelp", "(", "xT", ",", "rtf", ",", "defaultVal", ")", ",", "xT", "(", "method", "+", "\"", "\"", "+", "fieldName", ")", ")", "\n", "args", "=", "append", "(", "args", ",", "helpText", ")", "\n\n", "// For types which require a JSON object, or an array of JSON", "// objects, generate the full syntax for the argument.", "fieldType", ":=", "rtf", ".", "Type", "\n", "if", "fieldType", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "fieldType", "=", "fieldType", ".", "Elem", "(", ")", "\n", "}", "\n", "kind", ":=", "fieldType", ".", "Kind", "(", ")", "\n", "switch", "kind", "{", "case", "reflect", ".", "Struct", ":", "fieldDescKey", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "method", ",", "fieldName", ")", "\n", "resultText", ":=", "resultTypeHelp", "(", "xT", ",", "fieldType", ",", "fieldDescKey", ")", "\n", "args", "=", "append", "(", "args", ",", "resultText", ")", "\n\n", "case", "reflect", ".", "Map", ":", "fieldDescKey", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "method", ",", "fieldName", ")", "\n", "resultText", ":=", "resultTypeHelp", "(", "xT", ",", "fieldType", ",", "fieldDescKey", ")", "\n", "args", "=", "append", "(", "args", ",", "resultText", ")", "\n\n", "case", "reflect", ".", "Array", ",", "reflect", ".", "Slice", ":", "fieldDescKey", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "method", ",", "fieldName", ")", "\n", "if", "rtf", ".", "Type", ".", "Elem", "(", ")", ".", "Kind", "(", ")", "==", "reflect", ".", "Struct", "{", "resultText", ":=", "resultTypeHelp", "(", "xT", ",", "fieldType", ",", "fieldDescKey", ")", "\n", "args", "=", "append", "(", "args", ",", "resultText", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Add argument names, types, and descriptions if there are any. Use a", "// tab writer to nicely align the help text.", "var", "formatted", "bytes", ".", "Buffer", "\n", "w", ":=", "new", "(", "tabwriter", ".", "Writer", ")", "\n", "w", ".", "Init", "(", "&", "formatted", ",", "0", ",", "4", ",", "1", ",", "' '", ",", "0", ")", "\n", "for", "_", ",", "text", ":=", "range", "args", "{", "fmt", ".", "Fprintln", "(", "w", ",", "text", ")", "\n", "}", "\n", "w", ".", "Flush", "(", ")", "\n", "return", "formatted", ".", "String", "(", ")", "\n", "}" ]
// argHelp generates and returns formatted help for the provided command.
[ "argHelp", "generates", "and", "returns", "formatted", "help", "for", "the", "provided", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/help.go#L328-L391
train
btcsuite/btcd
btcjson/help.go
methodHelp
func methodHelp(xT descLookupFunc, rtp reflect.Type, defaults map[int]reflect.Value, method string, resultTypes []interface{}) string { // Start off with the method usage and help synopsis. help := fmt.Sprintf("%s\n\n%s\n", methodUsageText(rtp, defaults, method), xT(method+"--synopsis")) // Generate the help for each argument in the command. if argText := argHelp(xT, rtp, defaults, method); argText != "" { help += fmt.Sprintf("\n%s:\n%s", xT("help-arguments"), argText) } else { help += fmt.Sprintf("\n%s:\n%s\n", xT("help-arguments"), xT("help-arguments-none")) } // Generate the help text for each result type. resultTexts := make([]string, 0, len(resultTypes)) for i := range resultTypes { rtp := reflect.TypeOf(resultTypes[i]) fieldDescKey := fmt.Sprintf("%s--result%d", method, i) if resultTypes[i] == nil { resultText := xT("help-result-nothing") resultTexts = append(resultTexts, resultText) continue } resultText := resultTypeHelp(xT, rtp.Elem(), fieldDescKey) resultTexts = append(resultTexts, resultText) } // Add result types and descriptions. When there is more than one // result type, also add the condition which triggers it. if len(resultTexts) > 1 { for i, resultText := range resultTexts { condKey := fmt.Sprintf("%s--condition%d", method, i) help += fmt.Sprintf("\n%s (%s):\n%s\n", xT("help-result"), xT(condKey), resultText) } } else if len(resultTexts) > 0 { help += fmt.Sprintf("\n%s:\n%s\n", xT("help-result"), resultTexts[0]) } else { help += fmt.Sprintf("\n%s:\n%s\n", xT("help-result"), xT("help-result-nothing")) } return help }
go
func methodHelp(xT descLookupFunc, rtp reflect.Type, defaults map[int]reflect.Value, method string, resultTypes []interface{}) string { // Start off with the method usage and help synopsis. help := fmt.Sprintf("%s\n\n%s\n", methodUsageText(rtp, defaults, method), xT(method+"--synopsis")) // Generate the help for each argument in the command. if argText := argHelp(xT, rtp, defaults, method); argText != "" { help += fmt.Sprintf("\n%s:\n%s", xT("help-arguments"), argText) } else { help += fmt.Sprintf("\n%s:\n%s\n", xT("help-arguments"), xT("help-arguments-none")) } // Generate the help text for each result type. resultTexts := make([]string, 0, len(resultTypes)) for i := range resultTypes { rtp := reflect.TypeOf(resultTypes[i]) fieldDescKey := fmt.Sprintf("%s--result%d", method, i) if resultTypes[i] == nil { resultText := xT("help-result-nothing") resultTexts = append(resultTexts, resultText) continue } resultText := resultTypeHelp(xT, rtp.Elem(), fieldDescKey) resultTexts = append(resultTexts, resultText) } // Add result types and descriptions. When there is more than one // result type, also add the condition which triggers it. if len(resultTexts) > 1 { for i, resultText := range resultTexts { condKey := fmt.Sprintf("%s--condition%d", method, i) help += fmt.Sprintf("\n%s (%s):\n%s\n", xT("help-result"), xT(condKey), resultText) } } else if len(resultTexts) > 0 { help += fmt.Sprintf("\n%s:\n%s\n", xT("help-result"), resultTexts[0]) } else { help += fmt.Sprintf("\n%s:\n%s\n", xT("help-result"), xT("help-result-nothing")) } return help }
[ "func", "methodHelp", "(", "xT", "descLookupFunc", ",", "rtp", "reflect", ".", "Type", ",", "defaults", "map", "[", "int", "]", "reflect", ".", "Value", ",", "method", "string", ",", "resultTypes", "[", "]", "interface", "{", "}", ")", "string", "{", "// Start off with the method usage and help synopsis.", "help", ":=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\\n", "\\n", "\"", ",", "methodUsageText", "(", "rtp", ",", "defaults", ",", "method", ")", ",", "xT", "(", "method", "+", "\"", "\"", ")", ")", "\n\n", "// Generate the help for each argument in the command.", "if", "argText", ":=", "argHelp", "(", "xT", ",", "rtp", ",", "defaults", ",", "method", ")", ";", "argText", "!=", "\"", "\"", "{", "help", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\\n", "\"", ",", "xT", "(", "\"", "\"", ")", ",", "argText", ")", "\n", "}", "else", "{", "help", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\\n", "\\n", "\"", ",", "xT", "(", "\"", "\"", ")", ",", "xT", "(", "\"", "\"", ")", ")", "\n", "}", "\n\n", "// Generate the help text for each result type.", "resultTexts", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "resultTypes", ")", ")", "\n", "for", "i", ":=", "range", "resultTypes", "{", "rtp", ":=", "reflect", ".", "TypeOf", "(", "resultTypes", "[", "i", "]", ")", "\n", "fieldDescKey", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "method", ",", "i", ")", "\n", "if", "resultTypes", "[", "i", "]", "==", "nil", "{", "resultText", ":=", "xT", "(", "\"", "\"", ")", "\n", "resultTexts", "=", "append", "(", "resultTexts", ",", "resultText", ")", "\n", "continue", "\n", "}", "\n\n", "resultText", ":=", "resultTypeHelp", "(", "xT", ",", "rtp", ".", "Elem", "(", ")", ",", "fieldDescKey", ")", "\n", "resultTexts", "=", "append", "(", "resultTexts", ",", "resultText", ")", "\n", "}", "\n\n", "// Add result types and descriptions. When there is more than one", "// result type, also add the condition which triggers it.", "if", "len", "(", "resultTexts", ")", ">", "1", "{", "for", "i", ",", "resultText", ":=", "range", "resultTexts", "{", "condKey", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "method", ",", "i", ")", "\n", "help", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\\n", "\\n", "\"", ",", "xT", "(", "\"", "\"", ")", ",", "xT", "(", "condKey", ")", ",", "resultText", ")", "\n", "}", "\n", "}", "else", "if", "len", "(", "resultTexts", ")", ">", "0", "{", "help", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\\n", "\\n", "\"", ",", "xT", "(", "\"", "\"", ")", ",", "resultTexts", "[", "0", "]", ")", "\n", "}", "else", "{", "help", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\\n", "\\n", "\"", ",", "xT", "(", "\"", "\"", ")", ",", "xT", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "return", "help", "\n", "}" ]
// methodHelp generates and returns the help output for the provided command // and method info. This is the main work horse for the exported MethodHelp // function.
[ "methodHelp", "generates", "and", "returns", "the", "help", "output", "for", "the", "provided", "command", "and", "method", "info", ".", "This", "is", "the", "main", "work", "horse", "for", "the", "exported", "MethodHelp", "function", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/help.go#L396-L441
train
btcsuite/btcd
btcjson/help.go
isValidResultType
func isValidResultType(kind reflect.Kind) bool { if isNumeric(kind) { return true } switch kind { case reflect.String, reflect.Struct, reflect.Array, reflect.Slice, reflect.Bool, reflect.Map: return true } return false }
go
func isValidResultType(kind reflect.Kind) bool { if isNumeric(kind) { return true } switch kind { case reflect.String, reflect.Struct, reflect.Array, reflect.Slice, reflect.Bool, reflect.Map: return true } return false }
[ "func", "isValidResultType", "(", "kind", "reflect", ".", "Kind", ")", "bool", "{", "if", "isNumeric", "(", "kind", ")", "{", "return", "true", "\n", "}", "\n\n", "switch", "kind", "{", "case", "reflect", ".", "String", ",", "reflect", ".", "Struct", ",", "reflect", ".", "Array", ",", "reflect", ".", "Slice", ",", "reflect", ".", "Bool", ",", "reflect", ".", "Map", ":", "return", "true", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// isValidResultType returns whether the passed reflect kind is one of the // acceptable types for results.
[ "isValidResultType", "returns", "whether", "the", "passed", "reflect", "kind", "is", "one", "of", "the", "acceptable", "types", "for", "results", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/help.go#L445-L458
train
btcsuite/btcd
addrmgr/addrmanager.go
updateAddress
func (a *AddrManager) updateAddress(netAddr, srcAddr *wire.NetAddress) { // Filter out non-routable addresses. Note that non-routable // also includes invalid and local addresses. if !IsRoutable(netAddr) { return } addr := NetAddressKey(netAddr) ka := a.find(netAddr) if ka != nil { // TODO: only update addresses periodically. // Update the last seen time and services. // note that to prevent causing excess garbage on getaddr // messages the netaddresses in addrmaanger are *immutable*, // if we need to change them then we replace the pointer with a // new copy so that we don't have to copy every na for getaddr. if netAddr.Timestamp.After(ka.na.Timestamp) || (ka.na.Services&netAddr.Services) != netAddr.Services { naCopy := *ka.na naCopy.Timestamp = netAddr.Timestamp naCopy.AddService(netAddr.Services) ka.na = &naCopy } // If already in tried, we have nothing to do here. if ka.tried { return } // Already at our max? if ka.refs == newBucketsPerAddress { return } // The more entries we have, the less likely we are to add more. // likelihood is 2N. factor := int32(2 * ka.refs) if a.rand.Int31n(factor) != 0 { return } } else { // Make a copy of the net address to avoid races since it is // updated elsewhere in the addrmanager code and would otherwise // change the actual netaddress on the peer. netAddrCopy := *netAddr ka = &KnownAddress{na: &netAddrCopy, srcAddr: srcAddr} a.addrIndex[addr] = ka a.nNew++ // XXX time penalty? } bucket := a.getNewBucket(netAddr, srcAddr) // Already exists? if _, ok := a.addrNew[bucket][addr]; ok { return } // Enforce max addresses. if len(a.addrNew[bucket]) > newBucketSize { log.Tracef("new bucket is full, expiring old") a.expireNew(bucket) } // Add to new bucket. ka.refs++ a.addrNew[bucket][addr] = ka log.Tracef("Added new address %s for a total of %d addresses", addr, a.nTried+a.nNew) }
go
func (a *AddrManager) updateAddress(netAddr, srcAddr *wire.NetAddress) { // Filter out non-routable addresses. Note that non-routable // also includes invalid and local addresses. if !IsRoutable(netAddr) { return } addr := NetAddressKey(netAddr) ka := a.find(netAddr) if ka != nil { // TODO: only update addresses periodically. // Update the last seen time and services. // note that to prevent causing excess garbage on getaddr // messages the netaddresses in addrmaanger are *immutable*, // if we need to change them then we replace the pointer with a // new copy so that we don't have to copy every na for getaddr. if netAddr.Timestamp.After(ka.na.Timestamp) || (ka.na.Services&netAddr.Services) != netAddr.Services { naCopy := *ka.na naCopy.Timestamp = netAddr.Timestamp naCopy.AddService(netAddr.Services) ka.na = &naCopy } // If already in tried, we have nothing to do here. if ka.tried { return } // Already at our max? if ka.refs == newBucketsPerAddress { return } // The more entries we have, the less likely we are to add more. // likelihood is 2N. factor := int32(2 * ka.refs) if a.rand.Int31n(factor) != 0 { return } } else { // Make a copy of the net address to avoid races since it is // updated elsewhere in the addrmanager code and would otherwise // change the actual netaddress on the peer. netAddrCopy := *netAddr ka = &KnownAddress{na: &netAddrCopy, srcAddr: srcAddr} a.addrIndex[addr] = ka a.nNew++ // XXX time penalty? } bucket := a.getNewBucket(netAddr, srcAddr) // Already exists? if _, ok := a.addrNew[bucket][addr]; ok { return } // Enforce max addresses. if len(a.addrNew[bucket]) > newBucketSize { log.Tracef("new bucket is full, expiring old") a.expireNew(bucket) } // Add to new bucket. ka.refs++ a.addrNew[bucket][addr] = ka log.Tracef("Added new address %s for a total of %d addresses", addr, a.nTried+a.nNew) }
[ "func", "(", "a", "*", "AddrManager", ")", "updateAddress", "(", "netAddr", ",", "srcAddr", "*", "wire", ".", "NetAddress", ")", "{", "// Filter out non-routable addresses. Note that non-routable", "// also includes invalid and local addresses.", "if", "!", "IsRoutable", "(", "netAddr", ")", "{", "return", "\n", "}", "\n\n", "addr", ":=", "NetAddressKey", "(", "netAddr", ")", "\n", "ka", ":=", "a", ".", "find", "(", "netAddr", ")", "\n", "if", "ka", "!=", "nil", "{", "// TODO: only update addresses periodically.", "// Update the last seen time and services.", "// note that to prevent causing excess garbage on getaddr", "// messages the netaddresses in addrmaanger are *immutable*,", "// if we need to change them then we replace the pointer with a", "// new copy so that we don't have to copy every na for getaddr.", "if", "netAddr", ".", "Timestamp", ".", "After", "(", "ka", ".", "na", ".", "Timestamp", ")", "||", "(", "ka", ".", "na", ".", "Services", "&", "netAddr", ".", "Services", ")", "!=", "netAddr", ".", "Services", "{", "naCopy", ":=", "*", "ka", ".", "na", "\n", "naCopy", ".", "Timestamp", "=", "netAddr", ".", "Timestamp", "\n", "naCopy", ".", "AddService", "(", "netAddr", ".", "Services", ")", "\n", "ka", ".", "na", "=", "&", "naCopy", "\n", "}", "\n\n", "// If already in tried, we have nothing to do here.", "if", "ka", ".", "tried", "{", "return", "\n", "}", "\n\n", "// Already at our max?", "if", "ka", ".", "refs", "==", "newBucketsPerAddress", "{", "return", "\n", "}", "\n\n", "// The more entries we have, the less likely we are to add more.", "// likelihood is 2N.", "factor", ":=", "int32", "(", "2", "*", "ka", ".", "refs", ")", "\n", "if", "a", ".", "rand", ".", "Int31n", "(", "factor", ")", "!=", "0", "{", "return", "\n", "}", "\n", "}", "else", "{", "// Make a copy of the net address to avoid races since it is", "// updated elsewhere in the addrmanager code and would otherwise", "// change the actual netaddress on the peer.", "netAddrCopy", ":=", "*", "netAddr", "\n", "ka", "=", "&", "KnownAddress", "{", "na", ":", "&", "netAddrCopy", ",", "srcAddr", ":", "srcAddr", "}", "\n", "a", ".", "addrIndex", "[", "addr", "]", "=", "ka", "\n", "a", ".", "nNew", "++", "\n", "// XXX time penalty?", "}", "\n\n", "bucket", ":=", "a", ".", "getNewBucket", "(", "netAddr", ",", "srcAddr", ")", "\n\n", "// Already exists?", "if", "_", ",", "ok", ":=", "a", ".", "addrNew", "[", "bucket", "]", "[", "addr", "]", ";", "ok", "{", "return", "\n", "}", "\n\n", "// Enforce max addresses.", "if", "len", "(", "a", ".", "addrNew", "[", "bucket", "]", ")", ">", "newBucketSize", "{", "log", ".", "Tracef", "(", "\"", "\"", ")", "\n", "a", ".", "expireNew", "(", "bucket", ")", "\n", "}", "\n\n", "// Add to new bucket.", "ka", ".", "refs", "++", "\n", "a", ".", "addrNew", "[", "bucket", "]", "[", "addr", "]", "=", "ka", "\n\n", "log", ".", "Tracef", "(", "\"", "\"", ",", "addr", ",", "a", ".", "nTried", "+", "a", ".", "nNew", ")", "\n", "}" ]
// updateAddress is a helper function to either update an address already known // to the address manager, or to add the address if not already known.
[ "updateAddress", "is", "a", "helper", "function", "to", "either", "update", "an", "address", "already", "known", "to", "the", "address", "manager", "or", "to", "add", "the", "address", "if", "not", "already", "known", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/addrmanager.go#L166-L238
train
btcsuite/btcd
addrmgr/addrmanager.go
expireNew
func (a *AddrManager) expireNew(bucket int) { // First see if there are any entries that are so bad we can just throw // them away. otherwise we throw away the oldest entry in the cache. // Bitcoind here chooses four random and just throws the oldest of // those away, but we keep track of oldest in the initial traversal and // use that information instead. var oldest *KnownAddress for k, v := range a.addrNew[bucket] { if v.isBad() { log.Tracef("expiring bad address %v", k) delete(a.addrNew[bucket], k) v.refs-- if v.refs == 0 { a.nNew-- delete(a.addrIndex, k) } continue } if oldest == nil { oldest = v } else if !v.na.Timestamp.After(oldest.na.Timestamp) { oldest = v } } if oldest != nil { key := NetAddressKey(oldest.na) log.Tracef("expiring oldest address %v", key) delete(a.addrNew[bucket], key) oldest.refs-- if oldest.refs == 0 { a.nNew-- delete(a.addrIndex, key) } } }
go
func (a *AddrManager) expireNew(bucket int) { // First see if there are any entries that are so bad we can just throw // them away. otherwise we throw away the oldest entry in the cache. // Bitcoind here chooses four random and just throws the oldest of // those away, but we keep track of oldest in the initial traversal and // use that information instead. var oldest *KnownAddress for k, v := range a.addrNew[bucket] { if v.isBad() { log.Tracef("expiring bad address %v", k) delete(a.addrNew[bucket], k) v.refs-- if v.refs == 0 { a.nNew-- delete(a.addrIndex, k) } continue } if oldest == nil { oldest = v } else if !v.na.Timestamp.After(oldest.na.Timestamp) { oldest = v } } if oldest != nil { key := NetAddressKey(oldest.na) log.Tracef("expiring oldest address %v", key) delete(a.addrNew[bucket], key) oldest.refs-- if oldest.refs == 0 { a.nNew-- delete(a.addrIndex, key) } } }
[ "func", "(", "a", "*", "AddrManager", ")", "expireNew", "(", "bucket", "int", ")", "{", "// First see if there are any entries that are so bad we can just throw", "// them away. otherwise we throw away the oldest entry in the cache.", "// Bitcoind here chooses four random and just throws the oldest of", "// those away, but we keep track of oldest in the initial traversal and", "// use that information instead.", "var", "oldest", "*", "KnownAddress", "\n", "for", "k", ",", "v", ":=", "range", "a", ".", "addrNew", "[", "bucket", "]", "{", "if", "v", ".", "isBad", "(", ")", "{", "log", ".", "Tracef", "(", "\"", "\"", ",", "k", ")", "\n", "delete", "(", "a", ".", "addrNew", "[", "bucket", "]", ",", "k", ")", "\n", "v", ".", "refs", "--", "\n", "if", "v", ".", "refs", "==", "0", "{", "a", ".", "nNew", "--", "\n", "delete", "(", "a", ".", "addrIndex", ",", "k", ")", "\n", "}", "\n", "continue", "\n", "}", "\n", "if", "oldest", "==", "nil", "{", "oldest", "=", "v", "\n", "}", "else", "if", "!", "v", ".", "na", ".", "Timestamp", ".", "After", "(", "oldest", ".", "na", ".", "Timestamp", ")", "{", "oldest", "=", "v", "\n", "}", "\n", "}", "\n\n", "if", "oldest", "!=", "nil", "{", "key", ":=", "NetAddressKey", "(", "oldest", ".", "na", ")", "\n", "log", ".", "Tracef", "(", "\"", "\"", ",", "key", ")", "\n\n", "delete", "(", "a", ".", "addrNew", "[", "bucket", "]", ",", "key", ")", "\n", "oldest", ".", "refs", "--", "\n", "if", "oldest", ".", "refs", "==", "0", "{", "a", ".", "nNew", "--", "\n", "delete", "(", "a", ".", "addrIndex", ",", "key", ")", "\n", "}", "\n", "}", "\n", "}" ]
// expireNew makes space in the new buckets by expiring the really bad entries. // If no bad entries are available we look at a few and remove the oldest.
[ "expireNew", "makes", "space", "in", "the", "new", "buckets", "by", "expiring", "the", "really", "bad", "entries", ".", "If", "no", "bad", "entries", "are", "available", "we", "look", "at", "a", "few", "and", "remove", "the", "oldest", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/addrmanager.go#L242-L278
train
btcsuite/btcd
addrmgr/addrmanager.go
pickTried
func (a *AddrManager) pickTried(bucket int) *list.Element { var oldest *KnownAddress var oldestElem *list.Element for e := a.addrTried[bucket].Front(); e != nil; e = e.Next() { ka := e.Value.(*KnownAddress) if oldest == nil || oldest.na.Timestamp.After(ka.na.Timestamp) { oldestElem = e oldest = ka } } return oldestElem }
go
func (a *AddrManager) pickTried(bucket int) *list.Element { var oldest *KnownAddress var oldestElem *list.Element for e := a.addrTried[bucket].Front(); e != nil; e = e.Next() { ka := e.Value.(*KnownAddress) if oldest == nil || oldest.na.Timestamp.After(ka.na.Timestamp) { oldestElem = e oldest = ka } } return oldestElem }
[ "func", "(", "a", "*", "AddrManager", ")", "pickTried", "(", "bucket", "int", ")", "*", "list", ".", "Element", "{", "var", "oldest", "*", "KnownAddress", "\n", "var", "oldestElem", "*", "list", ".", "Element", "\n", "for", "e", ":=", "a", ".", "addrTried", "[", "bucket", "]", ".", "Front", "(", ")", ";", "e", "!=", "nil", ";", "e", "=", "e", ".", "Next", "(", ")", "{", "ka", ":=", "e", ".", "Value", ".", "(", "*", "KnownAddress", ")", "\n", "if", "oldest", "==", "nil", "||", "oldest", ".", "na", ".", "Timestamp", ".", "After", "(", "ka", ".", "na", ".", "Timestamp", ")", "{", "oldestElem", "=", "e", "\n", "oldest", "=", "ka", "\n", "}", "\n\n", "}", "\n", "return", "oldestElem", "\n", "}" ]
// pickTried selects an address from the tried bucket to be evicted. // We just choose the eldest. Bitcoind selects 4 random entries and throws away // the older of them.
[ "pickTried", "selects", "an", "address", "from", "the", "tried", "bucket", "to", "be", "evicted", ".", "We", "just", "choose", "the", "eldest", ".", "Bitcoind", "selects", "4", "random", "entries", "and", "throws", "away", "the", "older", "of", "them", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/addrmanager.go#L283-L295
train
btcsuite/btcd
addrmgr/addrmanager.go
addressHandler
func (a *AddrManager) addressHandler() { dumpAddressTicker := time.NewTicker(dumpAddressInterval) defer dumpAddressTicker.Stop() out: for { select { case <-dumpAddressTicker.C: a.savePeers() case <-a.quit: break out } } a.savePeers() a.wg.Done() log.Trace("Address handler done") }
go
func (a *AddrManager) addressHandler() { dumpAddressTicker := time.NewTicker(dumpAddressInterval) defer dumpAddressTicker.Stop() out: for { select { case <-dumpAddressTicker.C: a.savePeers() case <-a.quit: break out } } a.savePeers() a.wg.Done() log.Trace("Address handler done") }
[ "func", "(", "a", "*", "AddrManager", ")", "addressHandler", "(", ")", "{", "dumpAddressTicker", ":=", "time", ".", "NewTicker", "(", "dumpAddressInterval", ")", "\n", "defer", "dumpAddressTicker", ".", "Stop", "(", ")", "\n", "out", ":", "for", "{", "select", "{", "case", "<-", "dumpAddressTicker", ".", "C", ":", "a", ".", "savePeers", "(", ")", "\n\n", "case", "<-", "a", ".", "quit", ":", "break", "out", "\n", "}", "\n", "}", "\n", "a", ".", "savePeers", "(", ")", "\n", "a", ".", "wg", ".", "Done", "(", ")", "\n", "log", ".", "Trace", "(", "\"", "\"", ")", "\n", "}" ]
// addressHandler is the main handler for the address manager. It must be run // as a goroutine.
[ "addressHandler", "is", "the", "main", "handler", "for", "the", "address", "manager", ".", "It", "must", "be", "run", "as", "a", "goroutine", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/addrmanager.go#L341-L357
train
btcsuite/btcd
addrmgr/addrmanager.go
savePeers
func (a *AddrManager) savePeers() { a.mtx.Lock() defer a.mtx.Unlock() // First we make a serialisable datastructure so we can encode it to // json. sam := new(serializedAddrManager) sam.Version = a.version copy(sam.Key[:], a.key[:]) sam.Addresses = make([]*serializedKnownAddress, len(a.addrIndex)) i := 0 for k, v := range a.addrIndex { ska := new(serializedKnownAddress) ska.Addr = k ska.TimeStamp = v.na.Timestamp.Unix() ska.Src = NetAddressKey(v.srcAddr) ska.Attempts = v.attempts ska.LastAttempt = v.lastattempt.Unix() ska.LastSuccess = v.lastsuccess.Unix() if a.version > 1 { ska.Services = v.na.Services ska.SrcServices = v.srcAddr.Services } // Tried and refs are implicit in the rest of the structure // and will be worked out from context on unserialisation. sam.Addresses[i] = ska i++ } for i := range a.addrNew { sam.NewBuckets[i] = make([]string, len(a.addrNew[i])) j := 0 for k := range a.addrNew[i] { sam.NewBuckets[i][j] = k j++ } } for i := range a.addrTried { sam.TriedBuckets[i] = make([]string, a.addrTried[i].Len()) j := 0 for e := a.addrTried[i].Front(); e != nil; e = e.Next() { ka := e.Value.(*KnownAddress) sam.TriedBuckets[i][j] = NetAddressKey(ka.na) j++ } } w, err := os.Create(a.peersFile) if err != nil { log.Errorf("Error opening file %s: %v", a.peersFile, err) return } enc := json.NewEncoder(w) defer w.Close() if err := enc.Encode(&sam); err != nil { log.Errorf("Failed to encode file %s: %v", a.peersFile, err) return } }
go
func (a *AddrManager) savePeers() { a.mtx.Lock() defer a.mtx.Unlock() // First we make a serialisable datastructure so we can encode it to // json. sam := new(serializedAddrManager) sam.Version = a.version copy(sam.Key[:], a.key[:]) sam.Addresses = make([]*serializedKnownAddress, len(a.addrIndex)) i := 0 for k, v := range a.addrIndex { ska := new(serializedKnownAddress) ska.Addr = k ska.TimeStamp = v.na.Timestamp.Unix() ska.Src = NetAddressKey(v.srcAddr) ska.Attempts = v.attempts ska.LastAttempt = v.lastattempt.Unix() ska.LastSuccess = v.lastsuccess.Unix() if a.version > 1 { ska.Services = v.na.Services ska.SrcServices = v.srcAddr.Services } // Tried and refs are implicit in the rest of the structure // and will be worked out from context on unserialisation. sam.Addresses[i] = ska i++ } for i := range a.addrNew { sam.NewBuckets[i] = make([]string, len(a.addrNew[i])) j := 0 for k := range a.addrNew[i] { sam.NewBuckets[i][j] = k j++ } } for i := range a.addrTried { sam.TriedBuckets[i] = make([]string, a.addrTried[i].Len()) j := 0 for e := a.addrTried[i].Front(); e != nil; e = e.Next() { ka := e.Value.(*KnownAddress) sam.TriedBuckets[i][j] = NetAddressKey(ka.na) j++ } } w, err := os.Create(a.peersFile) if err != nil { log.Errorf("Error opening file %s: %v", a.peersFile, err) return } enc := json.NewEncoder(w) defer w.Close() if err := enc.Encode(&sam); err != nil { log.Errorf("Failed to encode file %s: %v", a.peersFile, err) return } }
[ "func", "(", "a", "*", "AddrManager", ")", "savePeers", "(", ")", "{", "a", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "// First we make a serialisable datastructure so we can encode it to", "// json.", "sam", ":=", "new", "(", "serializedAddrManager", ")", "\n", "sam", ".", "Version", "=", "a", ".", "version", "\n", "copy", "(", "sam", ".", "Key", "[", ":", "]", ",", "a", ".", "key", "[", ":", "]", ")", "\n\n", "sam", ".", "Addresses", "=", "make", "(", "[", "]", "*", "serializedKnownAddress", ",", "len", "(", "a", ".", "addrIndex", ")", ")", "\n", "i", ":=", "0", "\n", "for", "k", ",", "v", ":=", "range", "a", ".", "addrIndex", "{", "ska", ":=", "new", "(", "serializedKnownAddress", ")", "\n", "ska", ".", "Addr", "=", "k", "\n", "ska", ".", "TimeStamp", "=", "v", ".", "na", ".", "Timestamp", ".", "Unix", "(", ")", "\n", "ska", ".", "Src", "=", "NetAddressKey", "(", "v", ".", "srcAddr", ")", "\n", "ska", ".", "Attempts", "=", "v", ".", "attempts", "\n", "ska", ".", "LastAttempt", "=", "v", ".", "lastattempt", ".", "Unix", "(", ")", "\n", "ska", ".", "LastSuccess", "=", "v", ".", "lastsuccess", ".", "Unix", "(", ")", "\n", "if", "a", ".", "version", ">", "1", "{", "ska", ".", "Services", "=", "v", ".", "na", ".", "Services", "\n", "ska", ".", "SrcServices", "=", "v", ".", "srcAddr", ".", "Services", "\n", "}", "\n", "// Tried and refs are implicit in the rest of the structure", "// and will be worked out from context on unserialisation.", "sam", ".", "Addresses", "[", "i", "]", "=", "ska", "\n", "i", "++", "\n", "}", "\n", "for", "i", ":=", "range", "a", ".", "addrNew", "{", "sam", ".", "NewBuckets", "[", "i", "]", "=", "make", "(", "[", "]", "string", ",", "len", "(", "a", ".", "addrNew", "[", "i", "]", ")", ")", "\n", "j", ":=", "0", "\n", "for", "k", ":=", "range", "a", ".", "addrNew", "[", "i", "]", "{", "sam", ".", "NewBuckets", "[", "i", "]", "[", "j", "]", "=", "k", "\n", "j", "++", "\n", "}", "\n", "}", "\n", "for", "i", ":=", "range", "a", ".", "addrTried", "{", "sam", ".", "TriedBuckets", "[", "i", "]", "=", "make", "(", "[", "]", "string", ",", "a", ".", "addrTried", "[", "i", "]", ".", "Len", "(", ")", ")", "\n", "j", ":=", "0", "\n", "for", "e", ":=", "a", ".", "addrTried", "[", "i", "]", ".", "Front", "(", ")", ";", "e", "!=", "nil", ";", "e", "=", "e", ".", "Next", "(", ")", "{", "ka", ":=", "e", ".", "Value", ".", "(", "*", "KnownAddress", ")", "\n", "sam", ".", "TriedBuckets", "[", "i", "]", "[", "j", "]", "=", "NetAddressKey", "(", "ka", ".", "na", ")", "\n", "j", "++", "\n", "}", "\n", "}", "\n\n", "w", ",", "err", ":=", "os", ".", "Create", "(", "a", ".", "peersFile", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "a", ".", "peersFile", ",", "err", ")", "\n", "return", "\n", "}", "\n", "enc", ":=", "json", ".", "NewEncoder", "(", "w", ")", "\n", "defer", "w", ".", "Close", "(", ")", "\n", "if", "err", ":=", "enc", ".", "Encode", "(", "&", "sam", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "a", ".", "peersFile", ",", "err", ")", "\n", "return", "\n", "}", "\n", "}" ]
// savePeers saves all the known addresses to a file so they can be read back // in at next run.
[ "savePeers", "saves", "all", "the", "known", "addresses", "to", "a", "file", "so", "they", "can", "be", "read", "back", "in", "at", "next", "run", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/addrmanager.go#L361-L419
train
btcsuite/btcd
addrmgr/addrmanager.go
loadPeers
func (a *AddrManager) loadPeers() { a.mtx.Lock() defer a.mtx.Unlock() err := a.deserializePeers(a.peersFile) if err != nil { log.Errorf("Failed to parse file %s: %v", a.peersFile, err) // if it is invalid we nuke the old one unconditionally. err = os.Remove(a.peersFile) if err != nil { log.Warnf("Failed to remove corrupt peers file %s: %v", a.peersFile, err) } a.reset() return } log.Infof("Loaded %d addresses from file '%s'", a.numAddresses(), a.peersFile) }
go
func (a *AddrManager) loadPeers() { a.mtx.Lock() defer a.mtx.Unlock() err := a.deserializePeers(a.peersFile) if err != nil { log.Errorf("Failed to parse file %s: %v", a.peersFile, err) // if it is invalid we nuke the old one unconditionally. err = os.Remove(a.peersFile) if err != nil { log.Warnf("Failed to remove corrupt peers file %s: %v", a.peersFile, err) } a.reset() return } log.Infof("Loaded %d addresses from file '%s'", a.numAddresses(), a.peersFile) }
[ "func", "(", "a", "*", "AddrManager", ")", "loadPeers", "(", ")", "{", "a", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "err", ":=", "a", ".", "deserializePeers", "(", "a", ".", "peersFile", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "a", ".", "peersFile", ",", "err", ")", "\n", "// if it is invalid we nuke the old one unconditionally.", "err", "=", "os", ".", "Remove", "(", "a", ".", "peersFile", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "a", ".", "peersFile", ",", "err", ")", "\n", "}", "\n", "a", ".", "reset", "(", ")", "\n", "return", "\n", "}", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "a", ".", "numAddresses", "(", ")", ",", "a", ".", "peersFile", ")", "\n", "}" ]
// loadPeers loads the known address from the saved file. If empty, missing, or // malformed file, just don't load anything and start fresh
[ "loadPeers", "loads", "the", "known", "address", "from", "the", "saved", "file", ".", "If", "empty", "missing", "or", "malformed", "file", "just", "don", "t", "load", "anything", "and", "start", "fresh" ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/addrmanager.go#L423-L440
train
btcsuite/btcd
addrmgr/addrmanager.go
Start
func (a *AddrManager) Start() { // Already started? if atomic.AddInt32(&a.started, 1) != 1 { return } log.Trace("Starting address manager") // Load peers we already know about from file. a.loadPeers() // Start the address ticker to save addresses periodically. a.wg.Add(1) go a.addressHandler() }
go
func (a *AddrManager) Start() { // Already started? if atomic.AddInt32(&a.started, 1) != 1 { return } log.Trace("Starting address manager") // Load peers we already know about from file. a.loadPeers() // Start the address ticker to save addresses periodically. a.wg.Add(1) go a.addressHandler() }
[ "func", "(", "a", "*", "AddrManager", ")", "Start", "(", ")", "{", "// Already started?", "if", "atomic", ".", "AddInt32", "(", "&", "a", ".", "started", ",", "1", ")", "!=", "1", "{", "return", "\n", "}", "\n\n", "log", ".", "Trace", "(", "\"", "\"", ")", "\n\n", "// Load peers we already know about from file.", "a", ".", "loadPeers", "(", ")", "\n\n", "// Start the address ticker to save addresses periodically.", "a", ".", "wg", ".", "Add", "(", "1", ")", "\n", "go", "a", ".", "addressHandler", "(", ")", "\n", "}" ]
// Start begins the core address handler which manages a pool of known // addresses, timeouts, and interval based writes.
[ "Start", "begins", "the", "core", "address", "handler", "which", "manages", "a", "pool", "of", "known", "addresses", "timeouts", "and", "interval", "based", "writes", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/addrmanager.go#L567-L581
train
btcsuite/btcd
addrmgr/addrmanager.go
Stop
func (a *AddrManager) Stop() error { if atomic.AddInt32(&a.shutdown, 1) != 1 { log.Warnf("Address manager is already in the process of " + "shutting down") return nil } log.Infof("Address manager shutting down") close(a.quit) a.wg.Wait() return nil }
go
func (a *AddrManager) Stop() error { if atomic.AddInt32(&a.shutdown, 1) != 1 { log.Warnf("Address manager is already in the process of " + "shutting down") return nil } log.Infof("Address manager shutting down") close(a.quit) a.wg.Wait() return nil }
[ "func", "(", "a", "*", "AddrManager", ")", "Stop", "(", ")", "error", "{", "if", "atomic", ".", "AddInt32", "(", "&", "a", ".", "shutdown", ",", "1", ")", "!=", "1", "{", "log", ".", "Warnf", "(", "\"", "\"", "+", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "log", ".", "Infof", "(", "\"", "\"", ")", "\n", "close", "(", "a", ".", "quit", ")", "\n", "a", ".", "wg", ".", "Wait", "(", ")", "\n", "return", "nil", "\n", "}" ]
// Stop gracefully shuts down the address manager by stopping the main handler.
[ "Stop", "gracefully", "shuts", "down", "the", "address", "manager", "by", "stopping", "the", "main", "handler", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/addrmanager.go#L584-L595
train
btcsuite/btcd
addrmgr/addrmanager.go
AddAddresses
func (a *AddrManager) AddAddresses(addrs []*wire.NetAddress, srcAddr *wire.NetAddress) { a.mtx.Lock() defer a.mtx.Unlock() for _, na := range addrs { a.updateAddress(na, srcAddr) } }
go
func (a *AddrManager) AddAddresses(addrs []*wire.NetAddress, srcAddr *wire.NetAddress) { a.mtx.Lock() defer a.mtx.Unlock() for _, na := range addrs { a.updateAddress(na, srcAddr) } }
[ "func", "(", "a", "*", "AddrManager", ")", "AddAddresses", "(", "addrs", "[", "]", "*", "wire", ".", "NetAddress", ",", "srcAddr", "*", "wire", ".", "NetAddress", ")", "{", "a", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "for", "_", ",", "na", ":=", "range", "addrs", "{", "a", ".", "updateAddress", "(", "na", ",", "srcAddr", ")", "\n", "}", "\n", "}" ]
// AddAddresses adds new addresses to the address manager. It enforces a max // number of addresses and silently ignores duplicate addresses. It is // safe for concurrent access.
[ "AddAddresses", "adds", "new", "addresses", "to", "the", "address", "manager", ".", "It", "enforces", "a", "max", "number", "of", "addresses", "and", "silently", "ignores", "duplicate", "addresses", ".", "It", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/addrmanager.go#L600-L607
train
btcsuite/btcd
addrmgr/addrmanager.go
AddAddress
func (a *AddrManager) AddAddress(addr, srcAddr *wire.NetAddress) { a.mtx.Lock() defer a.mtx.Unlock() a.updateAddress(addr, srcAddr) }
go
func (a *AddrManager) AddAddress(addr, srcAddr *wire.NetAddress) { a.mtx.Lock() defer a.mtx.Unlock() a.updateAddress(addr, srcAddr) }
[ "func", "(", "a", "*", "AddrManager", ")", "AddAddress", "(", "addr", ",", "srcAddr", "*", "wire", ".", "NetAddress", ")", "{", "a", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "a", ".", "updateAddress", "(", "addr", ",", "srcAddr", ")", "\n", "}" ]
// AddAddress adds a new address to the address manager. It enforces a max // number of addresses and silently ignores duplicate addresses. It is // safe for concurrent access.
[ "AddAddress", "adds", "a", "new", "address", "to", "the", "address", "manager", ".", "It", "enforces", "a", "max", "number", "of", "addresses", "and", "silently", "ignores", "duplicate", "addresses", ".", "It", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/addrmanager.go#L612-L617
train
btcsuite/btcd
addrmgr/addrmanager.go
NumAddresses
func (a *AddrManager) NumAddresses() int { a.mtx.Lock() defer a.mtx.Unlock() return a.numAddresses() }
go
func (a *AddrManager) NumAddresses() int { a.mtx.Lock() defer a.mtx.Unlock() return a.numAddresses() }
[ "func", "(", "a", "*", "AddrManager", ")", "NumAddresses", "(", ")", "int", "{", "a", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "return", "a", ".", "numAddresses", "(", ")", "\n", "}" ]
// NumAddresses returns the number of addresses known to the address manager.
[ "NumAddresses", "returns", "the", "number", "of", "addresses", "known", "to", "the", "address", "manager", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/addrmanager.go#L647-L652
train
btcsuite/btcd
addrmgr/addrmanager.go
NeedMoreAddresses
func (a *AddrManager) NeedMoreAddresses() bool { a.mtx.Lock() defer a.mtx.Unlock() return a.numAddresses() < needAddressThreshold }
go
func (a *AddrManager) NeedMoreAddresses() bool { a.mtx.Lock() defer a.mtx.Unlock() return a.numAddresses() < needAddressThreshold }
[ "func", "(", "a", "*", "AddrManager", ")", "NeedMoreAddresses", "(", ")", "bool", "{", "a", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "return", "a", ".", "numAddresses", "(", ")", "<", "needAddressThreshold", "\n", "}" ]
// NeedMoreAddresses returns whether or not the address manager needs more // addresses.
[ "NeedMoreAddresses", "returns", "whether", "or", "not", "the", "address", "manager", "needs", "more", "addresses", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/addrmanager.go#L656-L661
train
btcsuite/btcd
addrmgr/addrmanager.go
getAddresses
func (a *AddrManager) getAddresses() []*wire.NetAddress { a.mtx.Lock() defer a.mtx.Unlock() addrIndexLen := len(a.addrIndex) if addrIndexLen == 0 { return nil } addrs := make([]*wire.NetAddress, 0, addrIndexLen) for _, v := range a.addrIndex { addrs = append(addrs, v.na) } return addrs }
go
func (a *AddrManager) getAddresses() []*wire.NetAddress { a.mtx.Lock() defer a.mtx.Unlock() addrIndexLen := len(a.addrIndex) if addrIndexLen == 0 { return nil } addrs := make([]*wire.NetAddress, 0, addrIndexLen) for _, v := range a.addrIndex { addrs = append(addrs, v.na) } return addrs }
[ "func", "(", "a", "*", "AddrManager", ")", "getAddresses", "(", ")", "[", "]", "*", "wire", ".", "NetAddress", "{", "a", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "addrIndexLen", ":=", "len", "(", "a", ".", "addrIndex", ")", "\n", "if", "addrIndexLen", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "addrs", ":=", "make", "(", "[", "]", "*", "wire", ".", "NetAddress", ",", "0", ",", "addrIndexLen", ")", "\n", "for", "_", ",", "v", ":=", "range", "a", ".", "addrIndex", "{", "addrs", "=", "append", "(", "addrs", ",", "v", ".", "na", ")", "\n", "}", "\n\n", "return", "addrs", "\n", "}" ]
// getAddresses returns all of the addresses currently found within the // manager's address cache.
[ "getAddresses", "returns", "all", "of", "the", "addresses", "currently", "found", "within", "the", "manager", "s", "address", "cache", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/addrmanager.go#L687-L702
train
btcsuite/btcd
addrmgr/addrmanager.go
reset
func (a *AddrManager) reset() { a.addrIndex = make(map[string]*KnownAddress) // fill key with bytes from a good random source. io.ReadFull(crand.Reader, a.key[:]) for i := range a.addrNew { a.addrNew[i] = make(map[string]*KnownAddress) } for i := range a.addrTried { a.addrTried[i] = list.New() } }
go
func (a *AddrManager) reset() { a.addrIndex = make(map[string]*KnownAddress) // fill key with bytes from a good random source. io.ReadFull(crand.Reader, a.key[:]) for i := range a.addrNew { a.addrNew[i] = make(map[string]*KnownAddress) } for i := range a.addrTried { a.addrTried[i] = list.New() } }
[ "func", "(", "a", "*", "AddrManager", ")", "reset", "(", ")", "{", "a", ".", "addrIndex", "=", "make", "(", "map", "[", "string", "]", "*", "KnownAddress", ")", "\n\n", "// fill key with bytes from a good random source.", "io", ".", "ReadFull", "(", "crand", ".", "Reader", ",", "a", ".", "key", "[", ":", "]", ")", "\n", "for", "i", ":=", "range", "a", ".", "addrNew", "{", "a", ".", "addrNew", "[", "i", "]", "=", "make", "(", "map", "[", "string", "]", "*", "KnownAddress", ")", "\n", "}", "\n", "for", "i", ":=", "range", "a", ".", "addrTried", "{", "a", ".", "addrTried", "[", "i", "]", "=", "list", ".", "New", "(", ")", "\n", "}", "\n", "}" ]
// reset resets the address manager by reinitialising the random source // and allocating fresh empty bucket storage.
[ "reset", "resets", "the", "address", "manager", "by", "reinitialising", "the", "random", "source", "and", "allocating", "fresh", "empty", "bucket", "storage", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/addrmanager.go#L706-L718
train
btcsuite/btcd
addrmgr/addrmanager.go
ipString
func ipString(na *wire.NetAddress) string { if IsOnionCatTor(na) { // We know now that na.IP is long enough. base32 := base32.StdEncoding.EncodeToString(na.IP[6:]) return strings.ToLower(base32) + ".onion" } return na.IP.String() }
go
func ipString(na *wire.NetAddress) string { if IsOnionCatTor(na) { // We know now that na.IP is long enough. base32 := base32.StdEncoding.EncodeToString(na.IP[6:]) return strings.ToLower(base32) + ".onion" } return na.IP.String() }
[ "func", "ipString", "(", "na", "*", "wire", ".", "NetAddress", ")", "string", "{", "if", "IsOnionCatTor", "(", "na", ")", "{", "// We know now that na.IP is long enough.", "base32", ":=", "base32", ".", "StdEncoding", ".", "EncodeToString", "(", "na", ".", "IP", "[", "6", ":", "]", ")", "\n", "return", "strings", ".", "ToLower", "(", "base32", ")", "+", "\"", "\"", "\n", "}", "\n\n", "return", "na", ".", "IP", ".", "String", "(", ")", "\n", "}" ]
// ipString returns a string for the ip from the provided NetAddress. If the // ip is in the range used for Tor addresses then it will be transformed into // the relevant .onion address.
[ "ipString", "returns", "a", "string", "for", "the", "ip", "from", "the", "provided", "NetAddress", ".", "If", "the", "ip", "is", "in", "the", "range", "used", "for", "Tor", "addresses", "then", "it", "will", "be", "transformed", "into", "the", "relevant", ".", "onion", "address", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/addrmanager.go#L754-L762
train
btcsuite/btcd
addrmgr/addrmanager.go
GetAddress
func (a *AddrManager) GetAddress() *KnownAddress { // Protect concurrent access. a.mtx.Lock() defer a.mtx.Unlock() if a.numAddresses() == 0 { return nil } // Use a 50% chance for choosing between tried and new table entries. if a.nTried > 0 && (a.nNew == 0 || a.rand.Intn(2) == 0) { // Tried entry. large := 1 << 30 factor := 1.0 for { // pick a random bucket. bucket := a.rand.Intn(len(a.addrTried)) if a.addrTried[bucket].Len() == 0 { continue } // Pick a random entry in the list e := a.addrTried[bucket].Front() for i := a.rand.Int63n(int64(a.addrTried[bucket].Len())); i > 0; i-- { e = e.Next() } ka := e.Value.(*KnownAddress) randval := a.rand.Intn(large) if float64(randval) < (factor * ka.chance() * float64(large)) { log.Tracef("Selected %v from tried bucket", NetAddressKey(ka.na)) return ka } factor *= 1.2 } } else { // new node. // XXX use a closure/function to avoid repeating this. large := 1 << 30 factor := 1.0 for { // Pick a random bucket. bucket := a.rand.Intn(len(a.addrNew)) if len(a.addrNew[bucket]) == 0 { continue } // Then, a random entry in it. var ka *KnownAddress nth := a.rand.Intn(len(a.addrNew[bucket])) for _, value := range a.addrNew[bucket] { if nth == 0 { ka = value } nth-- } randval := a.rand.Intn(large) if float64(randval) < (factor * ka.chance() * float64(large)) { log.Tracef("Selected %v from new bucket", NetAddressKey(ka.na)) return ka } factor *= 1.2 } } }
go
func (a *AddrManager) GetAddress() *KnownAddress { // Protect concurrent access. a.mtx.Lock() defer a.mtx.Unlock() if a.numAddresses() == 0 { return nil } // Use a 50% chance for choosing between tried and new table entries. if a.nTried > 0 && (a.nNew == 0 || a.rand.Intn(2) == 0) { // Tried entry. large := 1 << 30 factor := 1.0 for { // pick a random bucket. bucket := a.rand.Intn(len(a.addrTried)) if a.addrTried[bucket].Len() == 0 { continue } // Pick a random entry in the list e := a.addrTried[bucket].Front() for i := a.rand.Int63n(int64(a.addrTried[bucket].Len())); i > 0; i-- { e = e.Next() } ka := e.Value.(*KnownAddress) randval := a.rand.Intn(large) if float64(randval) < (factor * ka.chance() * float64(large)) { log.Tracef("Selected %v from tried bucket", NetAddressKey(ka.na)) return ka } factor *= 1.2 } } else { // new node. // XXX use a closure/function to avoid repeating this. large := 1 << 30 factor := 1.0 for { // Pick a random bucket. bucket := a.rand.Intn(len(a.addrNew)) if len(a.addrNew[bucket]) == 0 { continue } // Then, a random entry in it. var ka *KnownAddress nth := a.rand.Intn(len(a.addrNew[bucket])) for _, value := range a.addrNew[bucket] { if nth == 0 { ka = value } nth-- } randval := a.rand.Intn(large) if float64(randval) < (factor * ka.chance() * float64(large)) { log.Tracef("Selected %v from new bucket", NetAddressKey(ka.na)) return ka } factor *= 1.2 } } }
[ "func", "(", "a", "*", "AddrManager", ")", "GetAddress", "(", ")", "*", "KnownAddress", "{", "// Protect concurrent access.", "a", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "if", "a", ".", "numAddresses", "(", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "// Use a 50% chance for choosing between tried and new table entries.", "if", "a", ".", "nTried", ">", "0", "&&", "(", "a", ".", "nNew", "==", "0", "||", "a", ".", "rand", ".", "Intn", "(", "2", ")", "==", "0", ")", "{", "// Tried entry.", "large", ":=", "1", "<<", "30", "\n", "factor", ":=", "1.0", "\n", "for", "{", "// pick a random bucket.", "bucket", ":=", "a", ".", "rand", ".", "Intn", "(", "len", "(", "a", ".", "addrTried", ")", ")", "\n", "if", "a", ".", "addrTried", "[", "bucket", "]", ".", "Len", "(", ")", "==", "0", "{", "continue", "\n", "}", "\n\n", "// Pick a random entry in the list", "e", ":=", "a", ".", "addrTried", "[", "bucket", "]", ".", "Front", "(", ")", "\n", "for", "i", ":=", "a", ".", "rand", ".", "Int63n", "(", "int64", "(", "a", ".", "addrTried", "[", "bucket", "]", ".", "Len", "(", ")", ")", ")", ";", "i", ">", "0", ";", "i", "--", "{", "e", "=", "e", ".", "Next", "(", ")", "\n", "}", "\n", "ka", ":=", "e", ".", "Value", ".", "(", "*", "KnownAddress", ")", "\n", "randval", ":=", "a", ".", "rand", ".", "Intn", "(", "large", ")", "\n", "if", "float64", "(", "randval", ")", "<", "(", "factor", "*", "ka", ".", "chance", "(", ")", "*", "float64", "(", "large", ")", ")", "{", "log", ".", "Tracef", "(", "\"", "\"", ",", "NetAddressKey", "(", "ka", ".", "na", ")", ")", "\n", "return", "ka", "\n", "}", "\n", "factor", "*=", "1.2", "\n", "}", "\n", "}", "else", "{", "// new node.", "// XXX use a closure/function to avoid repeating this.", "large", ":=", "1", "<<", "30", "\n", "factor", ":=", "1.0", "\n", "for", "{", "// Pick a random bucket.", "bucket", ":=", "a", ".", "rand", ".", "Intn", "(", "len", "(", "a", ".", "addrNew", ")", ")", "\n", "if", "len", "(", "a", ".", "addrNew", "[", "bucket", "]", ")", "==", "0", "{", "continue", "\n", "}", "\n", "// Then, a random entry in it.", "var", "ka", "*", "KnownAddress", "\n", "nth", ":=", "a", ".", "rand", ".", "Intn", "(", "len", "(", "a", ".", "addrNew", "[", "bucket", "]", ")", ")", "\n", "for", "_", ",", "value", ":=", "range", "a", ".", "addrNew", "[", "bucket", "]", "{", "if", "nth", "==", "0", "{", "ka", "=", "value", "\n", "}", "\n", "nth", "--", "\n", "}", "\n", "randval", ":=", "a", ".", "rand", ".", "Intn", "(", "large", ")", "\n", "if", "float64", "(", "randval", ")", "<", "(", "factor", "*", "ka", ".", "chance", "(", ")", "*", "float64", "(", "large", ")", ")", "{", "log", ".", "Tracef", "(", "\"", "\"", ",", "NetAddressKey", "(", "ka", ".", "na", ")", ")", "\n", "return", "ka", "\n", "}", "\n", "factor", "*=", "1.2", "\n", "}", "\n", "}", "\n", "}" ]
// GetAddress returns a single address that should be routable. It picks a // random one from the possible addresses with preference given to ones that // have not been used recently and should not pick 'close' addresses // consecutively.
[ "GetAddress", "returns", "a", "single", "address", "that", "should", "be", "routable", ".", "It", "picks", "a", "random", "one", "from", "the", "possible", "addresses", "with", "preference", "given", "to", "ones", "that", "have", "not", "been", "used", "recently", "and", "should", "not", "pick", "close", "addresses", "consecutively", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/addrmanager.go#L776-L841
train
btcsuite/btcd
addrmgr/addrmanager.go
Attempt
func (a *AddrManager) Attempt(addr *wire.NetAddress) { a.mtx.Lock() defer a.mtx.Unlock() // find address. // Surely address will be in tried by now? ka := a.find(addr) if ka == nil { return } // set last tried time to now ka.attempts++ ka.lastattempt = time.Now() }
go
func (a *AddrManager) Attempt(addr *wire.NetAddress) { a.mtx.Lock() defer a.mtx.Unlock() // find address. // Surely address will be in tried by now? ka := a.find(addr) if ka == nil { return } // set last tried time to now ka.attempts++ ka.lastattempt = time.Now() }
[ "func", "(", "a", "*", "AddrManager", ")", "Attempt", "(", "addr", "*", "wire", ".", "NetAddress", ")", "{", "a", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "// find address.", "// Surely address will be in tried by now?", "ka", ":=", "a", ".", "find", "(", "addr", ")", "\n", "if", "ka", "==", "nil", "{", "return", "\n", "}", "\n", "// set last tried time to now", "ka", ".", "attempts", "++", "\n", "ka", ".", "lastattempt", "=", "time", ".", "Now", "(", ")", "\n", "}" ]
// Attempt increases the given address' attempt counter and updates // the last attempt time.
[ "Attempt", "increases", "the", "given", "address", "attempt", "counter", "and", "updates", "the", "last", "attempt", "time", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/addrmanager.go#L849-L862
train
btcsuite/btcd
addrmgr/addrmanager.go
Connected
func (a *AddrManager) Connected(addr *wire.NetAddress) { a.mtx.Lock() defer a.mtx.Unlock() ka := a.find(addr) if ka == nil { return } // Update the time as long as it has been 20 minutes since last we did // so. now := time.Now() if now.After(ka.na.Timestamp.Add(time.Minute * 20)) { // ka.na is immutable, so replace it. naCopy := *ka.na naCopy.Timestamp = time.Now() ka.na = &naCopy } }
go
func (a *AddrManager) Connected(addr *wire.NetAddress) { a.mtx.Lock() defer a.mtx.Unlock() ka := a.find(addr) if ka == nil { return } // Update the time as long as it has been 20 minutes since last we did // so. now := time.Now() if now.After(ka.na.Timestamp.Add(time.Minute * 20)) { // ka.na is immutable, so replace it. naCopy := *ka.na naCopy.Timestamp = time.Now() ka.na = &naCopy } }
[ "func", "(", "a", "*", "AddrManager", ")", "Connected", "(", "addr", "*", "wire", ".", "NetAddress", ")", "{", "a", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "ka", ":=", "a", ".", "find", "(", "addr", ")", "\n", "if", "ka", "==", "nil", "{", "return", "\n", "}", "\n\n", "// Update the time as long as it has been 20 minutes since last we did", "// so.", "now", ":=", "time", ".", "Now", "(", ")", "\n", "if", "now", ".", "After", "(", "ka", ".", "na", ".", "Timestamp", ".", "Add", "(", "time", ".", "Minute", "*", "20", ")", ")", "{", "// ka.na is immutable, so replace it.", "naCopy", ":=", "*", "ka", ".", "na", "\n", "naCopy", ".", "Timestamp", "=", "time", ".", "Now", "(", ")", "\n", "ka", ".", "na", "=", "&", "naCopy", "\n", "}", "\n", "}" ]
// Connected Marks the given address as currently connected and working at the // current time. The address must already be known to AddrManager else it will // be ignored.
[ "Connected", "Marks", "the", "given", "address", "as", "currently", "connected", "and", "working", "at", "the", "current", "time", ".", "The", "address", "must", "already", "be", "known", "to", "AddrManager", "else", "it", "will", "be", "ignored", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/addrmanager.go#L867-L885
train
btcsuite/btcd
addrmgr/addrmanager.go
Good
func (a *AddrManager) Good(addr *wire.NetAddress) { a.mtx.Lock() defer a.mtx.Unlock() ka := a.find(addr) if ka == nil { return } // ka.Timestamp is not updated here to avoid leaking information // about currently connected peers. now := time.Now() ka.lastsuccess = now ka.lastattempt = now ka.attempts = 0 // move to tried set, optionally evicting other addresses if neeed. if ka.tried { return } // ok, need to move it to tried. // remove from all new buckets. // record one of the buckets in question and call it the `first' addrKey := NetAddressKey(addr) oldBucket := -1 for i := range a.addrNew { // we check for existence so we can record the first one if _, ok := a.addrNew[i][addrKey]; ok { delete(a.addrNew[i], addrKey) ka.refs-- if oldBucket == -1 { oldBucket = i } } } a.nNew-- if oldBucket == -1 { // What? wasn't in a bucket after all.... Panic? return } bucket := a.getTriedBucket(ka.na) // Room in this tried bucket? if a.addrTried[bucket].Len() < triedBucketSize { ka.tried = true a.addrTried[bucket].PushBack(ka) a.nTried++ return } // No room, we have to evict something else. entry := a.pickTried(bucket) rmka := entry.Value.(*KnownAddress) // First bucket it would have been put in. newBucket := a.getNewBucket(rmka.na, rmka.srcAddr) // If no room in the original bucket, we put it in a bucket we just // freed up a space in. if len(a.addrNew[newBucket]) >= newBucketSize { newBucket = oldBucket } // replace with ka in list. ka.tried = true entry.Value = ka rmka.tried = false rmka.refs++ // We don't touch a.nTried here since the number of tried stays the same // but we decemented new above, raise it again since we're putting // something back. a.nNew++ rmkey := NetAddressKey(rmka.na) log.Tracef("Replacing %s with %s in tried", rmkey, addrKey) // We made sure there is space here just above. a.addrNew[newBucket][rmkey] = rmka }
go
func (a *AddrManager) Good(addr *wire.NetAddress) { a.mtx.Lock() defer a.mtx.Unlock() ka := a.find(addr) if ka == nil { return } // ka.Timestamp is not updated here to avoid leaking information // about currently connected peers. now := time.Now() ka.lastsuccess = now ka.lastattempt = now ka.attempts = 0 // move to tried set, optionally evicting other addresses if neeed. if ka.tried { return } // ok, need to move it to tried. // remove from all new buckets. // record one of the buckets in question and call it the `first' addrKey := NetAddressKey(addr) oldBucket := -1 for i := range a.addrNew { // we check for existence so we can record the first one if _, ok := a.addrNew[i][addrKey]; ok { delete(a.addrNew[i], addrKey) ka.refs-- if oldBucket == -1 { oldBucket = i } } } a.nNew-- if oldBucket == -1 { // What? wasn't in a bucket after all.... Panic? return } bucket := a.getTriedBucket(ka.na) // Room in this tried bucket? if a.addrTried[bucket].Len() < triedBucketSize { ka.tried = true a.addrTried[bucket].PushBack(ka) a.nTried++ return } // No room, we have to evict something else. entry := a.pickTried(bucket) rmka := entry.Value.(*KnownAddress) // First bucket it would have been put in. newBucket := a.getNewBucket(rmka.na, rmka.srcAddr) // If no room in the original bucket, we put it in a bucket we just // freed up a space in. if len(a.addrNew[newBucket]) >= newBucketSize { newBucket = oldBucket } // replace with ka in list. ka.tried = true entry.Value = ka rmka.tried = false rmka.refs++ // We don't touch a.nTried here since the number of tried stays the same // but we decemented new above, raise it again since we're putting // something back. a.nNew++ rmkey := NetAddressKey(rmka.na) log.Tracef("Replacing %s with %s in tried", rmkey, addrKey) // We made sure there is space here just above. a.addrNew[newBucket][rmkey] = rmka }
[ "func", "(", "a", "*", "AddrManager", ")", "Good", "(", "addr", "*", "wire", ".", "NetAddress", ")", "{", "a", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "ka", ":=", "a", ".", "find", "(", "addr", ")", "\n", "if", "ka", "==", "nil", "{", "return", "\n", "}", "\n\n", "// ka.Timestamp is not updated here to avoid leaking information", "// about currently connected peers.", "now", ":=", "time", ".", "Now", "(", ")", "\n", "ka", ".", "lastsuccess", "=", "now", "\n", "ka", ".", "lastattempt", "=", "now", "\n", "ka", ".", "attempts", "=", "0", "\n\n", "// move to tried set, optionally evicting other addresses if neeed.", "if", "ka", ".", "tried", "{", "return", "\n", "}", "\n\n", "// ok, need to move it to tried.", "// remove from all new buckets.", "// record one of the buckets in question and call it the `first'", "addrKey", ":=", "NetAddressKey", "(", "addr", ")", "\n", "oldBucket", ":=", "-", "1", "\n", "for", "i", ":=", "range", "a", ".", "addrNew", "{", "// we check for existence so we can record the first one", "if", "_", ",", "ok", ":=", "a", ".", "addrNew", "[", "i", "]", "[", "addrKey", "]", ";", "ok", "{", "delete", "(", "a", ".", "addrNew", "[", "i", "]", ",", "addrKey", ")", "\n", "ka", ".", "refs", "--", "\n", "if", "oldBucket", "==", "-", "1", "{", "oldBucket", "=", "i", "\n", "}", "\n", "}", "\n", "}", "\n", "a", ".", "nNew", "--", "\n\n", "if", "oldBucket", "==", "-", "1", "{", "// What? wasn't in a bucket after all.... Panic?", "return", "\n", "}", "\n\n", "bucket", ":=", "a", ".", "getTriedBucket", "(", "ka", ".", "na", ")", "\n\n", "// Room in this tried bucket?", "if", "a", ".", "addrTried", "[", "bucket", "]", ".", "Len", "(", ")", "<", "triedBucketSize", "{", "ka", ".", "tried", "=", "true", "\n", "a", ".", "addrTried", "[", "bucket", "]", ".", "PushBack", "(", "ka", ")", "\n", "a", ".", "nTried", "++", "\n", "return", "\n", "}", "\n\n", "// No room, we have to evict something else.", "entry", ":=", "a", ".", "pickTried", "(", "bucket", ")", "\n", "rmka", ":=", "entry", ".", "Value", ".", "(", "*", "KnownAddress", ")", "\n\n", "// First bucket it would have been put in.", "newBucket", ":=", "a", ".", "getNewBucket", "(", "rmka", ".", "na", ",", "rmka", ".", "srcAddr", ")", "\n\n", "// If no room in the original bucket, we put it in a bucket we just", "// freed up a space in.", "if", "len", "(", "a", ".", "addrNew", "[", "newBucket", "]", ")", ">=", "newBucketSize", "{", "newBucket", "=", "oldBucket", "\n", "}", "\n\n", "// replace with ka in list.", "ka", ".", "tried", "=", "true", "\n", "entry", ".", "Value", "=", "ka", "\n\n", "rmka", ".", "tried", "=", "false", "\n", "rmka", ".", "refs", "++", "\n\n", "// We don't touch a.nTried here since the number of tried stays the same", "// but we decemented new above, raise it again since we're putting", "// something back.", "a", ".", "nNew", "++", "\n\n", "rmkey", ":=", "NetAddressKey", "(", "rmka", ".", "na", ")", "\n", "log", ".", "Tracef", "(", "\"", "\"", ",", "rmkey", ",", "addrKey", ")", "\n\n", "// We made sure there is space here just above.", "a", ".", "addrNew", "[", "newBucket", "]", "[", "rmkey", "]", "=", "rmka", "\n", "}" ]
// Good marks the given address as good. To be called after a successful // connection and version exchange. If the address is unknown to the address // manager it will be ignored.
[ "Good", "marks", "the", "given", "address", "as", "good", ".", "To", "be", "called", "after", "a", "successful", "connection", "and", "version", "exchange", ".", "If", "the", "address", "is", "unknown", "to", "the", "address", "manager", "it", "will", "be", "ignored", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/addrmanager.go#L890-L974
train
btcsuite/btcd
addrmgr/addrmanager.go
SetServices
func (a *AddrManager) SetServices(addr *wire.NetAddress, services wire.ServiceFlag) { a.mtx.Lock() defer a.mtx.Unlock() ka := a.find(addr) if ka == nil { return } // Update the services if needed. if ka.na.Services != services { // ka.na is immutable, so replace it. naCopy := *ka.na naCopy.Services = services ka.na = &naCopy } }
go
func (a *AddrManager) SetServices(addr *wire.NetAddress, services wire.ServiceFlag) { a.mtx.Lock() defer a.mtx.Unlock() ka := a.find(addr) if ka == nil { return } // Update the services if needed. if ka.na.Services != services { // ka.na is immutable, so replace it. naCopy := *ka.na naCopy.Services = services ka.na = &naCopy } }
[ "func", "(", "a", "*", "AddrManager", ")", "SetServices", "(", "addr", "*", "wire", ".", "NetAddress", ",", "services", "wire", ".", "ServiceFlag", ")", "{", "a", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "ka", ":=", "a", ".", "find", "(", "addr", ")", "\n", "if", "ka", "==", "nil", "{", "return", "\n", "}", "\n\n", "// Update the services if needed.", "if", "ka", ".", "na", ".", "Services", "!=", "services", "{", "// ka.na is immutable, so replace it.", "naCopy", ":=", "*", "ka", ".", "na", "\n", "naCopy", ".", "Services", "=", "services", "\n", "ka", ".", "na", "=", "&", "naCopy", "\n", "}", "\n", "}" ]
// SetServices sets the services for the giiven address to the provided value.
[ "SetServices", "sets", "the", "services", "for", "the", "giiven", "address", "to", "the", "provided", "value", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/addrmanager.go#L977-L993
train
btcsuite/btcd
addrmgr/addrmanager.go
AddLocalAddress
func (a *AddrManager) AddLocalAddress(na *wire.NetAddress, priority AddressPriority) error { if !IsRoutable(na) { return fmt.Errorf("address %s is not routable", na.IP) } a.lamtx.Lock() defer a.lamtx.Unlock() key := NetAddressKey(na) la, ok := a.localAddresses[key] if !ok || la.score < priority { if ok { la.score = priority + 1 } else { a.localAddresses[key] = &localAddress{ na: na, score: priority, } } } return nil }
go
func (a *AddrManager) AddLocalAddress(na *wire.NetAddress, priority AddressPriority) error { if !IsRoutable(na) { return fmt.Errorf("address %s is not routable", na.IP) } a.lamtx.Lock() defer a.lamtx.Unlock() key := NetAddressKey(na) la, ok := a.localAddresses[key] if !ok || la.score < priority { if ok { la.score = priority + 1 } else { a.localAddresses[key] = &localAddress{ na: na, score: priority, } } } return nil }
[ "func", "(", "a", "*", "AddrManager", ")", "AddLocalAddress", "(", "na", "*", "wire", ".", "NetAddress", ",", "priority", "AddressPriority", ")", "error", "{", "if", "!", "IsRoutable", "(", "na", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "na", ".", "IP", ")", "\n", "}", "\n\n", "a", ".", "lamtx", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "lamtx", ".", "Unlock", "(", ")", "\n\n", "key", ":=", "NetAddressKey", "(", "na", ")", "\n", "la", ",", "ok", ":=", "a", ".", "localAddresses", "[", "key", "]", "\n", "if", "!", "ok", "||", "la", ".", "score", "<", "priority", "{", "if", "ok", "{", "la", ".", "score", "=", "priority", "+", "1", "\n", "}", "else", "{", "a", ".", "localAddresses", "[", "key", "]", "=", "&", "localAddress", "{", "na", ":", "na", ",", "score", ":", "priority", ",", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// AddLocalAddress adds na to the list of known local addresses to advertise // with the given priority.
[ "AddLocalAddress", "adds", "na", "to", "the", "list", "of", "known", "local", "addresses", "to", "advertise", "with", "the", "given", "priority", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/addrmanager.go#L997-L1018
train
btcsuite/btcd
addrmgr/addrmanager.go
getReachabilityFrom
func getReachabilityFrom(localAddr, remoteAddr *wire.NetAddress) int { const ( Unreachable = 0 Default = iota Teredo Ipv6Weak Ipv4 Ipv6Strong Private ) if !IsRoutable(remoteAddr) { return Unreachable } if IsOnionCatTor(remoteAddr) { if IsOnionCatTor(localAddr) { return Private } if IsRoutable(localAddr) && IsIPv4(localAddr) { return Ipv4 } return Default } if IsRFC4380(remoteAddr) { if !IsRoutable(localAddr) { return Default } if IsRFC4380(localAddr) { return Teredo } if IsIPv4(localAddr) { return Ipv4 } return Ipv6Weak } if IsIPv4(remoteAddr) { if IsRoutable(localAddr) && IsIPv4(localAddr) { return Ipv4 } return Unreachable } /* ipv6 */ var tunnelled bool // Is our v6 is tunnelled? if IsRFC3964(localAddr) || IsRFC6052(localAddr) || IsRFC6145(localAddr) { tunnelled = true } if !IsRoutable(localAddr) { return Default } if IsRFC4380(localAddr) { return Teredo } if IsIPv4(localAddr) { return Ipv4 } if tunnelled { // only prioritise ipv6 if we aren't tunnelling it. return Ipv6Weak } return Ipv6Strong }
go
func getReachabilityFrom(localAddr, remoteAddr *wire.NetAddress) int { const ( Unreachable = 0 Default = iota Teredo Ipv6Weak Ipv4 Ipv6Strong Private ) if !IsRoutable(remoteAddr) { return Unreachable } if IsOnionCatTor(remoteAddr) { if IsOnionCatTor(localAddr) { return Private } if IsRoutable(localAddr) && IsIPv4(localAddr) { return Ipv4 } return Default } if IsRFC4380(remoteAddr) { if !IsRoutable(localAddr) { return Default } if IsRFC4380(localAddr) { return Teredo } if IsIPv4(localAddr) { return Ipv4 } return Ipv6Weak } if IsIPv4(remoteAddr) { if IsRoutable(localAddr) && IsIPv4(localAddr) { return Ipv4 } return Unreachable } /* ipv6 */ var tunnelled bool // Is our v6 is tunnelled? if IsRFC3964(localAddr) || IsRFC6052(localAddr) || IsRFC6145(localAddr) { tunnelled = true } if !IsRoutable(localAddr) { return Default } if IsRFC4380(localAddr) { return Teredo } if IsIPv4(localAddr) { return Ipv4 } if tunnelled { // only prioritise ipv6 if we aren't tunnelling it. return Ipv6Weak } return Ipv6Strong }
[ "func", "getReachabilityFrom", "(", "localAddr", ",", "remoteAddr", "*", "wire", ".", "NetAddress", ")", "int", "{", "const", "(", "Unreachable", "=", "0", "\n", "Default", "=", "iota", "\n", "Teredo", "\n", "Ipv6Weak", "\n", "Ipv4", "\n", "Ipv6Strong", "\n", "Private", "\n", ")", "\n\n", "if", "!", "IsRoutable", "(", "remoteAddr", ")", "{", "return", "Unreachable", "\n", "}", "\n\n", "if", "IsOnionCatTor", "(", "remoteAddr", ")", "{", "if", "IsOnionCatTor", "(", "localAddr", ")", "{", "return", "Private", "\n", "}", "\n\n", "if", "IsRoutable", "(", "localAddr", ")", "&&", "IsIPv4", "(", "localAddr", ")", "{", "return", "Ipv4", "\n", "}", "\n\n", "return", "Default", "\n", "}", "\n\n", "if", "IsRFC4380", "(", "remoteAddr", ")", "{", "if", "!", "IsRoutable", "(", "localAddr", ")", "{", "return", "Default", "\n", "}", "\n\n", "if", "IsRFC4380", "(", "localAddr", ")", "{", "return", "Teredo", "\n", "}", "\n\n", "if", "IsIPv4", "(", "localAddr", ")", "{", "return", "Ipv4", "\n", "}", "\n\n", "return", "Ipv6Weak", "\n", "}", "\n\n", "if", "IsIPv4", "(", "remoteAddr", ")", "{", "if", "IsRoutable", "(", "localAddr", ")", "&&", "IsIPv4", "(", "localAddr", ")", "{", "return", "Ipv4", "\n", "}", "\n", "return", "Unreachable", "\n", "}", "\n\n", "/* ipv6 */", "var", "tunnelled", "bool", "\n", "// Is our v6 is tunnelled?", "if", "IsRFC3964", "(", "localAddr", ")", "||", "IsRFC6052", "(", "localAddr", ")", "||", "IsRFC6145", "(", "localAddr", ")", "{", "tunnelled", "=", "true", "\n", "}", "\n\n", "if", "!", "IsRoutable", "(", "localAddr", ")", "{", "return", "Default", "\n", "}", "\n\n", "if", "IsRFC4380", "(", "localAddr", ")", "{", "return", "Teredo", "\n", "}", "\n\n", "if", "IsIPv4", "(", "localAddr", ")", "{", "return", "Ipv4", "\n", "}", "\n\n", "if", "tunnelled", "{", "// only prioritise ipv6 if we aren't tunnelling it.", "return", "Ipv6Weak", "\n", "}", "\n\n", "return", "Ipv6Strong", "\n", "}" ]
// getReachabilityFrom returns the relative reachability of the provided local // address to the provided remote address.
[ "getReachabilityFrom", "returns", "the", "relative", "reachability", "of", "the", "provided", "local", "address", "to", "the", "provided", "remote", "address", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/addrmanager.go#L1022-L1097
train
btcsuite/btcd
addrmgr/addrmanager.go
GetBestLocalAddress
func (a *AddrManager) GetBestLocalAddress(remoteAddr *wire.NetAddress) *wire.NetAddress { a.lamtx.Lock() defer a.lamtx.Unlock() bestreach := 0 var bestscore AddressPriority var bestAddress *wire.NetAddress for _, la := range a.localAddresses { reach := getReachabilityFrom(la.na, remoteAddr) if reach > bestreach || (reach == bestreach && la.score > bestscore) { bestreach = reach bestscore = la.score bestAddress = la.na } } if bestAddress != nil { log.Debugf("Suggesting address %s:%d for %s:%d", bestAddress.IP, bestAddress.Port, remoteAddr.IP, remoteAddr.Port) } else { log.Debugf("No worthy address for %s:%d", remoteAddr.IP, remoteAddr.Port) // Send something unroutable if nothing suitable. var ip net.IP if !IsIPv4(remoteAddr) && !IsOnionCatTor(remoteAddr) { ip = net.IPv6zero } else { ip = net.IPv4zero } services := wire.SFNodeNetwork | wire.SFNodeWitness | wire.SFNodeBloom bestAddress = wire.NewNetAddressIPPort(ip, 0, services) } return bestAddress }
go
func (a *AddrManager) GetBestLocalAddress(remoteAddr *wire.NetAddress) *wire.NetAddress { a.lamtx.Lock() defer a.lamtx.Unlock() bestreach := 0 var bestscore AddressPriority var bestAddress *wire.NetAddress for _, la := range a.localAddresses { reach := getReachabilityFrom(la.na, remoteAddr) if reach > bestreach || (reach == bestreach && la.score > bestscore) { bestreach = reach bestscore = la.score bestAddress = la.na } } if bestAddress != nil { log.Debugf("Suggesting address %s:%d for %s:%d", bestAddress.IP, bestAddress.Port, remoteAddr.IP, remoteAddr.Port) } else { log.Debugf("No worthy address for %s:%d", remoteAddr.IP, remoteAddr.Port) // Send something unroutable if nothing suitable. var ip net.IP if !IsIPv4(remoteAddr) && !IsOnionCatTor(remoteAddr) { ip = net.IPv6zero } else { ip = net.IPv4zero } services := wire.SFNodeNetwork | wire.SFNodeWitness | wire.SFNodeBloom bestAddress = wire.NewNetAddressIPPort(ip, 0, services) } return bestAddress }
[ "func", "(", "a", "*", "AddrManager", ")", "GetBestLocalAddress", "(", "remoteAddr", "*", "wire", ".", "NetAddress", ")", "*", "wire", ".", "NetAddress", "{", "a", ".", "lamtx", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "lamtx", ".", "Unlock", "(", ")", "\n\n", "bestreach", ":=", "0", "\n", "var", "bestscore", "AddressPriority", "\n", "var", "bestAddress", "*", "wire", ".", "NetAddress", "\n", "for", "_", ",", "la", ":=", "range", "a", ".", "localAddresses", "{", "reach", ":=", "getReachabilityFrom", "(", "la", ".", "na", ",", "remoteAddr", ")", "\n", "if", "reach", ">", "bestreach", "||", "(", "reach", "==", "bestreach", "&&", "la", ".", "score", ">", "bestscore", ")", "{", "bestreach", "=", "reach", "\n", "bestscore", "=", "la", ".", "score", "\n", "bestAddress", "=", "la", ".", "na", "\n", "}", "\n", "}", "\n", "if", "bestAddress", "!=", "nil", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "bestAddress", ".", "IP", ",", "bestAddress", ".", "Port", ",", "remoteAddr", ".", "IP", ",", "remoteAddr", ".", "Port", ")", "\n", "}", "else", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "remoteAddr", ".", "IP", ",", "remoteAddr", ".", "Port", ")", "\n\n", "// Send something unroutable if nothing suitable.", "var", "ip", "net", ".", "IP", "\n", "if", "!", "IsIPv4", "(", "remoteAddr", ")", "&&", "!", "IsOnionCatTor", "(", "remoteAddr", ")", "{", "ip", "=", "net", ".", "IPv6zero", "\n", "}", "else", "{", "ip", "=", "net", ".", "IPv4zero", "\n", "}", "\n", "services", ":=", "wire", ".", "SFNodeNetwork", "|", "wire", ".", "SFNodeWitness", "|", "wire", ".", "SFNodeBloom", "\n", "bestAddress", "=", "wire", ".", "NewNetAddressIPPort", "(", "ip", ",", "0", ",", "services", ")", "\n", "}", "\n\n", "return", "bestAddress", "\n", "}" ]
// GetBestLocalAddress returns the most appropriate local address to use // for the given remote address.
[ "GetBestLocalAddress", "returns", "the", "most", "appropriate", "local", "address", "to", "use", "for", "the", "given", "remote", "address", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/addrmanager.go#L1101-L1136
train
btcsuite/btcd
addrmgr/addrmanager.go
New
func New(dataDir string, lookupFunc func(string) ([]net.IP, error)) *AddrManager { am := AddrManager{ peersFile: filepath.Join(dataDir, "peers.json"), lookupFunc: lookupFunc, rand: rand.New(rand.NewSource(time.Now().UnixNano())), quit: make(chan struct{}), localAddresses: make(map[string]*localAddress), version: serialisationVersion, } am.reset() return &am }
go
func New(dataDir string, lookupFunc func(string) ([]net.IP, error)) *AddrManager { am := AddrManager{ peersFile: filepath.Join(dataDir, "peers.json"), lookupFunc: lookupFunc, rand: rand.New(rand.NewSource(time.Now().UnixNano())), quit: make(chan struct{}), localAddresses: make(map[string]*localAddress), version: serialisationVersion, } am.reset() return &am }
[ "func", "New", "(", "dataDir", "string", ",", "lookupFunc", "func", "(", "string", ")", "(", "[", "]", "net", ".", "IP", ",", "error", ")", ")", "*", "AddrManager", "{", "am", ":=", "AddrManager", "{", "peersFile", ":", "filepath", ".", "Join", "(", "dataDir", ",", "\"", "\"", ")", ",", "lookupFunc", ":", "lookupFunc", ",", "rand", ":", "rand", ".", "New", "(", "rand", ".", "NewSource", "(", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", ")", ",", "quit", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "localAddresses", ":", "make", "(", "map", "[", "string", "]", "*", "localAddress", ")", ",", "version", ":", "serialisationVersion", ",", "}", "\n", "am", ".", "reset", "(", ")", "\n", "return", "&", "am", "\n", "}" ]
// New returns a new bitcoin address manager. // Use Start to begin processing asynchronous address updates.
[ "New", "returns", "a", "new", "bitcoin", "address", "manager", ".", "Use", "Start", "to", "begin", "processing", "asynchronous", "address", "updates", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/addrmanager.go#L1140-L1151
train
btcsuite/btcd
wire/msgcfcheckpt.go
AddCFHeader
func (msg *MsgCFCheckpt) AddCFHeader(header *chainhash.Hash) error { if len(msg.FilterHeaders) == cap(msg.FilterHeaders) { str := fmt.Sprintf("FilterHeaders has insufficient capacity for "+ "additional header: len = %d", len(msg.FilterHeaders)) return messageError("MsgCFCheckpt.AddCFHeader", str) } msg.FilterHeaders = append(msg.FilterHeaders, header) return nil }
go
func (msg *MsgCFCheckpt) AddCFHeader(header *chainhash.Hash) error { if len(msg.FilterHeaders) == cap(msg.FilterHeaders) { str := fmt.Sprintf("FilterHeaders has insufficient capacity for "+ "additional header: len = %d", len(msg.FilterHeaders)) return messageError("MsgCFCheckpt.AddCFHeader", str) } msg.FilterHeaders = append(msg.FilterHeaders, header) return nil }
[ "func", "(", "msg", "*", "MsgCFCheckpt", ")", "AddCFHeader", "(", "header", "*", "chainhash", ".", "Hash", ")", "error", "{", "if", "len", "(", "msg", ".", "FilterHeaders", ")", "==", "cap", "(", "msg", ".", "FilterHeaders", ")", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "len", "(", "msg", ".", "FilterHeaders", ")", ")", "\n", "return", "messageError", "(", "\"", "\"", ",", "str", ")", "\n", "}", "\n\n", "msg", ".", "FilterHeaders", "=", "append", "(", "msg", ".", "FilterHeaders", ",", "header", ")", "\n", "return", "nil", "\n", "}" ]
// AddCFHeader adds a new committed filter header to the message.
[ "AddCFHeader", "adds", "a", "new", "committed", "filter", "header", "to", "the", "message", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgcfcheckpt.go#L41-L50
train
btcsuite/btcd
wire/msgcfcheckpt.go
NewMsgCFCheckpt
func NewMsgCFCheckpt(filterType FilterType, stopHash *chainhash.Hash, headersCount int) *MsgCFCheckpt { return &MsgCFCheckpt{ FilterType: filterType, StopHash: *stopHash, FilterHeaders: make([]*chainhash.Hash, 0, headersCount), } }
go
func NewMsgCFCheckpt(filterType FilterType, stopHash *chainhash.Hash, headersCount int) *MsgCFCheckpt { return &MsgCFCheckpt{ FilterType: filterType, StopHash: *stopHash, FilterHeaders: make([]*chainhash.Hash, 0, headersCount), } }
[ "func", "NewMsgCFCheckpt", "(", "filterType", "FilterType", ",", "stopHash", "*", "chainhash", ".", "Hash", ",", "headersCount", "int", ")", "*", "MsgCFCheckpt", "{", "return", "&", "MsgCFCheckpt", "{", "FilterType", ":", "filterType", ",", "StopHash", ":", "*", "stopHash", ",", "FilterHeaders", ":", "make", "(", "[", "]", "*", "chainhash", ".", "Hash", ",", "0", ",", "headersCount", ")", ",", "}", "\n", "}" ]
// NewMsgCFCheckpt returns a new bitcoin cfheaders message that conforms to // the Message interface. See MsgCFCheckpt for details.
[ "NewMsgCFCheckpt", "returns", "a", "new", "bitcoin", "cfheaders", "message", "that", "conforms", "to", "the", "Message", "interface", ".", "See", "MsgCFCheckpt", "for", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgcfcheckpt.go#L157-L164
train
btcsuite/btcd
blockchain/error.go
ruleError
func ruleError(c ErrorCode, desc string) RuleError { return RuleError{ErrorCode: c, Description: desc} }
go
func ruleError(c ErrorCode, desc string) RuleError { return RuleError{ErrorCode: c, Description: desc} }
[ "func", "ruleError", "(", "c", "ErrorCode", ",", "desc", "string", ")", "RuleError", "{", "return", "RuleError", "{", "ErrorCode", ":", "c", ",", "Description", ":", "desc", "}", "\n", "}" ]
// ruleError creates an RuleError given a set of arguments.
[ "ruleError", "creates", "an", "RuleError", "given", "a", "set", "of", "arguments", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/error.go#L296-L298
train
btcsuite/btcd
wire/error.go
messageError
func messageError(f string, desc string) *MessageError { return &MessageError{Func: f, Description: desc} }
go
func messageError(f string, desc string) *MessageError { return &MessageError{Func: f, Description: desc} }
[ "func", "messageError", "(", "f", "string", ",", "desc", "string", ")", "*", "MessageError", "{", "return", "&", "MessageError", "{", "Func", ":", "f", ",", "Description", ":", "desc", "}", "\n", "}" ]
// messageError creates an error for the given function and description.
[ "messageError", "creates", "an", "error", "for", "the", "given", "function", "and", "description", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/error.go#L32-L34
train
btcsuite/btcd
blockchain/chainview.go
newChainView
func newChainView(tip *blockNode) *chainView { // The mutex is intentionally not held since this is a constructor. var c chainView c.setTip(tip) return &c }
go
func newChainView(tip *blockNode) *chainView { // The mutex is intentionally not held since this is a constructor. var c chainView c.setTip(tip) return &c }
[ "func", "newChainView", "(", "tip", "*", "blockNode", ")", "*", "chainView", "{", "// The mutex is intentionally not held since this is a constructor.", "var", "c", "chainView", "\n", "c", ".", "setTip", "(", "tip", ")", "\n", "return", "&", "c", "\n", "}" ]
// newChainView returns a new chain view for the given tip block node. Passing // nil as the tip will result in a chain view that is not initialized. The tip // can be updated at any time via the setTip function.
[ "newChainView", "returns", "a", "new", "chain", "view", "for", "the", "given", "tip", "block", "node", ".", "Passing", "nil", "as", "the", "tip", "will", "result", "in", "a", "chain", "view", "that", "is", "not", "initialized", ".", "The", "tip", "can", "be", "updated", "at", "any", "time", "via", "the", "setTip", "function", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/chainview.go#L52-L57
train
btcsuite/btcd
blockchain/chainview.go
Genesis
func (c *chainView) Genesis() *blockNode { c.mtx.Lock() genesis := c.genesis() c.mtx.Unlock() return genesis }
go
func (c *chainView) Genesis() *blockNode { c.mtx.Lock() genesis := c.genesis() c.mtx.Unlock() return genesis }
[ "func", "(", "c", "*", "chainView", ")", "Genesis", "(", ")", "*", "blockNode", "{", "c", ".", "mtx", ".", "Lock", "(", ")", "\n", "genesis", ":=", "c", ".", "genesis", "(", ")", "\n", "c", ".", "mtx", ".", "Unlock", "(", ")", "\n", "return", "genesis", "\n", "}" ]
// Genesis returns the genesis block for the chain view. // // This function is safe for concurrent access.
[ "Genesis", "returns", "the", "genesis", "block", "for", "the", "chain", "view", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/chainview.go#L75-L80
train
btcsuite/btcd
blockchain/chainview.go
Tip
func (c *chainView) Tip() *blockNode { c.mtx.Lock() tip := c.tip() c.mtx.Unlock() return tip }
go
func (c *chainView) Tip() *blockNode { c.mtx.Lock() tip := c.tip() c.mtx.Unlock() return tip }
[ "func", "(", "c", "*", "chainView", ")", "Tip", "(", ")", "*", "blockNode", "{", "c", ".", "mtx", ".", "Lock", "(", ")", "\n", "tip", ":=", "c", ".", "tip", "(", ")", "\n", "c", ".", "mtx", ".", "Unlock", "(", ")", "\n", "return", "tip", "\n", "}" ]
// Tip returns the current tip block node for the chain view. It will return // nil if there is no tip. // // This function is safe for concurrent access.
[ "Tip", "returns", "the", "current", "tip", "block", "node", "for", "the", "chain", "view", ".", "It", "will", "return", "nil", "if", "there", "is", "no", "tip", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/chainview.go#L99-L104
train
btcsuite/btcd
blockchain/chainview.go
SetTip
func (c *chainView) SetTip(node *blockNode) { c.mtx.Lock() c.setTip(node) c.mtx.Unlock() }
go
func (c *chainView) SetTip(node *blockNode) { c.mtx.Lock() c.setTip(node) c.mtx.Unlock() }
[ "func", "(", "c", "*", "chainView", ")", "SetTip", "(", "node", "*", "blockNode", ")", "{", "c", ".", "mtx", ".", "Lock", "(", ")", "\n", "c", ".", "setTip", "(", "node", ")", "\n", "c", ".", "mtx", ".", "Unlock", "(", ")", "\n", "}" ]
// SetTip sets the chain view to use the provided block node as the current tip // and ensures the view is consistent by populating it with the nodes obtained // by walking backwards all the way to genesis block as necessary. Further // calls will only perform the minimum work needed, so switching between chain // tips is efficient. // // This function is safe for concurrent access.
[ "SetTip", "sets", "the", "chain", "view", "to", "use", "the", "provided", "block", "node", "as", "the", "current", "tip", "and", "ensures", "the", "view", "is", "consistent", "by", "populating", "it", "with", "the", "nodes", "obtained", "by", "walking", "backwards", "all", "the", "way", "to", "genesis", "block", "as", "necessary", ".", "Further", "calls", "will", "only", "perform", "the", "minimum", "work", "needed", "so", "switching", "between", "chain", "tips", "is", "efficient", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/chainview.go#L155-L159
train
btcsuite/btcd
blockchain/chainview.go
NodeByHeight
func (c *chainView) NodeByHeight(height int32) *blockNode { c.mtx.Lock() node := c.nodeByHeight(height) c.mtx.Unlock() return node }
go
func (c *chainView) NodeByHeight(height int32) *blockNode { c.mtx.Lock() node := c.nodeByHeight(height) c.mtx.Unlock() return node }
[ "func", "(", "c", "*", "chainView", ")", "NodeByHeight", "(", "height", "int32", ")", "*", "blockNode", "{", "c", ".", "mtx", ".", "Lock", "(", ")", "\n", "node", ":=", "c", ".", "nodeByHeight", "(", "height", ")", "\n", "c", ".", "mtx", ".", "Unlock", "(", ")", "\n", "return", "node", "\n", "}" ]
// NodeByHeight returns the block node at the specified height. Nil will be // returned if the height does not exist. // // This function is safe for concurrent access.
[ "NodeByHeight", "returns", "the", "block", "node", "at", "the", "specified", "height", ".", "Nil", "will", "be", "returned", "if", "the", "height", "does", "not", "exist", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/chainview.go#L200-L205
train
btcsuite/btcd
blockchain/chainview.go
Contains
func (c *chainView) Contains(node *blockNode) bool { c.mtx.Lock() contains := c.contains(node) c.mtx.Unlock() return contains }
go
func (c *chainView) Contains(node *blockNode) bool { c.mtx.Lock() contains := c.contains(node) c.mtx.Unlock() return contains }
[ "func", "(", "c", "*", "chainView", ")", "Contains", "(", "node", "*", "blockNode", ")", "bool", "{", "c", ".", "mtx", ".", "Lock", "(", ")", "\n", "contains", ":=", "c", ".", "contains", "(", "node", ")", "\n", "c", ".", "mtx", ".", "Unlock", "(", ")", "\n", "return", "contains", "\n", "}" ]
// Contains returns whether or not the chain view contains the passed block // node. // // This function is safe for concurrent access.
[ "Contains", "returns", "whether", "or", "not", "the", "chain", "view", "contains", "the", "passed", "block", "node", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/chainview.go#L233-L238
train
btcsuite/btcd
blockchain/chainview.go
BlockLocator
func (c *chainView) BlockLocator(node *blockNode) BlockLocator { c.mtx.Lock() locator := c.blockLocator(node) c.mtx.Unlock() return locator }
go
func (c *chainView) BlockLocator(node *blockNode) BlockLocator { c.mtx.Lock() locator := c.blockLocator(node) c.mtx.Unlock() return locator }
[ "func", "(", "c", "*", "chainView", ")", "BlockLocator", "(", "node", "*", "blockNode", ")", "BlockLocator", "{", "c", ".", "mtx", ".", "Lock", "(", ")", "\n", "locator", ":=", "c", ".", "blockLocator", "(", "node", ")", "\n", "c", ".", "mtx", ".", "Unlock", "(", ")", "\n", "return", "locator", "\n", "}" ]
// BlockLocator returns a block locator for the passed block node. The passed // node can be nil in which case the block locator for the current tip // associated with the view will be returned. // // See the BlockLocator type for details on the algorithm used to create a block // locator. // // This function is safe for concurrent access.
[ "BlockLocator", "returns", "a", "block", "locator", "for", "the", "passed", "block", "node", ".", "The", "passed", "node", "can", "be", "nil", "in", "which", "case", "the", "block", "locator", "for", "the", "current", "tip", "associated", "with", "the", "view", "will", "be", "returned", ".", "See", "the", "BlockLocator", "type", "for", "details", "on", "the", "algorithm", "used", "to", "create", "a", "block", "locator", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/chainview.go#L418-L423
train
btcsuite/btcd
txscript/script.go
isSmallInt
func isSmallInt(op *opcode) bool { if op.value == OP_0 || (op.value >= OP_1 && op.value <= OP_16) { return true } return false }
go
func isSmallInt(op *opcode) bool { if op.value == OP_0 || (op.value >= OP_1 && op.value <= OP_16) { return true } return false }
[ "func", "isSmallInt", "(", "op", "*", "opcode", ")", "bool", "{", "if", "op", ".", "value", "==", "OP_0", "||", "(", "op", ".", "value", ">=", "OP_1", "&&", "op", ".", "value", "<=", "OP_16", ")", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isSmallInt returns whether or not the opcode is considered a small integer, // which is an OP_0, or OP_1 through OP_16.
[ "isSmallInt", "returns", "whether", "or", "not", "the", "opcode", "is", "considered", "a", "small", "integer", "which", "is", "an", "OP_0", "or", "OP_1", "through", "OP_16", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/script.go#L47-L52
train
btcsuite/btcd
txscript/script.go
isScriptHash
func isScriptHash(pops []parsedOpcode) bool { return len(pops) == 3 && pops[0].opcode.value == OP_HASH160 && pops[1].opcode.value == OP_DATA_20 && pops[2].opcode.value == OP_EQUAL }
go
func isScriptHash(pops []parsedOpcode) bool { return len(pops) == 3 && pops[0].opcode.value == OP_HASH160 && pops[1].opcode.value == OP_DATA_20 && pops[2].opcode.value == OP_EQUAL }
[ "func", "isScriptHash", "(", "pops", "[", "]", "parsedOpcode", ")", "bool", "{", "return", "len", "(", "pops", ")", "==", "3", "&&", "pops", "[", "0", "]", ".", "opcode", ".", "value", "==", "OP_HASH160", "&&", "pops", "[", "1", "]", ".", "opcode", ".", "value", "==", "OP_DATA_20", "&&", "pops", "[", "2", "]", ".", "opcode", ".", "value", "==", "OP_EQUAL", "\n", "}" ]
// isScriptHash returns true if the script passed is a pay-to-script-hash // transaction, false otherwise.
[ "isScriptHash", "returns", "true", "if", "the", "script", "passed", "is", "a", "pay", "-", "to", "-", "script", "-", "hash", "transaction", "false", "otherwise", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/script.go#L56-L61
train
btcsuite/btcd
txscript/script.go
isWitnessScriptHash
func isWitnessScriptHash(pops []parsedOpcode) bool { return len(pops) == 2 && pops[0].opcode.value == OP_0 && pops[1].opcode.value == OP_DATA_32 }
go
func isWitnessScriptHash(pops []parsedOpcode) bool { return len(pops) == 2 && pops[0].opcode.value == OP_0 && pops[1].opcode.value == OP_DATA_32 }
[ "func", "isWitnessScriptHash", "(", "pops", "[", "]", "parsedOpcode", ")", "bool", "{", "return", "len", "(", "pops", ")", "==", "2", "&&", "pops", "[", "0", "]", ".", "opcode", ".", "value", "==", "OP_0", "&&", "pops", "[", "1", "]", ".", "opcode", ".", "value", "==", "OP_DATA_32", "\n", "}" ]
// isWitnessScriptHash returns true if the passed script is a // pay-to-witness-script-hash transaction, false otherwise.
[ "isWitnessScriptHash", "returns", "true", "if", "the", "passed", "script", "is", "a", "pay", "-", "to", "-", "witness", "-", "script", "-", "hash", "transaction", "false", "otherwise", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/script.go#L75-L79
train
btcsuite/btcd
txscript/script.go
isWitnessPubKeyHash
func isWitnessPubKeyHash(pops []parsedOpcode) bool { return len(pops) == 2 && pops[0].opcode.value == OP_0 && pops[1].opcode.value == OP_DATA_20 }
go
func isWitnessPubKeyHash(pops []parsedOpcode) bool { return len(pops) == 2 && pops[0].opcode.value == OP_0 && pops[1].opcode.value == OP_DATA_20 }
[ "func", "isWitnessPubKeyHash", "(", "pops", "[", "]", "parsedOpcode", ")", "bool", "{", "return", "len", "(", "pops", ")", "==", "2", "&&", "pops", "[", "0", "]", ".", "opcode", ".", "value", "==", "OP_0", "&&", "pops", "[", "1", "]", ".", "opcode", ".", "value", "==", "OP_DATA_20", "\n", "}" ]
// isWitnessPubKeyHash returns true if the passed script is a // pay-to-witness-pubkey-hash, and false otherwise.
[ "isWitnessPubKeyHash", "returns", "true", "if", "the", "passed", "script", "is", "a", "pay", "-", "to", "-", "witness", "-", "pubkey", "-", "hash", "and", "false", "otherwise", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/script.go#L103-L107
train
btcsuite/btcd
txscript/script.go
ExtractWitnessProgramInfo
func ExtractWitnessProgramInfo(script []byte) (int, []byte, error) { pops, err := parseScript(script) if err != nil { return 0, nil, err } // If at this point, the scripts doesn't resemble a witness program, // then we'll exit early as there isn't a valid version or program to // extract. if !isWitnessProgram(pops) { return 0, nil, fmt.Errorf("script is not a witness program, " + "unable to extract version or witness program") } witnessVersion := asSmallInt(pops[0].opcode) witnessProgram := pops[1].data return witnessVersion, witnessProgram, nil }
go
func ExtractWitnessProgramInfo(script []byte) (int, []byte, error) { pops, err := parseScript(script) if err != nil { return 0, nil, err } // If at this point, the scripts doesn't resemble a witness program, // then we'll exit early as there isn't a valid version or program to // extract. if !isWitnessProgram(pops) { return 0, nil, fmt.Errorf("script is not a witness program, " + "unable to extract version or witness program") } witnessVersion := asSmallInt(pops[0].opcode) witnessProgram := pops[1].data return witnessVersion, witnessProgram, nil }
[ "func", "ExtractWitnessProgramInfo", "(", "script", "[", "]", "byte", ")", "(", "int", ",", "[", "]", "byte", ",", "error", ")", "{", "pops", ",", "err", ":=", "parseScript", "(", "script", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "nil", ",", "err", "\n", "}", "\n\n", "// If at this point, the scripts doesn't resemble a witness program,", "// then we'll exit early as there isn't a valid version or program to", "// extract.", "if", "!", "isWitnessProgram", "(", "pops", ")", "{", "return", "0", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ")", "\n", "}", "\n\n", "witnessVersion", ":=", "asSmallInt", "(", "pops", "[", "0", "]", ".", "opcode", ")", "\n", "witnessProgram", ":=", "pops", "[", "1", "]", ".", "data", "\n\n", "return", "witnessVersion", ",", "witnessProgram", ",", "nil", "\n", "}" ]
// ExtractWitnessProgramInfo attempts to extract the witness program version, // as well as the witness program itself from the passed script.
[ "ExtractWitnessProgramInfo", "attempts", "to", "extract", "the", "witness", "program", "version", "as", "well", "as", "the", "witness", "program", "itself", "from", "the", "passed", "script", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/script.go#L145-L163
train
btcsuite/btcd
txscript/script.go
isPushOnly
func isPushOnly(pops []parsedOpcode) bool { // NOTE: This function does NOT verify opcodes directly since it is // internal and is only called with parsed opcodes for scripts that did // not have any parse errors. Thus, consensus is properly maintained. for _, pop := range pops { // All opcodes up to OP_16 are data push instructions. // NOTE: This does consider OP_RESERVED to be a data push // instruction, but execution of OP_RESERVED will fail anyways // and matches the behavior required by consensus. if pop.opcode.value > OP_16 { return false } } return true }
go
func isPushOnly(pops []parsedOpcode) bool { // NOTE: This function does NOT verify opcodes directly since it is // internal and is only called with parsed opcodes for scripts that did // not have any parse errors. Thus, consensus is properly maintained. for _, pop := range pops { // All opcodes up to OP_16 are data push instructions. // NOTE: This does consider OP_RESERVED to be a data push // instruction, but execution of OP_RESERVED will fail anyways // and matches the behavior required by consensus. if pop.opcode.value > OP_16 { return false } } return true }
[ "func", "isPushOnly", "(", "pops", "[", "]", "parsedOpcode", ")", "bool", "{", "// NOTE: This function does NOT verify opcodes directly since it is", "// internal and is only called with parsed opcodes for scripts that did", "// not have any parse errors. Thus, consensus is properly maintained.", "for", "_", ",", "pop", ":=", "range", "pops", "{", "// All opcodes up to OP_16 are data push instructions.", "// NOTE: This does consider OP_RESERVED to be a data push", "// instruction, but execution of OP_RESERVED will fail anyways", "// and matches the behavior required by consensus.", "if", "pop", ".", "opcode", ".", "value", ">", "OP_16", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// isPushOnly returns true if the script only pushes data, false otherwise.
[ "isPushOnly", "returns", "true", "if", "the", "script", "only", "pushes", "data", "false", "otherwise", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/script.go#L166-L181
train
btcsuite/btcd
txscript/script.go
IsPushOnlyScript
func IsPushOnlyScript(script []byte) bool { pops, err := parseScript(script) if err != nil { return false } return isPushOnly(pops) }
go
func IsPushOnlyScript(script []byte) bool { pops, err := parseScript(script) if err != nil { return false } return isPushOnly(pops) }
[ "func", "IsPushOnlyScript", "(", "script", "[", "]", "byte", ")", "bool", "{", "pops", ",", "err", ":=", "parseScript", "(", "script", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "return", "isPushOnly", "(", "pops", ")", "\n", "}" ]
// IsPushOnlyScript returns whether or not the passed script only pushes data. // // False will be returned when the script does not parse.
[ "IsPushOnlyScript", "returns", "whether", "or", "not", "the", "passed", "script", "only", "pushes", "data", ".", "False", "will", "be", "returned", "when", "the", "script", "does", "not", "parse", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/script.go#L186-L192
train
btcsuite/btcd
txscript/script.go
parseScriptTemplate
func parseScriptTemplate(script []byte, opcodes *[256]opcode) ([]parsedOpcode, error) { retScript := make([]parsedOpcode, 0, len(script)) for i := 0; i < len(script); { instr := script[i] op := &opcodes[instr] pop := parsedOpcode{opcode: op} // Parse data out of instruction. switch { // No additional data. Note that some of the opcodes, notably // OP_1NEGATE, OP_0, and OP_[1-16] represent the data // themselves. case op.length == 1: i++ // Data pushes of specific lengths -- OP_DATA_[1-75]. case op.length > 1: if len(script[i:]) < op.length { str := fmt.Sprintf("opcode %s requires %d "+ "bytes, but script only has %d remaining", op.name, op.length, len(script[i:])) return retScript, scriptError(ErrMalformedPush, str) } // Slice out the data. pop.data = script[i+1 : i+op.length] i += op.length // Data pushes with parsed lengths -- OP_PUSHDATAP{1,2,4}. case op.length < 0: var l uint off := i + 1 if len(script[off:]) < -op.length { str := fmt.Sprintf("opcode %s requires %d "+ "bytes, but script only has %d remaining", op.name, -op.length, len(script[off:])) return retScript, scriptError(ErrMalformedPush, str) } // Next -length bytes are little endian length of data. switch op.length { case -1: l = uint(script[off]) case -2: l = ((uint(script[off+1]) << 8) | uint(script[off])) case -4: l = ((uint(script[off+3]) << 24) | (uint(script[off+2]) << 16) | (uint(script[off+1]) << 8) | uint(script[off])) default: str := fmt.Sprintf("invalid opcode length %d", op.length) return retScript, scriptError(ErrMalformedPush, str) } // Move offset to beginning of the data. off += -op.length // Disallow entries that do not fit script or were // sign extended. if int(l) > len(script[off:]) || int(l) < 0 { str := fmt.Sprintf("opcode %s pushes %d bytes, "+ "but script only has %d remaining", op.name, int(l), len(script[off:])) return retScript, scriptError(ErrMalformedPush, str) } pop.data = script[off : off+int(l)] i += 1 - op.length + int(l) } retScript = append(retScript, pop) } return retScript, nil }
go
func parseScriptTemplate(script []byte, opcodes *[256]opcode) ([]parsedOpcode, error) { retScript := make([]parsedOpcode, 0, len(script)) for i := 0; i < len(script); { instr := script[i] op := &opcodes[instr] pop := parsedOpcode{opcode: op} // Parse data out of instruction. switch { // No additional data. Note that some of the opcodes, notably // OP_1NEGATE, OP_0, and OP_[1-16] represent the data // themselves. case op.length == 1: i++ // Data pushes of specific lengths -- OP_DATA_[1-75]. case op.length > 1: if len(script[i:]) < op.length { str := fmt.Sprintf("opcode %s requires %d "+ "bytes, but script only has %d remaining", op.name, op.length, len(script[i:])) return retScript, scriptError(ErrMalformedPush, str) } // Slice out the data. pop.data = script[i+1 : i+op.length] i += op.length // Data pushes with parsed lengths -- OP_PUSHDATAP{1,2,4}. case op.length < 0: var l uint off := i + 1 if len(script[off:]) < -op.length { str := fmt.Sprintf("opcode %s requires %d "+ "bytes, but script only has %d remaining", op.name, -op.length, len(script[off:])) return retScript, scriptError(ErrMalformedPush, str) } // Next -length bytes are little endian length of data. switch op.length { case -1: l = uint(script[off]) case -2: l = ((uint(script[off+1]) << 8) | uint(script[off])) case -4: l = ((uint(script[off+3]) << 24) | (uint(script[off+2]) << 16) | (uint(script[off+1]) << 8) | uint(script[off])) default: str := fmt.Sprintf("invalid opcode length %d", op.length) return retScript, scriptError(ErrMalformedPush, str) } // Move offset to beginning of the data. off += -op.length // Disallow entries that do not fit script or were // sign extended. if int(l) > len(script[off:]) || int(l) < 0 { str := fmt.Sprintf("opcode %s pushes %d bytes, "+ "but script only has %d remaining", op.name, int(l), len(script[off:])) return retScript, scriptError(ErrMalformedPush, str) } pop.data = script[off : off+int(l)] i += 1 - op.length + int(l) } retScript = append(retScript, pop) } return retScript, nil }
[ "func", "parseScriptTemplate", "(", "script", "[", "]", "byte", ",", "opcodes", "*", "[", "256", "]", "opcode", ")", "(", "[", "]", "parsedOpcode", ",", "error", ")", "{", "retScript", ":=", "make", "(", "[", "]", "parsedOpcode", ",", "0", ",", "len", "(", "script", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "script", ")", ";", "{", "instr", ":=", "script", "[", "i", "]", "\n", "op", ":=", "&", "opcodes", "[", "instr", "]", "\n", "pop", ":=", "parsedOpcode", "{", "opcode", ":", "op", "}", "\n\n", "// Parse data out of instruction.", "switch", "{", "// No additional data. Note that some of the opcodes, notably", "// OP_1NEGATE, OP_0, and OP_[1-16] represent the data", "// themselves.", "case", "op", ".", "length", "==", "1", ":", "i", "++", "\n\n", "// Data pushes of specific lengths -- OP_DATA_[1-75].", "case", "op", ".", "length", ">", "1", ":", "if", "len", "(", "script", "[", "i", ":", "]", ")", "<", "op", ".", "length", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "op", ".", "name", ",", "op", ".", "length", ",", "len", "(", "script", "[", "i", ":", "]", ")", ")", "\n", "return", "retScript", ",", "scriptError", "(", "ErrMalformedPush", ",", "str", ")", "\n", "}", "\n\n", "// Slice out the data.", "pop", ".", "data", "=", "script", "[", "i", "+", "1", ":", "i", "+", "op", ".", "length", "]", "\n", "i", "+=", "op", ".", "length", "\n\n", "// Data pushes with parsed lengths -- OP_PUSHDATAP{1,2,4}.", "case", "op", ".", "length", "<", "0", ":", "var", "l", "uint", "\n", "off", ":=", "i", "+", "1", "\n\n", "if", "len", "(", "script", "[", "off", ":", "]", ")", "<", "-", "op", ".", "length", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "op", ".", "name", ",", "-", "op", ".", "length", ",", "len", "(", "script", "[", "off", ":", "]", ")", ")", "\n", "return", "retScript", ",", "scriptError", "(", "ErrMalformedPush", ",", "str", ")", "\n", "}", "\n\n", "// Next -length bytes are little endian length of data.", "switch", "op", ".", "length", "{", "case", "-", "1", ":", "l", "=", "uint", "(", "script", "[", "off", "]", ")", "\n", "case", "-", "2", ":", "l", "=", "(", "(", "uint", "(", "script", "[", "off", "+", "1", "]", ")", "<<", "8", ")", "|", "uint", "(", "script", "[", "off", "]", ")", ")", "\n", "case", "-", "4", ":", "l", "=", "(", "(", "uint", "(", "script", "[", "off", "+", "3", "]", ")", "<<", "24", ")", "|", "(", "uint", "(", "script", "[", "off", "+", "2", "]", ")", "<<", "16", ")", "|", "(", "uint", "(", "script", "[", "off", "+", "1", "]", ")", "<<", "8", ")", "|", "uint", "(", "script", "[", "off", "]", ")", ")", "\n", "default", ":", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "op", ".", "length", ")", "\n", "return", "retScript", ",", "scriptError", "(", "ErrMalformedPush", ",", "str", ")", "\n", "}", "\n\n", "// Move offset to beginning of the data.", "off", "+=", "-", "op", ".", "length", "\n\n", "// Disallow entries that do not fit script or were", "// sign extended.", "if", "int", "(", "l", ")", ">", "len", "(", "script", "[", "off", ":", "]", ")", "||", "int", "(", "l", ")", "<", "0", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "op", ".", "name", ",", "int", "(", "l", ")", ",", "len", "(", "script", "[", "off", ":", "]", ")", ")", "\n", "return", "retScript", ",", "scriptError", "(", "ErrMalformedPush", ",", "str", ")", "\n", "}", "\n\n", "pop", ".", "data", "=", "script", "[", "off", ":", "off", "+", "int", "(", "l", ")", "]", "\n", "i", "+=", "1", "-", "op", ".", "length", "+", "int", "(", "l", ")", "\n", "}", "\n\n", "retScript", "=", "append", "(", "retScript", ",", "pop", ")", "\n", "}", "\n\n", "return", "retScript", ",", "nil", "\n", "}" ]
// parseScriptTemplate is the same as parseScript but allows the passing of the // template list for testing purposes. When there are parse errors, it returns // the list of parsed opcodes up to the point of failure along with the error.
[ "parseScriptTemplate", "is", "the", "same", "as", "parseScript", "but", "allows", "the", "passing", "of", "the", "template", "list", "for", "testing", "purposes", ".", "When", "there", "are", "parse", "errors", "it", "returns", "the", "list", "of", "parsed", "opcodes", "up", "to", "the", "point", "of", "failure", "along", "with", "the", "error", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/script.go#L197-L279
train
btcsuite/btcd
txscript/script.go
unparseScript
func unparseScript(pops []parsedOpcode) ([]byte, error) { script := make([]byte, 0, len(pops)) for _, pop := range pops { b, err := pop.bytes() if err != nil { return nil, err } script = append(script, b...) } return script, nil }
go
func unparseScript(pops []parsedOpcode) ([]byte, error) { script := make([]byte, 0, len(pops)) for _, pop := range pops { b, err := pop.bytes() if err != nil { return nil, err } script = append(script, b...) } return script, nil }
[ "func", "unparseScript", "(", "pops", "[", "]", "parsedOpcode", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "script", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "len", "(", "pops", ")", ")", "\n", "for", "_", ",", "pop", ":=", "range", "pops", "{", "b", ",", "err", ":=", "pop", ".", "bytes", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "script", "=", "append", "(", "script", ",", "b", "...", ")", "\n", "}", "\n", "return", "script", ",", "nil", "\n", "}" ]
// unparseScript reversed the action of parseScript and returns the // parsedOpcodes as a list of bytes
[ "unparseScript", "reversed", "the", "action", "of", "parseScript", "and", "returns", "the", "parsedOpcodes", "as", "a", "list", "of", "bytes" ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/script.go#L289-L299
train
btcsuite/btcd
txscript/script.go
removeOpcode
func removeOpcode(pkscript []parsedOpcode, opcode byte) []parsedOpcode { retScript := make([]parsedOpcode, 0, len(pkscript)) for _, pop := range pkscript { if pop.opcode.value != opcode { retScript = append(retScript, pop) } } return retScript }
go
func removeOpcode(pkscript []parsedOpcode, opcode byte) []parsedOpcode { retScript := make([]parsedOpcode, 0, len(pkscript)) for _, pop := range pkscript { if pop.opcode.value != opcode { retScript = append(retScript, pop) } } return retScript }
[ "func", "removeOpcode", "(", "pkscript", "[", "]", "parsedOpcode", ",", "opcode", "byte", ")", "[", "]", "parsedOpcode", "{", "retScript", ":=", "make", "(", "[", "]", "parsedOpcode", ",", "0", ",", "len", "(", "pkscript", ")", ")", "\n", "for", "_", ",", "pop", ":=", "range", "pkscript", "{", "if", "pop", ".", "opcode", ".", "value", "!=", "opcode", "{", "retScript", "=", "append", "(", "retScript", ",", "pop", ")", "\n", "}", "\n", "}", "\n", "return", "retScript", "\n", "}" ]
// removeOpcode will remove any opcode matching ``opcode'' from the opcode // stream in pkscript
[ "removeOpcode", "will", "remove", "any", "opcode", "matching", "opcode", "from", "the", "opcode", "stream", "in", "pkscript" ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/script.go#L324-L332
train
btcsuite/btcd
txscript/script.go
canonicalPush
func canonicalPush(pop parsedOpcode) bool { opcode := pop.opcode.value data := pop.data dataLen := len(pop.data) if opcode > OP_16 { return true } if opcode < OP_PUSHDATA1 && opcode > OP_0 && (dataLen == 1 && data[0] <= 16) { return false } if opcode == OP_PUSHDATA1 && dataLen < OP_PUSHDATA1 { return false } if opcode == OP_PUSHDATA2 && dataLen <= 0xff { return false } if opcode == OP_PUSHDATA4 && dataLen <= 0xffff { return false } return true }
go
func canonicalPush(pop parsedOpcode) bool { opcode := pop.opcode.value data := pop.data dataLen := len(pop.data) if opcode > OP_16 { return true } if opcode < OP_PUSHDATA1 && opcode > OP_0 && (dataLen == 1 && data[0] <= 16) { return false } if opcode == OP_PUSHDATA1 && dataLen < OP_PUSHDATA1 { return false } if opcode == OP_PUSHDATA2 && dataLen <= 0xff { return false } if opcode == OP_PUSHDATA4 && dataLen <= 0xffff { return false } return true }
[ "func", "canonicalPush", "(", "pop", "parsedOpcode", ")", "bool", "{", "opcode", ":=", "pop", ".", "opcode", ".", "value", "\n", "data", ":=", "pop", ".", "data", "\n", "dataLen", ":=", "len", "(", "pop", ".", "data", ")", "\n", "if", "opcode", ">", "OP_16", "{", "return", "true", "\n", "}", "\n\n", "if", "opcode", "<", "OP_PUSHDATA1", "&&", "opcode", ">", "OP_0", "&&", "(", "dataLen", "==", "1", "&&", "data", "[", "0", "]", "<=", "16", ")", "{", "return", "false", "\n", "}", "\n", "if", "opcode", "==", "OP_PUSHDATA1", "&&", "dataLen", "<", "OP_PUSHDATA1", "{", "return", "false", "\n", "}", "\n", "if", "opcode", "==", "OP_PUSHDATA2", "&&", "dataLen", "<=", "0xff", "{", "return", "false", "\n", "}", "\n", "if", "opcode", "==", "OP_PUSHDATA4", "&&", "dataLen", "<=", "0xffff", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// canonicalPush returns true if the object is either not a push instruction // or the push instruction contained wherein is matches the canonical form // or using the smallest instruction to do the job. False otherwise.
[ "canonicalPush", "returns", "true", "if", "the", "object", "is", "either", "not", "a", "push", "instruction", "or", "the", "push", "instruction", "contained", "wherein", "is", "matches", "the", "canonical", "form", "or", "using", "the", "smallest", "instruction", "to", "do", "the", "job", ".", "False", "otherwise", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/script.go#L337-L358
train
btcsuite/btcd
txscript/script.go
removeOpcodeByData
func removeOpcodeByData(pkscript []parsedOpcode, data []byte) []parsedOpcode { retScript := make([]parsedOpcode, 0, len(pkscript)) for _, pop := range pkscript { if !canonicalPush(pop) || !bytes.Contains(pop.data, data) { retScript = append(retScript, pop) } } return retScript }
go
func removeOpcodeByData(pkscript []parsedOpcode, data []byte) []parsedOpcode { retScript := make([]parsedOpcode, 0, len(pkscript)) for _, pop := range pkscript { if !canonicalPush(pop) || !bytes.Contains(pop.data, data) { retScript = append(retScript, pop) } } return retScript }
[ "func", "removeOpcodeByData", "(", "pkscript", "[", "]", "parsedOpcode", ",", "data", "[", "]", "byte", ")", "[", "]", "parsedOpcode", "{", "retScript", ":=", "make", "(", "[", "]", "parsedOpcode", ",", "0", ",", "len", "(", "pkscript", ")", ")", "\n", "for", "_", ",", "pop", ":=", "range", "pkscript", "{", "if", "!", "canonicalPush", "(", "pop", ")", "||", "!", "bytes", ".", "Contains", "(", "pop", ".", "data", ",", "data", ")", "{", "retScript", "=", "append", "(", "retScript", ",", "pop", ")", "\n", "}", "\n", "}", "\n", "return", "retScript", "\n\n", "}" ]
// removeOpcodeByData will return the script minus any opcodes that would push // the passed data to the stack.
[ "removeOpcodeByData", "will", "return", "the", "script", "minus", "any", "opcodes", "that", "would", "push", "the", "passed", "data", "to", "the", "stack", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/script.go#L362-L371
train
btcsuite/btcd
txscript/script.go
CalcWitnessSigHash
func CalcWitnessSigHash(script []byte, sigHashes *TxSigHashes, hType SigHashType, tx *wire.MsgTx, idx int, amt int64) ([]byte, error) { parsedScript, err := parseScript(script) if err != nil { return nil, fmt.Errorf("cannot parse output script: %v", err) } return calcWitnessSignatureHash(parsedScript, sigHashes, hType, tx, idx, amt) }
go
func CalcWitnessSigHash(script []byte, sigHashes *TxSigHashes, hType SigHashType, tx *wire.MsgTx, idx int, amt int64) ([]byte, error) { parsedScript, err := parseScript(script) if err != nil { return nil, fmt.Errorf("cannot parse output script: %v", err) } return calcWitnessSignatureHash(parsedScript, sigHashes, hType, tx, idx, amt) }
[ "func", "CalcWitnessSigHash", "(", "script", "[", "]", "byte", ",", "sigHashes", "*", "TxSigHashes", ",", "hType", "SigHashType", ",", "tx", "*", "wire", ".", "MsgTx", ",", "idx", "int", ",", "amt", "int64", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "parsedScript", ",", "err", ":=", "parseScript", "(", "script", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "calcWitnessSignatureHash", "(", "parsedScript", ",", "sigHashes", ",", "hType", ",", "tx", ",", "idx", ",", "amt", ")", "\n", "}" ]
// CalcWitnessSigHash computes the sighash digest for the specified input of // the target transaction observing the desired sig hash type.
[ "CalcWitnessSigHash", "computes", "the", "sighash", "digest", "for", "the", "specified", "input", "of", "the", "target", "transaction", "observing", "the", "desired", "sig", "hash", "type", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/script.go#L545-L555
train
btcsuite/btcd
txscript/script.go
shallowCopyTx
func shallowCopyTx(tx *wire.MsgTx) wire.MsgTx { // As an additional memory optimization, use contiguous backing arrays // for the copied inputs and outputs and point the final slice of // pointers into the contiguous arrays. This avoids a lot of small // allocations. txCopy := wire.MsgTx{ Version: tx.Version, TxIn: make([]*wire.TxIn, len(tx.TxIn)), TxOut: make([]*wire.TxOut, len(tx.TxOut)), LockTime: tx.LockTime, } txIns := make([]wire.TxIn, len(tx.TxIn)) for i, oldTxIn := range tx.TxIn { txIns[i] = *oldTxIn txCopy.TxIn[i] = &txIns[i] } txOuts := make([]wire.TxOut, len(tx.TxOut)) for i, oldTxOut := range tx.TxOut { txOuts[i] = *oldTxOut txCopy.TxOut[i] = &txOuts[i] } return txCopy }
go
func shallowCopyTx(tx *wire.MsgTx) wire.MsgTx { // As an additional memory optimization, use contiguous backing arrays // for the copied inputs and outputs and point the final slice of // pointers into the contiguous arrays. This avoids a lot of small // allocations. txCopy := wire.MsgTx{ Version: tx.Version, TxIn: make([]*wire.TxIn, len(tx.TxIn)), TxOut: make([]*wire.TxOut, len(tx.TxOut)), LockTime: tx.LockTime, } txIns := make([]wire.TxIn, len(tx.TxIn)) for i, oldTxIn := range tx.TxIn { txIns[i] = *oldTxIn txCopy.TxIn[i] = &txIns[i] } txOuts := make([]wire.TxOut, len(tx.TxOut)) for i, oldTxOut := range tx.TxOut { txOuts[i] = *oldTxOut txCopy.TxOut[i] = &txOuts[i] } return txCopy }
[ "func", "shallowCopyTx", "(", "tx", "*", "wire", ".", "MsgTx", ")", "wire", ".", "MsgTx", "{", "// As an additional memory optimization, use contiguous backing arrays", "// for the copied inputs and outputs and point the final slice of", "// pointers into the contiguous arrays. This avoids a lot of small", "// allocations.", "txCopy", ":=", "wire", ".", "MsgTx", "{", "Version", ":", "tx", ".", "Version", ",", "TxIn", ":", "make", "(", "[", "]", "*", "wire", ".", "TxIn", ",", "len", "(", "tx", ".", "TxIn", ")", ")", ",", "TxOut", ":", "make", "(", "[", "]", "*", "wire", ".", "TxOut", ",", "len", "(", "tx", ".", "TxOut", ")", ")", ",", "LockTime", ":", "tx", ".", "LockTime", ",", "}", "\n", "txIns", ":=", "make", "(", "[", "]", "wire", ".", "TxIn", ",", "len", "(", "tx", ".", "TxIn", ")", ")", "\n", "for", "i", ",", "oldTxIn", ":=", "range", "tx", ".", "TxIn", "{", "txIns", "[", "i", "]", "=", "*", "oldTxIn", "\n", "txCopy", ".", "TxIn", "[", "i", "]", "=", "&", "txIns", "[", "i", "]", "\n", "}", "\n", "txOuts", ":=", "make", "(", "[", "]", "wire", ".", "TxOut", ",", "len", "(", "tx", ".", "TxOut", ")", ")", "\n", "for", "i", ",", "oldTxOut", ":=", "range", "tx", ".", "TxOut", "{", "txOuts", "[", "i", "]", "=", "*", "oldTxOut", "\n", "txCopy", ".", "TxOut", "[", "i", "]", "=", "&", "txOuts", "[", "i", "]", "\n", "}", "\n", "return", "txCopy", "\n", "}" ]
// shallowCopyTx creates a shallow copy of the transaction for use when // calculating the signature hash. It is used over the Copy method on the // transaction itself since that is a deep copy and therefore does more work and // allocates much more space than needed.
[ "shallowCopyTx", "creates", "a", "shallow", "copy", "of", "the", "transaction", "for", "use", "when", "calculating", "the", "signature", "hash", ".", "It", "is", "used", "over", "the", "Copy", "method", "on", "the", "transaction", "itself", "since", "that", "is", "a", "deep", "copy", "and", "therefore", "does", "more", "work", "and", "allocates", "much", "more", "space", "than", "needed", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/script.go#L561-L583
train
btcsuite/btcd
txscript/script.go
CalcSignatureHash
func CalcSignatureHash(script []byte, hashType SigHashType, tx *wire.MsgTx, idx int) ([]byte, error) { parsedScript, err := parseScript(script) if err != nil { return nil, fmt.Errorf("cannot parse output script: %v", err) } return calcSignatureHash(parsedScript, hashType, tx, idx), nil }
go
func CalcSignatureHash(script []byte, hashType SigHashType, tx *wire.MsgTx, idx int) ([]byte, error) { parsedScript, err := parseScript(script) if err != nil { return nil, fmt.Errorf("cannot parse output script: %v", err) } return calcSignatureHash(parsedScript, hashType, tx, idx), nil }
[ "func", "CalcSignatureHash", "(", "script", "[", "]", "byte", ",", "hashType", "SigHashType", ",", "tx", "*", "wire", ".", "MsgTx", ",", "idx", "int", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "parsedScript", ",", "err", ":=", "parseScript", "(", "script", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "calcSignatureHash", "(", "parsedScript", ",", "hashType", ",", "tx", ",", "idx", ")", ",", "nil", "\n", "}" ]
// CalcSignatureHash will, given a script and hash type for the current script // engine instance, calculate the signature hash to be used for signing and // verification.
[ "CalcSignatureHash", "will", "given", "a", "script", "and", "hash", "type", "for", "the", "current", "script", "engine", "instance", "calculate", "the", "signature", "hash", "to", "be", "used", "for", "signing", "and", "verification", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/script.go#L588-L594
train
btcsuite/btcd
txscript/script.go
calcSignatureHash
func calcSignatureHash(script []parsedOpcode, hashType SigHashType, tx *wire.MsgTx, idx int) []byte { // The SigHashSingle signature type signs only the corresponding input // and output (the output with the same index number as the input). // // Since transactions can have more inputs than outputs, this means it // is improper to use SigHashSingle on input indices that don't have a // corresponding output. // // A bug in the original Satoshi client implementation means specifying // an index that is out of range results in a signature hash of 1 (as a // uint256 little endian). The original intent appeared to be to // indicate failure, but unfortunately, it was never checked and thus is // treated as the actual signature hash. This buggy behavior is now // part of the consensus and a hard fork would be required to fix it. // // Due to this, care must be taken by software that creates transactions // which make use of SigHashSingle because it can lead to an extremely // dangerous situation where the invalid inputs will end up signing a // hash of 1. This in turn presents an opportunity for attackers to // cleverly construct transactions which can steal those coins provided // they can reuse signatures. if hashType&sigHashMask == SigHashSingle && idx >= len(tx.TxOut) { var hash chainhash.Hash hash[0] = 0x01 return hash[:] } // Remove all instances of OP_CODESEPARATOR from the script. script = removeOpcode(script, OP_CODESEPARATOR) // Make a shallow copy of the transaction, zeroing out the script for // all inputs that are not currently being processed. txCopy := shallowCopyTx(tx) for i := range txCopy.TxIn { if i == idx { // UnparseScript cannot fail here because removeOpcode // above only returns a valid script. sigScript, _ := unparseScript(script) txCopy.TxIn[idx].SignatureScript = sigScript } else { txCopy.TxIn[i].SignatureScript = nil } } switch hashType & sigHashMask { case SigHashNone: txCopy.TxOut = txCopy.TxOut[0:0] // Empty slice. for i := range txCopy.TxIn { if i != idx { txCopy.TxIn[i].Sequence = 0 } } case SigHashSingle: // Resize output array to up to and including requested index. txCopy.TxOut = txCopy.TxOut[:idx+1] // All but current output get zeroed out. for i := 0; i < idx; i++ { txCopy.TxOut[i].Value = -1 txCopy.TxOut[i].PkScript = nil } // Sequence on all other inputs is 0, too. for i := range txCopy.TxIn { if i != idx { txCopy.TxIn[i].Sequence = 0 } } default: // Consensus treats undefined hashtypes like normal SigHashAll // for purposes of hash generation. fallthrough case SigHashOld: fallthrough case SigHashAll: // Nothing special here. } if hashType&SigHashAnyOneCanPay != 0 { txCopy.TxIn = txCopy.TxIn[idx : idx+1] } // The final hash is the double sha256 of both the serialized modified // transaction and the hash type (encoded as a 4-byte little-endian // value) appended. wbuf := bytes.NewBuffer(make([]byte, 0, txCopy.SerializeSizeStripped()+4)) txCopy.SerializeNoWitness(wbuf) binary.Write(wbuf, binary.LittleEndian, hashType) return chainhash.DoubleHashB(wbuf.Bytes()) }
go
func calcSignatureHash(script []parsedOpcode, hashType SigHashType, tx *wire.MsgTx, idx int) []byte { // The SigHashSingle signature type signs only the corresponding input // and output (the output with the same index number as the input). // // Since transactions can have more inputs than outputs, this means it // is improper to use SigHashSingle on input indices that don't have a // corresponding output. // // A bug in the original Satoshi client implementation means specifying // an index that is out of range results in a signature hash of 1 (as a // uint256 little endian). The original intent appeared to be to // indicate failure, but unfortunately, it was never checked and thus is // treated as the actual signature hash. This buggy behavior is now // part of the consensus and a hard fork would be required to fix it. // // Due to this, care must be taken by software that creates transactions // which make use of SigHashSingle because it can lead to an extremely // dangerous situation where the invalid inputs will end up signing a // hash of 1. This in turn presents an opportunity for attackers to // cleverly construct transactions which can steal those coins provided // they can reuse signatures. if hashType&sigHashMask == SigHashSingle && idx >= len(tx.TxOut) { var hash chainhash.Hash hash[0] = 0x01 return hash[:] } // Remove all instances of OP_CODESEPARATOR from the script. script = removeOpcode(script, OP_CODESEPARATOR) // Make a shallow copy of the transaction, zeroing out the script for // all inputs that are not currently being processed. txCopy := shallowCopyTx(tx) for i := range txCopy.TxIn { if i == idx { // UnparseScript cannot fail here because removeOpcode // above only returns a valid script. sigScript, _ := unparseScript(script) txCopy.TxIn[idx].SignatureScript = sigScript } else { txCopy.TxIn[i].SignatureScript = nil } } switch hashType & sigHashMask { case SigHashNone: txCopy.TxOut = txCopy.TxOut[0:0] // Empty slice. for i := range txCopy.TxIn { if i != idx { txCopy.TxIn[i].Sequence = 0 } } case SigHashSingle: // Resize output array to up to and including requested index. txCopy.TxOut = txCopy.TxOut[:idx+1] // All but current output get zeroed out. for i := 0; i < idx; i++ { txCopy.TxOut[i].Value = -1 txCopy.TxOut[i].PkScript = nil } // Sequence on all other inputs is 0, too. for i := range txCopy.TxIn { if i != idx { txCopy.TxIn[i].Sequence = 0 } } default: // Consensus treats undefined hashtypes like normal SigHashAll // for purposes of hash generation. fallthrough case SigHashOld: fallthrough case SigHashAll: // Nothing special here. } if hashType&SigHashAnyOneCanPay != 0 { txCopy.TxIn = txCopy.TxIn[idx : idx+1] } // The final hash is the double sha256 of both the serialized modified // transaction and the hash type (encoded as a 4-byte little-endian // value) appended. wbuf := bytes.NewBuffer(make([]byte, 0, txCopy.SerializeSizeStripped()+4)) txCopy.SerializeNoWitness(wbuf) binary.Write(wbuf, binary.LittleEndian, hashType) return chainhash.DoubleHashB(wbuf.Bytes()) }
[ "func", "calcSignatureHash", "(", "script", "[", "]", "parsedOpcode", ",", "hashType", "SigHashType", ",", "tx", "*", "wire", ".", "MsgTx", ",", "idx", "int", ")", "[", "]", "byte", "{", "// The SigHashSingle signature type signs only the corresponding input", "// and output (the output with the same index number as the input).", "//", "// Since transactions can have more inputs than outputs, this means it", "// is improper to use SigHashSingle on input indices that don't have a", "// corresponding output.", "//", "// A bug in the original Satoshi client implementation means specifying", "// an index that is out of range results in a signature hash of 1 (as a", "// uint256 little endian). The original intent appeared to be to", "// indicate failure, but unfortunately, it was never checked and thus is", "// treated as the actual signature hash. This buggy behavior is now", "// part of the consensus and a hard fork would be required to fix it.", "//", "// Due to this, care must be taken by software that creates transactions", "// which make use of SigHashSingle because it can lead to an extremely", "// dangerous situation where the invalid inputs will end up signing a", "// hash of 1. This in turn presents an opportunity for attackers to", "// cleverly construct transactions which can steal those coins provided", "// they can reuse signatures.", "if", "hashType", "&", "sigHashMask", "==", "SigHashSingle", "&&", "idx", ">=", "len", "(", "tx", ".", "TxOut", ")", "{", "var", "hash", "chainhash", ".", "Hash", "\n", "hash", "[", "0", "]", "=", "0x01", "\n", "return", "hash", "[", ":", "]", "\n", "}", "\n\n", "// Remove all instances of OP_CODESEPARATOR from the script.", "script", "=", "removeOpcode", "(", "script", ",", "OP_CODESEPARATOR", ")", "\n\n", "// Make a shallow copy of the transaction, zeroing out the script for", "// all inputs that are not currently being processed.", "txCopy", ":=", "shallowCopyTx", "(", "tx", ")", "\n", "for", "i", ":=", "range", "txCopy", ".", "TxIn", "{", "if", "i", "==", "idx", "{", "// UnparseScript cannot fail here because removeOpcode", "// above only returns a valid script.", "sigScript", ",", "_", ":=", "unparseScript", "(", "script", ")", "\n", "txCopy", ".", "TxIn", "[", "idx", "]", ".", "SignatureScript", "=", "sigScript", "\n", "}", "else", "{", "txCopy", ".", "TxIn", "[", "i", "]", ".", "SignatureScript", "=", "nil", "\n", "}", "\n", "}", "\n\n", "switch", "hashType", "&", "sigHashMask", "{", "case", "SigHashNone", ":", "txCopy", ".", "TxOut", "=", "txCopy", ".", "TxOut", "[", "0", ":", "0", "]", "// Empty slice.", "\n", "for", "i", ":=", "range", "txCopy", ".", "TxIn", "{", "if", "i", "!=", "idx", "{", "txCopy", ".", "TxIn", "[", "i", "]", ".", "Sequence", "=", "0", "\n", "}", "\n", "}", "\n\n", "case", "SigHashSingle", ":", "// Resize output array to up to and including requested index.", "txCopy", ".", "TxOut", "=", "txCopy", ".", "TxOut", "[", ":", "idx", "+", "1", "]", "\n\n", "// All but current output get zeroed out.", "for", "i", ":=", "0", ";", "i", "<", "idx", ";", "i", "++", "{", "txCopy", ".", "TxOut", "[", "i", "]", ".", "Value", "=", "-", "1", "\n", "txCopy", ".", "TxOut", "[", "i", "]", ".", "PkScript", "=", "nil", "\n", "}", "\n\n", "// Sequence on all other inputs is 0, too.", "for", "i", ":=", "range", "txCopy", ".", "TxIn", "{", "if", "i", "!=", "idx", "{", "txCopy", ".", "TxIn", "[", "i", "]", ".", "Sequence", "=", "0", "\n", "}", "\n", "}", "\n\n", "default", ":", "// Consensus treats undefined hashtypes like normal SigHashAll", "// for purposes of hash generation.", "fallthrough", "\n", "case", "SigHashOld", ":", "fallthrough", "\n", "case", "SigHashAll", ":", "// Nothing special here.", "}", "\n", "if", "hashType", "&", "SigHashAnyOneCanPay", "!=", "0", "{", "txCopy", ".", "TxIn", "=", "txCopy", ".", "TxIn", "[", "idx", ":", "idx", "+", "1", "]", "\n", "}", "\n\n", "// The final hash is the double sha256 of both the serialized modified", "// transaction and the hash type (encoded as a 4-byte little-endian", "// value) appended.", "wbuf", ":=", "bytes", ".", "NewBuffer", "(", "make", "(", "[", "]", "byte", ",", "0", ",", "txCopy", ".", "SerializeSizeStripped", "(", ")", "+", "4", ")", ")", "\n", "txCopy", ".", "SerializeNoWitness", "(", "wbuf", ")", "\n", "binary", ".", "Write", "(", "wbuf", ",", "binary", ".", "LittleEndian", ",", "hashType", ")", "\n", "return", "chainhash", ".", "DoubleHashB", "(", "wbuf", ".", "Bytes", "(", ")", ")", "\n", "}" ]
// calcSignatureHash will, given a script and hash type for the current script // engine instance, calculate the signature hash to be used for signing and // verification.
[ "calcSignatureHash", "will", "given", "a", "script", "and", "hash", "type", "for", "the", "current", "script", "engine", "instance", "calculate", "the", "signature", "hash", "to", "be", "used", "for", "signing", "and", "verification", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/script.go#L599-L689
train
btcsuite/btcd
txscript/script.go
getSigOpCount
func getSigOpCount(pops []parsedOpcode, precise bool) int { nSigs := 0 for i, pop := range pops { switch pop.opcode.value { case OP_CHECKSIG: fallthrough case OP_CHECKSIGVERIFY: nSigs++ case OP_CHECKMULTISIG: fallthrough case OP_CHECKMULTISIGVERIFY: // If we are being precise then look for familiar // patterns for multisig, for now all we recognize is // OP_1 - OP_16 to signify the number of pubkeys. // Otherwise, we use the max of 20. if precise && i > 0 && pops[i-1].opcode.value >= OP_1 && pops[i-1].opcode.value <= OP_16 { nSigs += asSmallInt(pops[i-1].opcode) } else { nSigs += MaxPubKeysPerMultiSig } default: // Not a sigop. } } return nSigs }
go
func getSigOpCount(pops []parsedOpcode, precise bool) int { nSigs := 0 for i, pop := range pops { switch pop.opcode.value { case OP_CHECKSIG: fallthrough case OP_CHECKSIGVERIFY: nSigs++ case OP_CHECKMULTISIG: fallthrough case OP_CHECKMULTISIGVERIFY: // If we are being precise then look for familiar // patterns for multisig, for now all we recognize is // OP_1 - OP_16 to signify the number of pubkeys. // Otherwise, we use the max of 20. if precise && i > 0 && pops[i-1].opcode.value >= OP_1 && pops[i-1].opcode.value <= OP_16 { nSigs += asSmallInt(pops[i-1].opcode) } else { nSigs += MaxPubKeysPerMultiSig } default: // Not a sigop. } } return nSigs }
[ "func", "getSigOpCount", "(", "pops", "[", "]", "parsedOpcode", ",", "precise", "bool", ")", "int", "{", "nSigs", ":=", "0", "\n", "for", "i", ",", "pop", ":=", "range", "pops", "{", "switch", "pop", ".", "opcode", ".", "value", "{", "case", "OP_CHECKSIG", ":", "fallthrough", "\n", "case", "OP_CHECKSIGVERIFY", ":", "nSigs", "++", "\n", "case", "OP_CHECKMULTISIG", ":", "fallthrough", "\n", "case", "OP_CHECKMULTISIGVERIFY", ":", "// If we are being precise then look for familiar", "// patterns for multisig, for now all we recognize is", "// OP_1 - OP_16 to signify the number of pubkeys.", "// Otherwise, we use the max of 20.", "if", "precise", "&&", "i", ">", "0", "&&", "pops", "[", "i", "-", "1", "]", ".", "opcode", ".", "value", ">=", "OP_1", "&&", "pops", "[", "i", "-", "1", "]", ".", "opcode", ".", "value", "<=", "OP_16", "{", "nSigs", "+=", "asSmallInt", "(", "pops", "[", "i", "-", "1", "]", ".", "opcode", ")", "\n", "}", "else", "{", "nSigs", "+=", "MaxPubKeysPerMultiSig", "\n", "}", "\n", "default", ":", "// Not a sigop.", "}", "\n", "}", "\n\n", "return", "nSigs", "\n", "}" ]
// getSigOpCount is the implementation function for counting the number of // signature operations in the script provided by pops. If precise mode is // requested then we attempt to count the number of operations for a multisig // op. Otherwise we use the maximum.
[ "getSigOpCount", "is", "the", "implementation", "function", "for", "counting", "the", "number", "of", "signature", "operations", "in", "the", "script", "provided", "by", "pops", ".", "If", "precise", "mode", "is", "requested", "then", "we", "attempt", "to", "count", "the", "number", "of", "operations", "for", "a", "multisig", "op", ".", "Otherwise", "we", "use", "the", "maximum", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/script.go#L705-L733
train
btcsuite/btcd
txscript/script.go
GetSigOpCount
func GetSigOpCount(script []byte) int { // Don't check error since parseScript returns the parsed-up-to-error // list of pops. pops, _ := parseScript(script) return getSigOpCount(pops, false) }
go
func GetSigOpCount(script []byte) int { // Don't check error since parseScript returns the parsed-up-to-error // list of pops. pops, _ := parseScript(script) return getSigOpCount(pops, false) }
[ "func", "GetSigOpCount", "(", "script", "[", "]", "byte", ")", "int", "{", "// Don't check error since parseScript returns the parsed-up-to-error", "// list of pops.", "pops", ",", "_", ":=", "parseScript", "(", "script", ")", "\n", "return", "getSigOpCount", "(", "pops", ",", "false", ")", "\n", "}" ]
// GetSigOpCount provides a quick count of the number of signature operations // in a script. a CHECKSIG operations counts for 1, and a CHECK_MULTISIG for 20. // If the script fails to parse, then the count up to the point of failure is // returned.
[ "GetSigOpCount", "provides", "a", "quick", "count", "of", "the", "number", "of", "signature", "operations", "in", "a", "script", ".", "a", "CHECKSIG", "operations", "counts", "for", "1", "and", "a", "CHECK_MULTISIG", "for", "20", ".", "If", "the", "script", "fails", "to", "parse", "then", "the", "count", "up", "to", "the", "point", "of", "failure", "is", "returned", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/script.go#L739-L744
train
btcsuite/btcd
txscript/script.go
GetPreciseSigOpCount
func GetPreciseSigOpCount(scriptSig, scriptPubKey []byte, bip16 bool) int { // Don't check error since parseScript returns the parsed-up-to-error // list of pops. pops, _ := parseScript(scriptPubKey) // Treat non P2SH transactions as normal. if !(bip16 && isScriptHash(pops)) { return getSigOpCount(pops, true) } // The public key script is a pay-to-script-hash, so parse the signature // script to get the final item. Scripts that fail to fully parse count // as 0 signature operations. sigPops, err := parseScript(scriptSig) if err != nil { return 0 } // The signature script must only push data to the stack for P2SH to be // a valid pair, so the signature operation count is 0 when that is not // the case. if !isPushOnly(sigPops) || len(sigPops) == 0 { return 0 } // The P2SH script is the last item the signature script pushes to the // stack. When the script is empty, there are no signature operations. shScript := sigPops[len(sigPops)-1].data if len(shScript) == 0 { return 0 } // Parse the P2SH script and don't check the error since parseScript // returns the parsed-up-to-error list of pops and the consensus rules // dictate signature operations are counted up to the first parse // failure. shPops, _ := parseScript(shScript) return getSigOpCount(shPops, true) }
go
func GetPreciseSigOpCount(scriptSig, scriptPubKey []byte, bip16 bool) int { // Don't check error since parseScript returns the parsed-up-to-error // list of pops. pops, _ := parseScript(scriptPubKey) // Treat non P2SH transactions as normal. if !(bip16 && isScriptHash(pops)) { return getSigOpCount(pops, true) } // The public key script is a pay-to-script-hash, so parse the signature // script to get the final item. Scripts that fail to fully parse count // as 0 signature operations. sigPops, err := parseScript(scriptSig) if err != nil { return 0 } // The signature script must only push data to the stack for P2SH to be // a valid pair, so the signature operation count is 0 when that is not // the case. if !isPushOnly(sigPops) || len(sigPops) == 0 { return 0 } // The P2SH script is the last item the signature script pushes to the // stack. When the script is empty, there are no signature operations. shScript := sigPops[len(sigPops)-1].data if len(shScript) == 0 { return 0 } // Parse the P2SH script and don't check the error since parseScript // returns the parsed-up-to-error list of pops and the consensus rules // dictate signature operations are counted up to the first parse // failure. shPops, _ := parseScript(shScript) return getSigOpCount(shPops, true) }
[ "func", "GetPreciseSigOpCount", "(", "scriptSig", ",", "scriptPubKey", "[", "]", "byte", ",", "bip16", "bool", ")", "int", "{", "// Don't check error since parseScript returns the parsed-up-to-error", "// list of pops.", "pops", ",", "_", ":=", "parseScript", "(", "scriptPubKey", ")", "\n\n", "// Treat non P2SH transactions as normal.", "if", "!", "(", "bip16", "&&", "isScriptHash", "(", "pops", ")", ")", "{", "return", "getSigOpCount", "(", "pops", ",", "true", ")", "\n", "}", "\n\n", "// The public key script is a pay-to-script-hash, so parse the signature", "// script to get the final item. Scripts that fail to fully parse count", "// as 0 signature operations.", "sigPops", ",", "err", ":=", "parseScript", "(", "scriptSig", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", "\n", "}", "\n\n", "// The signature script must only push data to the stack for P2SH to be", "// a valid pair, so the signature operation count is 0 when that is not", "// the case.", "if", "!", "isPushOnly", "(", "sigPops", ")", "||", "len", "(", "sigPops", ")", "==", "0", "{", "return", "0", "\n", "}", "\n\n", "// The P2SH script is the last item the signature script pushes to the", "// stack. When the script is empty, there are no signature operations.", "shScript", ":=", "sigPops", "[", "len", "(", "sigPops", ")", "-", "1", "]", ".", "data", "\n", "if", "len", "(", "shScript", ")", "==", "0", "{", "return", "0", "\n", "}", "\n\n", "// Parse the P2SH script and don't check the error since parseScript", "// returns the parsed-up-to-error list of pops and the consensus rules", "// dictate signature operations are counted up to the first parse", "// failure.", "shPops", ",", "_", ":=", "parseScript", "(", "shScript", ")", "\n", "return", "getSigOpCount", "(", "shPops", ",", "true", ")", "\n", "}" ]
// GetPreciseSigOpCount returns the number of signature operations in // scriptPubKey. If bip16 is true then scriptSig may be searched for the // Pay-To-Script-Hash script in order to find the precise number of signature // operations in the transaction. If the script fails to parse, then the count // up to the point of failure is returned.
[ "GetPreciseSigOpCount", "returns", "the", "number", "of", "signature", "operations", "in", "scriptPubKey", ".", "If", "bip16", "is", "true", "then", "scriptSig", "may", "be", "searched", "for", "the", "Pay", "-", "To", "-", "Script", "-", "Hash", "script", "in", "order", "to", "find", "the", "precise", "number", "of", "signature", "operations", "in", "the", "transaction", ".", "If", "the", "script", "fails", "to", "parse", "then", "the", "count", "up", "to", "the", "point", "of", "failure", "is", "returned", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/script.go#L751-L789
train
btcsuite/btcd
txscript/script.go
GetWitnessSigOpCount
func GetWitnessSigOpCount(sigScript, pkScript []byte, witness wire.TxWitness) int { // If this is a regular witness program, then we can proceed directly // to counting its signature operations without any further processing. if IsWitnessProgram(pkScript) { return getWitnessSigOps(pkScript, witness) } // Next, we'll check the sigScript to see if this is a nested p2sh // witness program. This is a case wherein the sigScript is actually a // datapush of a p2wsh witness program. sigPops, err := parseScript(sigScript) if err != nil { return 0 } if IsPayToScriptHash(pkScript) && isPushOnly(sigPops) && IsWitnessProgram(sigScript[1:]) { return getWitnessSigOps(sigScript[1:], witness) } return 0 }
go
func GetWitnessSigOpCount(sigScript, pkScript []byte, witness wire.TxWitness) int { // If this is a regular witness program, then we can proceed directly // to counting its signature operations without any further processing. if IsWitnessProgram(pkScript) { return getWitnessSigOps(pkScript, witness) } // Next, we'll check the sigScript to see if this is a nested p2sh // witness program. This is a case wherein the sigScript is actually a // datapush of a p2wsh witness program. sigPops, err := parseScript(sigScript) if err != nil { return 0 } if IsPayToScriptHash(pkScript) && isPushOnly(sigPops) && IsWitnessProgram(sigScript[1:]) { return getWitnessSigOps(sigScript[1:], witness) } return 0 }
[ "func", "GetWitnessSigOpCount", "(", "sigScript", ",", "pkScript", "[", "]", "byte", ",", "witness", "wire", ".", "TxWitness", ")", "int", "{", "// If this is a regular witness program, then we can proceed directly", "// to counting its signature operations without any further processing.", "if", "IsWitnessProgram", "(", "pkScript", ")", "{", "return", "getWitnessSigOps", "(", "pkScript", ",", "witness", ")", "\n", "}", "\n\n", "// Next, we'll check the sigScript to see if this is a nested p2sh", "// witness program. This is a case wherein the sigScript is actually a", "// datapush of a p2wsh witness program.", "sigPops", ",", "err", ":=", "parseScript", "(", "sigScript", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", "\n", "}", "\n", "if", "IsPayToScriptHash", "(", "pkScript", ")", "&&", "isPushOnly", "(", "sigPops", ")", "&&", "IsWitnessProgram", "(", "sigScript", "[", "1", ":", "]", ")", "{", "return", "getWitnessSigOps", "(", "sigScript", "[", "1", ":", "]", ",", "witness", ")", "\n", "}", "\n\n", "return", "0", "\n", "}" ]
// GetWitnessSigOpCount returns the number of signature operations generated by // spending the passed pkScript with the specified witness, or sigScript. // Unlike GetPreciseSigOpCount, this function is able to accurately count the // number of signature operations generated by spending witness programs, and // nested p2sh witness programs. If the script fails to parse, then the count // up to the point of failure is returned.
[ "GetWitnessSigOpCount", "returns", "the", "number", "of", "signature", "operations", "generated", "by", "spending", "the", "passed", "pkScript", "with", "the", "specified", "witness", "or", "sigScript", ".", "Unlike", "GetPreciseSigOpCount", "this", "function", "is", "able", "to", "accurately", "count", "the", "number", "of", "signature", "operations", "generated", "by", "spending", "witness", "programs", "and", "nested", "p2sh", "witness", "programs", ".", "If", "the", "script", "fails", "to", "parse", "then", "the", "count", "up", "to", "the", "point", "of", "failure", "is", "returned", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/script.go#L797-L817
train
btcsuite/btcd
txscript/script.go
getWitnessSigOps
func getWitnessSigOps(pkScript []byte, witness wire.TxWitness) int { // Attempt to extract the witness program version. witnessVersion, witnessProgram, err := ExtractWitnessProgramInfo( pkScript, ) if err != nil { return 0 } switch witnessVersion { case 0: switch { case len(witnessProgram) == payToWitnessPubKeyHashDataSize: return 1 case len(witnessProgram) == payToWitnessScriptHashDataSize && len(witness) > 0: witnessScript := witness[len(witness)-1] pops, _ := parseScript(witnessScript) return getSigOpCount(pops, true) } } return 0 }
go
func getWitnessSigOps(pkScript []byte, witness wire.TxWitness) int { // Attempt to extract the witness program version. witnessVersion, witnessProgram, err := ExtractWitnessProgramInfo( pkScript, ) if err != nil { return 0 } switch witnessVersion { case 0: switch { case len(witnessProgram) == payToWitnessPubKeyHashDataSize: return 1 case len(witnessProgram) == payToWitnessScriptHashDataSize && len(witness) > 0: witnessScript := witness[len(witness)-1] pops, _ := parseScript(witnessScript) return getSigOpCount(pops, true) } } return 0 }
[ "func", "getWitnessSigOps", "(", "pkScript", "[", "]", "byte", ",", "witness", "wire", ".", "TxWitness", ")", "int", "{", "// Attempt to extract the witness program version.", "witnessVersion", ",", "witnessProgram", ",", "err", ":=", "ExtractWitnessProgramInfo", "(", "pkScript", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", "\n", "}", "\n\n", "switch", "witnessVersion", "{", "case", "0", ":", "switch", "{", "case", "len", "(", "witnessProgram", ")", "==", "payToWitnessPubKeyHashDataSize", ":", "return", "1", "\n", "case", "len", "(", "witnessProgram", ")", "==", "payToWitnessScriptHashDataSize", "&&", "len", "(", "witness", ")", ">", "0", ":", "witnessScript", ":=", "witness", "[", "len", "(", "witness", ")", "-", "1", "]", "\n", "pops", ",", "_", ":=", "parseScript", "(", "witnessScript", ")", "\n", "return", "getSigOpCount", "(", "pops", ",", "true", ")", "\n", "}", "\n", "}", "\n\n", "return", "0", "\n", "}" ]
// getWitnessSigOps returns the number of signature operations generated by // spending the passed witness program wit the passed witness. The exact // signature counting heuristic is modified by the version of the passed // witness program. If the version of the witness program is unable to be // extracted, then 0 is returned for the sig op count.
[ "getWitnessSigOps", "returns", "the", "number", "of", "signature", "operations", "generated", "by", "spending", "the", "passed", "witness", "program", "wit", "the", "passed", "witness", ".", "The", "exact", "signature", "counting", "heuristic", "is", "modified", "by", "the", "version", "of", "the", "passed", "witness", "program", ".", "If", "the", "version", "of", "the", "witness", "program", "is", "unable", "to", "be", "extracted", "then", "0", "is", "returned", "for", "the", "sig", "op", "count", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/script.go#L824-L848
train
btcsuite/btcd
txscript/script.go
IsUnspendable
func IsUnspendable(pkScript []byte) bool { pops, err := parseScript(pkScript) if err != nil { return true } return len(pops) > 0 && pops[0].opcode.value == OP_RETURN }
go
func IsUnspendable(pkScript []byte) bool { pops, err := parseScript(pkScript) if err != nil { return true } return len(pops) > 0 && pops[0].opcode.value == OP_RETURN }
[ "func", "IsUnspendable", "(", "pkScript", "[", "]", "byte", ")", "bool", "{", "pops", ",", "err", ":=", "parseScript", "(", "pkScript", ")", "\n", "if", "err", "!=", "nil", "{", "return", "true", "\n", "}", "\n\n", "return", "len", "(", "pops", ")", ">", "0", "&&", "pops", "[", "0", "]", ".", "opcode", ".", "value", "==", "OP_RETURN", "\n", "}" ]
// IsUnspendable returns whether the passed public key script is unspendable, or // guaranteed to fail at execution. This allows inputs to be pruned instantly // when entering the UTXO set.
[ "IsUnspendable", "returns", "whether", "the", "passed", "public", "key", "script", "is", "unspendable", "or", "guaranteed", "to", "fail", "at", "execution", ".", "This", "allows", "inputs", "to", "be", "pruned", "instantly", "when", "entering", "the", "UTXO", "set", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/script.go#L853-L860
train
btcsuite/btcd
btcec/gensecp256k1.go
SerializedBytePoints
func (curve *KoblitzCurve) SerializedBytePoints() []byte { doublingPoints := curve.getDoublingPoints() // Segregate the bits into byte-sized windows serialized := make([]byte, curve.byteSize*256*3*10*4) offset := 0 for byteNum := 0; byteNum < curve.byteSize; byteNum++ { // Grab the 8 bits that make up this byte from doublingPoints. startingBit := 8 * (curve.byteSize - byteNum - 1) computingPoints := doublingPoints[startingBit : startingBit+8] // Compute all points in this window and serialize them. for i := 0; i < 256; i++ { px, py, pz := new(fieldVal), new(fieldVal), new(fieldVal) for j := 0; j < 8; j++ { if i>>uint(j)&1 == 1 { curve.addJacobian(px, py, pz, &computingPoints[j][0], &computingPoints[j][1], &computingPoints[j][2], px, py, pz) } } for i := 0; i < 10; i++ { binary.LittleEndian.PutUint32(serialized[offset:], px.n[i]) offset += 4 } for i := 0; i < 10; i++ { binary.LittleEndian.PutUint32(serialized[offset:], py.n[i]) offset += 4 } for i := 0; i < 10; i++ { binary.LittleEndian.PutUint32(serialized[offset:], pz.n[i]) offset += 4 } } } return serialized }
go
func (curve *KoblitzCurve) SerializedBytePoints() []byte { doublingPoints := curve.getDoublingPoints() // Segregate the bits into byte-sized windows serialized := make([]byte, curve.byteSize*256*3*10*4) offset := 0 for byteNum := 0; byteNum < curve.byteSize; byteNum++ { // Grab the 8 bits that make up this byte from doublingPoints. startingBit := 8 * (curve.byteSize - byteNum - 1) computingPoints := doublingPoints[startingBit : startingBit+8] // Compute all points in this window and serialize them. for i := 0; i < 256; i++ { px, py, pz := new(fieldVal), new(fieldVal), new(fieldVal) for j := 0; j < 8; j++ { if i>>uint(j)&1 == 1 { curve.addJacobian(px, py, pz, &computingPoints[j][0], &computingPoints[j][1], &computingPoints[j][2], px, py, pz) } } for i := 0; i < 10; i++ { binary.LittleEndian.PutUint32(serialized[offset:], px.n[i]) offset += 4 } for i := 0; i < 10; i++ { binary.LittleEndian.PutUint32(serialized[offset:], py.n[i]) offset += 4 } for i := 0; i < 10; i++ { binary.LittleEndian.PutUint32(serialized[offset:], pz.n[i]) offset += 4 } } } return serialized }
[ "func", "(", "curve", "*", "KoblitzCurve", ")", "SerializedBytePoints", "(", ")", "[", "]", "byte", "{", "doublingPoints", ":=", "curve", ".", "getDoublingPoints", "(", ")", "\n\n", "// Segregate the bits into byte-sized windows", "serialized", ":=", "make", "(", "[", "]", "byte", ",", "curve", ".", "byteSize", "*", "256", "*", "3", "*", "10", "*", "4", ")", "\n", "offset", ":=", "0", "\n", "for", "byteNum", ":=", "0", ";", "byteNum", "<", "curve", ".", "byteSize", ";", "byteNum", "++", "{", "// Grab the 8 bits that make up this byte from doublingPoints.", "startingBit", ":=", "8", "*", "(", "curve", ".", "byteSize", "-", "byteNum", "-", "1", ")", "\n", "computingPoints", ":=", "doublingPoints", "[", "startingBit", ":", "startingBit", "+", "8", "]", "\n\n", "// Compute all points in this window and serialize them.", "for", "i", ":=", "0", ";", "i", "<", "256", ";", "i", "++", "{", "px", ",", "py", ",", "pz", ":=", "new", "(", "fieldVal", ")", ",", "new", "(", "fieldVal", ")", ",", "new", "(", "fieldVal", ")", "\n", "for", "j", ":=", "0", ";", "j", "<", "8", ";", "j", "++", "{", "if", "i", ">>", "uint", "(", "j", ")", "&", "1", "==", "1", "{", "curve", ".", "addJacobian", "(", "px", ",", "py", ",", "pz", ",", "&", "computingPoints", "[", "j", "]", "[", "0", "]", ",", "&", "computingPoints", "[", "j", "]", "[", "1", "]", ",", "&", "computingPoints", "[", "j", "]", "[", "2", "]", ",", "px", ",", "py", ",", "pz", ")", "\n", "}", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "10", ";", "i", "++", "{", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "serialized", "[", "offset", ":", "]", ",", "px", ".", "n", "[", "i", "]", ")", "\n", "offset", "+=", "4", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "10", ";", "i", "++", "{", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "serialized", "[", "offset", ":", "]", ",", "py", ".", "n", "[", "i", "]", ")", "\n", "offset", "+=", "4", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "10", ";", "i", "++", "{", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "serialized", "[", "offset", ":", "]", ",", "pz", ".", "n", "[", "i", "]", ")", "\n", "offset", "+=", "4", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "serialized", "\n", "}" ]
// SerializedBytePoints returns a serialized byte slice which contains all of // the possible points per 8-bit window. This is used to when generating // secp256k1.go.
[ "SerializedBytePoints", "returns", "a", "serialized", "byte", "slice", "which", "contains", "all", "of", "the", "possible", "points", "per", "8", "-", "bit", "window", ".", "This", "is", "used", "to", "when", "generating", "secp256k1", ".", "go", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/gensecp256k1.go#L43-L79
train
btcsuite/btcd
btcec/gensecp256k1.go
sqrt
func sqrt(n *big.Int) *big.Int { // Initial guess = 2^(log_2(n)/2) guess := big.NewInt(2) guess.Exp(guess, big.NewInt(int64(n.BitLen()/2)), nil) // Now refine using Newton's method. big2 := big.NewInt(2) prevGuess := big.NewInt(0) for { prevGuess.Set(guess) guess.Add(guess, new(big.Int).Div(n, guess)) guess.Div(guess, big2) if guess.Cmp(prevGuess) == 0 { break } } return guess }
go
func sqrt(n *big.Int) *big.Int { // Initial guess = 2^(log_2(n)/2) guess := big.NewInt(2) guess.Exp(guess, big.NewInt(int64(n.BitLen()/2)), nil) // Now refine using Newton's method. big2 := big.NewInt(2) prevGuess := big.NewInt(0) for { prevGuess.Set(guess) guess.Add(guess, new(big.Int).Div(n, guess)) guess.Div(guess, big2) if guess.Cmp(prevGuess) == 0 { break } } return guess }
[ "func", "sqrt", "(", "n", "*", "big", ".", "Int", ")", "*", "big", ".", "Int", "{", "// Initial guess = 2^(log_2(n)/2)", "guess", ":=", "big", ".", "NewInt", "(", "2", ")", "\n", "guess", ".", "Exp", "(", "guess", ",", "big", ".", "NewInt", "(", "int64", "(", "n", ".", "BitLen", "(", ")", "/", "2", ")", ")", ",", "nil", ")", "\n\n", "// Now refine using Newton's method.", "big2", ":=", "big", ".", "NewInt", "(", "2", ")", "\n", "prevGuess", ":=", "big", ".", "NewInt", "(", "0", ")", "\n", "for", "{", "prevGuess", ".", "Set", "(", "guess", ")", "\n", "guess", ".", "Add", "(", "guess", ",", "new", "(", "big", ".", "Int", ")", ".", "Div", "(", "n", ",", "guess", ")", ")", "\n", "guess", ".", "Div", "(", "guess", ",", "big2", ")", "\n", "if", "guess", ".", "Cmp", "(", "prevGuess", ")", "==", "0", "{", "break", "\n", "}", "\n", "}", "\n", "return", "guess", "\n", "}" ]
// sqrt returns the square root of the provided big integer using Newton's // method. It's only compiled and used during generation of pre-computed // values, so speed is not a huge concern.
[ "sqrt", "returns", "the", "square", "root", "of", "the", "provided", "big", "integer", "using", "Newton", "s", "method", ".", "It", "s", "only", "compiled", "and", "used", "during", "generation", "of", "pre", "-", "computed", "values", "so", "speed", "is", "not", "a", "huge", "concern", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/gensecp256k1.go#L84-L101
train
btcsuite/btcd
database/ffldb/blockio.go
deserializeBlockLoc
func deserializeBlockLoc(serializedLoc []byte) blockLocation { // The serialized block location format is: // // [0:4] Block file (4 bytes) // [4:8] File offset (4 bytes) // [8:12] Block length (4 bytes) return blockLocation{ blockFileNum: byteOrder.Uint32(serializedLoc[0:4]), fileOffset: byteOrder.Uint32(serializedLoc[4:8]), blockLen: byteOrder.Uint32(serializedLoc[8:12]), } }
go
func deserializeBlockLoc(serializedLoc []byte) blockLocation { // The serialized block location format is: // // [0:4] Block file (4 bytes) // [4:8] File offset (4 bytes) // [8:12] Block length (4 bytes) return blockLocation{ blockFileNum: byteOrder.Uint32(serializedLoc[0:4]), fileOffset: byteOrder.Uint32(serializedLoc[4:8]), blockLen: byteOrder.Uint32(serializedLoc[8:12]), } }
[ "func", "deserializeBlockLoc", "(", "serializedLoc", "[", "]", "byte", ")", "blockLocation", "{", "// The serialized block location format is:", "//", "// [0:4] Block file (4 bytes)", "// [4:8] File offset (4 bytes)", "// [8:12] Block length (4 bytes)", "return", "blockLocation", "{", "blockFileNum", ":", "byteOrder", ".", "Uint32", "(", "serializedLoc", "[", "0", ":", "4", "]", ")", ",", "fileOffset", ":", "byteOrder", ".", "Uint32", "(", "serializedLoc", "[", "4", ":", "8", "]", ")", ",", "blockLen", ":", "byteOrder", ".", "Uint32", "(", "serializedLoc", "[", "8", ":", "12", "]", ")", ",", "}", "\n", "}" ]
// deserializeBlockLoc deserializes the passed serialized block location // information. This is data stored into the block index metadata for each // block. The serialized data passed to this function MUST be at least // blockLocSize bytes or it will panic. The error check is avoided here because // this information will always be coming from the block index which includes a // checksum to detect corruption. Thus it is safe to use this unchecked here.
[ "deserializeBlockLoc", "deserializes", "the", "passed", "serialized", "block", "location", "information", ".", "This", "is", "data", "stored", "into", "the", "block", "index", "metadata", "for", "each", "block", ".", "The", "serialized", "data", "passed", "to", "this", "function", "MUST", "be", "at", "least", "blockLocSize", "bytes", "or", "it", "will", "panic", ".", "The", "error", "check", "is", "avoided", "here", "because", "this", "information", "will", "always", "be", "coming", "from", "the", "block", "index", "which", "includes", "a", "checksum", "to", "detect", "corruption", ".", "Thus", "it", "is", "safe", "to", "use", "this", "unchecked", "here", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/blockio.go#L192-L203
train
btcsuite/btcd
database/ffldb/blockio.go
serializeBlockLoc
func serializeBlockLoc(loc blockLocation) []byte { // The serialized block location format is: // // [0:4] Block file (4 bytes) // [4:8] File offset (4 bytes) // [8:12] Block length (4 bytes) var serializedData [12]byte byteOrder.PutUint32(serializedData[0:4], loc.blockFileNum) byteOrder.PutUint32(serializedData[4:8], loc.fileOffset) byteOrder.PutUint32(serializedData[8:12], loc.blockLen) return serializedData[:] }
go
func serializeBlockLoc(loc blockLocation) []byte { // The serialized block location format is: // // [0:4] Block file (4 bytes) // [4:8] File offset (4 bytes) // [8:12] Block length (4 bytes) var serializedData [12]byte byteOrder.PutUint32(serializedData[0:4], loc.blockFileNum) byteOrder.PutUint32(serializedData[4:8], loc.fileOffset) byteOrder.PutUint32(serializedData[8:12], loc.blockLen) return serializedData[:] }
[ "func", "serializeBlockLoc", "(", "loc", "blockLocation", ")", "[", "]", "byte", "{", "// The serialized block location format is:", "//", "// [0:4] Block file (4 bytes)", "// [4:8] File offset (4 bytes)", "// [8:12] Block length (4 bytes)", "var", "serializedData", "[", "12", "]", "byte", "\n", "byteOrder", ".", "PutUint32", "(", "serializedData", "[", "0", ":", "4", "]", ",", "loc", ".", "blockFileNum", ")", "\n", "byteOrder", ".", "PutUint32", "(", "serializedData", "[", "4", ":", "8", "]", ",", "loc", ".", "fileOffset", ")", "\n", "byteOrder", ".", "PutUint32", "(", "serializedData", "[", "8", ":", "12", "]", ",", "loc", ".", "blockLen", ")", "\n", "return", "serializedData", "[", ":", "]", "\n", "}" ]
// serializeBlockLoc returns the serialization of the passed block location. // This is data to be stored into the block index metadata for each block.
[ "serializeBlockLoc", "returns", "the", "serialization", "of", "the", "passed", "block", "location", ".", "This", "is", "data", "to", "be", "stored", "into", "the", "block", "index", "metadata", "for", "each", "block", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/blockio.go#L207-L218
train
btcsuite/btcd
database/ffldb/blockio.go
blockFilePath
func blockFilePath(dbPath string, fileNum uint32) string { fileName := fmt.Sprintf(blockFilenameTemplate, fileNum) return filepath.Join(dbPath, fileName) }
go
func blockFilePath(dbPath string, fileNum uint32) string { fileName := fmt.Sprintf(blockFilenameTemplate, fileNum) return filepath.Join(dbPath, fileName) }
[ "func", "blockFilePath", "(", "dbPath", "string", ",", "fileNum", "uint32", ")", "string", "{", "fileName", ":=", "fmt", ".", "Sprintf", "(", "blockFilenameTemplate", ",", "fileNum", ")", "\n", "return", "filepath", ".", "Join", "(", "dbPath", ",", "fileName", ")", "\n", "}" ]
// blockFilePath return the file path for the provided block file number.
[ "blockFilePath", "return", "the", "file", "path", "for", "the", "provided", "block", "file", "number", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/blockio.go#L221-L224
train
btcsuite/btcd
database/ffldb/blockio.go
deleteFile
func (s *blockStore) deleteFile(fileNum uint32) error { filePath := blockFilePath(s.basePath, fileNum) if err := os.Remove(filePath); err != nil { return makeDbErr(database.ErrDriverSpecific, err.Error(), err) } return nil }
go
func (s *blockStore) deleteFile(fileNum uint32) error { filePath := blockFilePath(s.basePath, fileNum) if err := os.Remove(filePath); err != nil { return makeDbErr(database.ErrDriverSpecific, err.Error(), err) } return nil }
[ "func", "(", "s", "*", "blockStore", ")", "deleteFile", "(", "fileNum", "uint32", ")", "error", "{", "filePath", ":=", "blockFilePath", "(", "s", ".", "basePath", ",", "fileNum", ")", "\n", "if", "err", ":=", "os", ".", "Remove", "(", "filePath", ")", ";", "err", "!=", "nil", "{", "return", "makeDbErr", "(", "database", ".", "ErrDriverSpecific", ",", "err", ".", "Error", "(", ")", ",", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// deleteFile removes the block file for the passed flat file number. The file // must already be closed and it is the responsibility of the caller to do any // other state cleanup necessary.
[ "deleteFile", "removes", "the", "block", "file", "for", "the", "passed", "flat", "file", "number", ".", "The", "file", "must", "already", "be", "closed", "and", "it", "is", "the", "responsibility", "of", "the", "caller", "to", "do", "any", "other", "state", "cleanup", "necessary", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/blockio.go#L301-L308
train
btcsuite/btcd
database/ffldb/blockio.go
syncBlocks
func (s *blockStore) syncBlocks() error { wc := s.writeCursor wc.RLock() defer wc.RUnlock() // Nothing to do if there is no current file associated with the write // cursor. wc.curFile.RLock() defer wc.curFile.RUnlock() if wc.curFile.file == nil { return nil } // Sync the file to disk. if err := wc.curFile.file.Sync(); err != nil { str := fmt.Sprintf("failed to sync file %d: %v", wc.curFileNum, err) return makeDbErr(database.ErrDriverSpecific, str, err) } return nil }
go
func (s *blockStore) syncBlocks() error { wc := s.writeCursor wc.RLock() defer wc.RUnlock() // Nothing to do if there is no current file associated with the write // cursor. wc.curFile.RLock() defer wc.curFile.RUnlock() if wc.curFile.file == nil { return nil } // Sync the file to disk. if err := wc.curFile.file.Sync(); err != nil { str := fmt.Sprintf("failed to sync file %d: %v", wc.curFileNum, err) return makeDbErr(database.ErrDriverSpecific, str, err) } return nil }
[ "func", "(", "s", "*", "blockStore", ")", "syncBlocks", "(", ")", "error", "{", "wc", ":=", "s", ".", "writeCursor", "\n", "wc", ".", "RLock", "(", ")", "\n", "defer", "wc", ".", "RUnlock", "(", ")", "\n\n", "// Nothing to do if there is no current file associated with the write", "// cursor.", "wc", ".", "curFile", ".", "RLock", "(", ")", "\n", "defer", "wc", ".", "curFile", ".", "RUnlock", "(", ")", "\n", "if", "wc", ".", "curFile", ".", "file", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "// Sync the file to disk.", "if", "err", ":=", "wc", ".", "curFile", ".", "file", ".", "Sync", "(", ")", ";", "err", "!=", "nil", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "wc", ".", "curFileNum", ",", "err", ")", "\n", "return", "makeDbErr", "(", "database", ".", "ErrDriverSpecific", ",", "str", ",", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// syncBlocks performs a file system sync on the flat file associated with the // store's current write cursor. It is safe to call even when there is not a // current write file in which case it will have no effect. // // This is used when flushing cached metadata updates to disk to ensure all the // block data is fully written before updating the metadata. This ensures the // metadata and block data can be properly reconciled in failure scenarios.
[ "syncBlocks", "performs", "a", "file", "system", "sync", "on", "the", "flat", "file", "associated", "with", "the", "store", "s", "current", "write", "cursor", ".", "It", "is", "safe", "to", "call", "even", "when", "there", "is", "not", "a", "current", "write", "file", "in", "which", "case", "it", "will", "have", "no", "effect", ".", "This", "is", "used", "when", "flushing", "cached", "metadata", "updates", "to", "disk", "to", "ensure", "all", "the", "block", "data", "is", "fully", "written", "before", "updating", "the", "metadata", ".", "This", "ensures", "the", "metadata", "and", "block", "data", "can", "be", "properly", "reconciled", "in", "failure", "scenarios", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/blockio.go#L597-L618
train
btcsuite/btcd
database/ffldb/blockio.go
scanBlockFiles
func scanBlockFiles(dbPath string) (int, uint32) { lastFile := -1 fileLen := uint32(0) for i := 0; ; i++ { filePath := blockFilePath(dbPath, uint32(i)) st, err := os.Stat(filePath) if err != nil { break } lastFile = i fileLen = uint32(st.Size()) } log.Tracef("Scan found latest block file #%d with length %d", lastFile, fileLen) return lastFile, fileLen }
go
func scanBlockFiles(dbPath string) (int, uint32) { lastFile := -1 fileLen := uint32(0) for i := 0; ; i++ { filePath := blockFilePath(dbPath, uint32(i)) st, err := os.Stat(filePath) if err != nil { break } lastFile = i fileLen = uint32(st.Size()) } log.Tracef("Scan found latest block file #%d with length %d", lastFile, fileLen) return lastFile, fileLen }
[ "func", "scanBlockFiles", "(", "dbPath", "string", ")", "(", "int", ",", "uint32", ")", "{", "lastFile", ":=", "-", "1", "\n", "fileLen", ":=", "uint32", "(", "0", ")", "\n", "for", "i", ":=", "0", ";", ";", "i", "++", "{", "filePath", ":=", "blockFilePath", "(", "dbPath", ",", "uint32", "(", "i", ")", ")", "\n", "st", ",", "err", ":=", "os", ".", "Stat", "(", "filePath", ")", "\n", "if", "err", "!=", "nil", "{", "break", "\n", "}", "\n", "lastFile", "=", "i", "\n\n", "fileLen", "=", "uint32", "(", "st", ".", "Size", "(", ")", ")", "\n", "}", "\n\n", "log", ".", "Tracef", "(", "\"", "\"", ",", "lastFile", ",", "fileLen", ")", "\n", "return", "lastFile", ",", "fileLen", "\n", "}" ]
// scanBlockFiles searches the database directory for all flat block files to // find the end of the most recent file. This position is considered the // current write cursor which is also stored in the metadata. Thus, it is used // to detect unexpected shutdowns in the middle of writes so the block files // can be reconciled.
[ "scanBlockFiles", "searches", "the", "database", "directory", "for", "all", "flat", "block", "files", "to", "find", "the", "end", "of", "the", "most", "recent", "file", ".", "This", "position", "is", "considered", "the", "current", "write", "cursor", "which", "is", "also", "stored", "in", "the", "metadata", ".", "Thus", "it", "is", "used", "to", "detect", "unexpected", "shutdowns", "in", "the", "middle", "of", "writes", "so", "the", "block", "files", "can", "be", "reconciled", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/blockio.go#L720-L737
train
btcsuite/btcd
database/ffldb/blockio.go
newBlockStore
func newBlockStore(basePath string, network wire.BitcoinNet) *blockStore { // Look for the end of the latest block to file to determine what the // write cursor position is from the viewpoing of the block files on // disk. fileNum, fileOff := scanBlockFiles(basePath) if fileNum == -1 { fileNum = 0 fileOff = 0 } store := &blockStore{ network: network, basePath: basePath, maxBlockFileSize: maxBlockFileSize, openBlockFiles: make(map[uint32]*lockableFile), openBlocksLRU: list.New(), fileNumToLRUElem: make(map[uint32]*list.Element), writeCursor: &writeCursor{ curFile: &lockableFile{}, curFileNum: uint32(fileNum), curOffset: fileOff, }, } store.openFileFunc = store.openFile store.openWriteFileFunc = store.openWriteFile store.deleteFileFunc = store.deleteFile return store }
go
func newBlockStore(basePath string, network wire.BitcoinNet) *blockStore { // Look for the end of the latest block to file to determine what the // write cursor position is from the viewpoing of the block files on // disk. fileNum, fileOff := scanBlockFiles(basePath) if fileNum == -1 { fileNum = 0 fileOff = 0 } store := &blockStore{ network: network, basePath: basePath, maxBlockFileSize: maxBlockFileSize, openBlockFiles: make(map[uint32]*lockableFile), openBlocksLRU: list.New(), fileNumToLRUElem: make(map[uint32]*list.Element), writeCursor: &writeCursor{ curFile: &lockableFile{}, curFileNum: uint32(fileNum), curOffset: fileOff, }, } store.openFileFunc = store.openFile store.openWriteFileFunc = store.openWriteFile store.deleteFileFunc = store.deleteFile return store }
[ "func", "newBlockStore", "(", "basePath", "string", ",", "network", "wire", ".", "BitcoinNet", ")", "*", "blockStore", "{", "// Look for the end of the latest block to file to determine what the", "// write cursor position is from the viewpoing of the block files on", "// disk.", "fileNum", ",", "fileOff", ":=", "scanBlockFiles", "(", "basePath", ")", "\n", "if", "fileNum", "==", "-", "1", "{", "fileNum", "=", "0", "\n", "fileOff", "=", "0", "\n", "}", "\n\n", "store", ":=", "&", "blockStore", "{", "network", ":", "network", ",", "basePath", ":", "basePath", ",", "maxBlockFileSize", ":", "maxBlockFileSize", ",", "openBlockFiles", ":", "make", "(", "map", "[", "uint32", "]", "*", "lockableFile", ")", ",", "openBlocksLRU", ":", "list", ".", "New", "(", ")", ",", "fileNumToLRUElem", ":", "make", "(", "map", "[", "uint32", "]", "*", "list", ".", "Element", ")", ",", "writeCursor", ":", "&", "writeCursor", "{", "curFile", ":", "&", "lockableFile", "{", "}", ",", "curFileNum", ":", "uint32", "(", "fileNum", ")", ",", "curOffset", ":", "fileOff", ",", "}", ",", "}", "\n", "store", ".", "openFileFunc", "=", "store", ".", "openFile", "\n", "store", ".", "openWriteFileFunc", "=", "store", ".", "openWriteFile", "\n", "store", ".", "deleteFileFunc", "=", "store", ".", "deleteFile", "\n", "return", "store", "\n", "}" ]
// newBlockStore returns a new block store with the current block file number // and offset set and all fields initialized.
[ "newBlockStore", "returns", "a", "new", "block", "store", "with", "the", "current", "block", "file", "number", "and", "offset", "set", "and", "all", "fields", "initialized", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/blockio.go#L741-L769
train
btcsuite/btcd
blockchain/chain.go
newBestState
func newBestState(node *blockNode, blockSize, blockWeight, numTxns, totalTxns uint64, medianTime time.Time) *BestState { return &BestState{ Hash: node.hash, Height: node.height, Bits: node.bits, BlockSize: blockSize, BlockWeight: blockWeight, NumTxns: numTxns, TotalTxns: totalTxns, MedianTime: medianTime, } }
go
func newBestState(node *blockNode, blockSize, blockWeight, numTxns, totalTxns uint64, medianTime time.Time) *BestState { return &BestState{ Hash: node.hash, Height: node.height, Bits: node.bits, BlockSize: blockSize, BlockWeight: blockWeight, NumTxns: numTxns, TotalTxns: totalTxns, MedianTime: medianTime, } }
[ "func", "newBestState", "(", "node", "*", "blockNode", ",", "blockSize", ",", "blockWeight", ",", "numTxns", ",", "totalTxns", "uint64", ",", "medianTime", "time", ".", "Time", ")", "*", "BestState", "{", "return", "&", "BestState", "{", "Hash", ":", "node", ".", "hash", ",", "Height", ":", "node", ".", "height", ",", "Bits", ":", "node", ".", "bits", ",", "BlockSize", ":", "blockSize", ",", "BlockWeight", ":", "blockWeight", ",", "NumTxns", ":", "numTxns", ",", "TotalTxns", ":", "totalTxns", ",", "MedianTime", ":", "medianTime", ",", "}", "\n", "}" ]
// newBestState returns a new best stats instance for the given parameters.
[ "newBestState", "returns", "a", "new", "best", "stats", "instance", "for", "the", "given", "parameters", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/chain.go#L73-L86
train
btcsuite/btcd
blockchain/chain.go
HaveBlock
func (b *BlockChain) HaveBlock(hash *chainhash.Hash) (bool, error) { exists, err := b.blockExists(hash) if err != nil { return false, err } return exists || b.IsKnownOrphan(hash), nil }
go
func (b *BlockChain) HaveBlock(hash *chainhash.Hash) (bool, error) { exists, err := b.blockExists(hash) if err != nil { return false, err } return exists || b.IsKnownOrphan(hash), nil }
[ "func", "(", "b", "*", "BlockChain", ")", "HaveBlock", "(", "hash", "*", "chainhash", ".", "Hash", ")", "(", "bool", ",", "error", ")", "{", "exists", ",", "err", ":=", "b", ".", "blockExists", "(", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "return", "exists", "||", "b", ".", "IsKnownOrphan", "(", "hash", ")", ",", "nil", "\n", "}" ]
// HaveBlock returns whether or not the chain instance has the block represented // by the passed hash. This includes checking the various places a block can // be like part of the main chain, on a side chain, or in the orphan pool. // // This function is safe for concurrent access.
[ "HaveBlock", "returns", "whether", "or", "not", "the", "chain", "instance", "has", "the", "block", "represented", "by", "the", "passed", "hash", ".", "This", "includes", "checking", "the", "various", "places", "a", "block", "can", "be", "like", "part", "of", "the", "main", "chain", "on", "a", "side", "chain", "or", "in", "the", "orphan", "pool", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/chain.go#L194-L200
train
btcsuite/btcd
blockchain/chain.go
GetOrphanRoot
func (b *BlockChain) GetOrphanRoot(hash *chainhash.Hash) *chainhash.Hash { // Protect concurrent access. Using a read lock only so multiple // readers can query without blocking each other. b.orphanLock.RLock() defer b.orphanLock.RUnlock() // Keep looping while the parent of each orphaned block is // known and is an orphan itself. orphanRoot := hash prevHash := hash for { orphan, exists := b.orphans[*prevHash] if !exists { break } orphanRoot = prevHash prevHash = &orphan.block.MsgBlock().Header.PrevBlock } return orphanRoot }
go
func (b *BlockChain) GetOrphanRoot(hash *chainhash.Hash) *chainhash.Hash { // Protect concurrent access. Using a read lock only so multiple // readers can query without blocking each other. b.orphanLock.RLock() defer b.orphanLock.RUnlock() // Keep looping while the parent of each orphaned block is // known and is an orphan itself. orphanRoot := hash prevHash := hash for { orphan, exists := b.orphans[*prevHash] if !exists { break } orphanRoot = prevHash prevHash = &orphan.block.MsgBlock().Header.PrevBlock } return orphanRoot }
[ "func", "(", "b", "*", "BlockChain", ")", "GetOrphanRoot", "(", "hash", "*", "chainhash", ".", "Hash", ")", "*", "chainhash", ".", "Hash", "{", "// Protect concurrent access. Using a read lock only so multiple", "// readers can query without blocking each other.", "b", ".", "orphanLock", ".", "RLock", "(", ")", "\n", "defer", "b", ".", "orphanLock", ".", "RUnlock", "(", ")", "\n\n", "// Keep looping while the parent of each orphaned block is", "// known and is an orphan itself.", "orphanRoot", ":=", "hash", "\n", "prevHash", ":=", "hash", "\n", "for", "{", "orphan", ",", "exists", ":=", "b", ".", "orphans", "[", "*", "prevHash", "]", "\n", "if", "!", "exists", "{", "break", "\n", "}", "\n", "orphanRoot", "=", "prevHash", "\n", "prevHash", "=", "&", "orphan", ".", "block", ".", "MsgBlock", "(", ")", ".", "Header", ".", "PrevBlock", "\n", "}", "\n\n", "return", "orphanRoot", "\n", "}" ]
// GetOrphanRoot returns the head of the chain for the provided hash from the // map of orphan blocks. // // This function is safe for concurrent access.
[ "GetOrphanRoot", "returns", "the", "head", "of", "the", "chain", "for", "the", "provided", "hash", "from", "the", "map", "of", "orphan", "blocks", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/chain.go#L226-L246
train
btcsuite/btcd
blockchain/chain.go
removeOrphanBlock
func (b *BlockChain) removeOrphanBlock(orphan *orphanBlock) { // Protect concurrent access. b.orphanLock.Lock() defer b.orphanLock.Unlock() // Remove the orphan block from the orphan pool. orphanHash := orphan.block.Hash() delete(b.orphans, *orphanHash) // Remove the reference from the previous orphan index too. An indexing // for loop is intentionally used over a range here as range does not // reevaluate the slice on each iteration nor does it adjust the index // for the modified slice. prevHash := &orphan.block.MsgBlock().Header.PrevBlock orphans := b.prevOrphans[*prevHash] for i := 0; i < len(orphans); i++ { hash := orphans[i].block.Hash() if hash.IsEqual(orphanHash) { copy(orphans[i:], orphans[i+1:]) orphans[len(orphans)-1] = nil orphans = orphans[:len(orphans)-1] i-- } } b.prevOrphans[*prevHash] = orphans // Remove the map entry altogether if there are no longer any orphans // which depend on the parent hash. if len(b.prevOrphans[*prevHash]) == 0 { delete(b.prevOrphans, *prevHash) } }
go
func (b *BlockChain) removeOrphanBlock(orphan *orphanBlock) { // Protect concurrent access. b.orphanLock.Lock() defer b.orphanLock.Unlock() // Remove the orphan block from the orphan pool. orphanHash := orphan.block.Hash() delete(b.orphans, *orphanHash) // Remove the reference from the previous orphan index too. An indexing // for loop is intentionally used over a range here as range does not // reevaluate the slice on each iteration nor does it adjust the index // for the modified slice. prevHash := &orphan.block.MsgBlock().Header.PrevBlock orphans := b.prevOrphans[*prevHash] for i := 0; i < len(orphans); i++ { hash := orphans[i].block.Hash() if hash.IsEqual(orphanHash) { copy(orphans[i:], orphans[i+1:]) orphans[len(orphans)-1] = nil orphans = orphans[:len(orphans)-1] i-- } } b.prevOrphans[*prevHash] = orphans // Remove the map entry altogether if there are no longer any orphans // which depend on the parent hash. if len(b.prevOrphans[*prevHash]) == 0 { delete(b.prevOrphans, *prevHash) } }
[ "func", "(", "b", "*", "BlockChain", ")", "removeOrphanBlock", "(", "orphan", "*", "orphanBlock", ")", "{", "// Protect concurrent access.", "b", ".", "orphanLock", ".", "Lock", "(", ")", "\n", "defer", "b", ".", "orphanLock", ".", "Unlock", "(", ")", "\n\n", "// Remove the orphan block from the orphan pool.", "orphanHash", ":=", "orphan", ".", "block", ".", "Hash", "(", ")", "\n", "delete", "(", "b", ".", "orphans", ",", "*", "orphanHash", ")", "\n\n", "// Remove the reference from the previous orphan index too. An indexing", "// for loop is intentionally used over a range here as range does not", "// reevaluate the slice on each iteration nor does it adjust the index", "// for the modified slice.", "prevHash", ":=", "&", "orphan", ".", "block", ".", "MsgBlock", "(", ")", ".", "Header", ".", "PrevBlock", "\n", "orphans", ":=", "b", ".", "prevOrphans", "[", "*", "prevHash", "]", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "orphans", ")", ";", "i", "++", "{", "hash", ":=", "orphans", "[", "i", "]", ".", "block", ".", "Hash", "(", ")", "\n", "if", "hash", ".", "IsEqual", "(", "orphanHash", ")", "{", "copy", "(", "orphans", "[", "i", ":", "]", ",", "orphans", "[", "i", "+", "1", ":", "]", ")", "\n", "orphans", "[", "len", "(", "orphans", ")", "-", "1", "]", "=", "nil", "\n", "orphans", "=", "orphans", "[", ":", "len", "(", "orphans", ")", "-", "1", "]", "\n", "i", "--", "\n", "}", "\n", "}", "\n", "b", ".", "prevOrphans", "[", "*", "prevHash", "]", "=", "orphans", "\n\n", "// Remove the map entry altogether if there are no longer any orphans", "// which depend on the parent hash.", "if", "len", "(", "b", ".", "prevOrphans", "[", "*", "prevHash", "]", ")", "==", "0", "{", "delete", "(", "b", ".", "prevOrphans", ",", "*", "prevHash", ")", "\n", "}", "\n", "}" ]
// removeOrphanBlock removes the passed orphan block from the orphan pool and // previous orphan index.
[ "removeOrphanBlock", "removes", "the", "passed", "orphan", "block", "from", "the", "orphan", "pool", "and", "previous", "orphan", "index", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/chain.go#L250-L281
train
btcsuite/btcd
blockchain/chain.go
CalcSequenceLock
func (b *BlockChain) CalcSequenceLock(tx *btcutil.Tx, utxoView *UtxoViewpoint, mempool bool) (*SequenceLock, error) { b.chainLock.Lock() defer b.chainLock.Unlock() return b.calcSequenceLock(b.bestChain.Tip(), tx, utxoView, mempool) }
go
func (b *BlockChain) CalcSequenceLock(tx *btcutil.Tx, utxoView *UtxoViewpoint, mempool bool) (*SequenceLock, error) { b.chainLock.Lock() defer b.chainLock.Unlock() return b.calcSequenceLock(b.bestChain.Tip(), tx, utxoView, mempool) }
[ "func", "(", "b", "*", "BlockChain", ")", "CalcSequenceLock", "(", "tx", "*", "btcutil", ".", "Tx", ",", "utxoView", "*", "UtxoViewpoint", ",", "mempool", "bool", ")", "(", "*", "SequenceLock", ",", "error", ")", "{", "b", ".", "chainLock", ".", "Lock", "(", ")", "\n", "defer", "b", ".", "chainLock", ".", "Unlock", "(", ")", "\n\n", "return", "b", ".", "calcSequenceLock", "(", "b", ".", "bestChain", ".", "Tip", "(", ")", ",", "tx", ",", "utxoView", ",", "mempool", ")", "\n", "}" ]
// CalcSequenceLock computes a relative lock-time SequenceLock for the passed // transaction using the passed UtxoViewpoint to obtain the past median time // for blocks in which the referenced inputs of the transactions were included // within. The generated SequenceLock lock can be used in conjunction with a // block height, and adjusted median block time to determine if all the inputs // referenced within a transaction have reached sufficient maturity allowing // the candidate transaction to be included in a block. // // This function is safe for concurrent access.
[ "CalcSequenceLock", "computes", "a", "relative", "lock", "-", "time", "SequenceLock", "for", "the", "passed", "transaction", "using", "the", "passed", "UtxoViewpoint", "to", "obtain", "the", "past", "median", "time", "for", "blocks", "in", "which", "the", "referenced", "inputs", "of", "the", "transactions", "were", "included", "within", ".", "The", "generated", "SequenceLock", "lock", "can", "be", "used", "in", "conjunction", "with", "a", "block", "height", "and", "adjusted", "median", "block", "time", "to", "determine", "if", "all", "the", "inputs", "referenced", "within", "a", "transaction", "have", "reached", "sufficient", "maturity", "allowing", "the", "candidate", "transaction", "to", "be", "included", "in", "a", "block", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/chain.go#L351-L356
train
btcsuite/btcd
blockchain/chain.go
countSpentOutputs
func countSpentOutputs(block *btcutil.Block) int { // Exclude the coinbase transaction since it can't spend anything. var numSpent int for _, tx := range block.Transactions()[1:] { numSpent += len(tx.MsgTx().TxIn) } return numSpent }
go
func countSpentOutputs(block *btcutil.Block) int { // Exclude the coinbase transaction since it can't spend anything. var numSpent int for _, tx := range block.Transactions()[1:] { numSpent += len(tx.MsgTx().TxIn) } return numSpent }
[ "func", "countSpentOutputs", "(", "block", "*", "btcutil", ".", "Block", ")", "int", "{", "// Exclude the coinbase transaction since it can't spend anything.", "var", "numSpent", "int", "\n", "for", "_", ",", "tx", ":=", "range", "block", ".", "Transactions", "(", ")", "[", "1", ":", "]", "{", "numSpent", "+=", "len", "(", "tx", ".", "MsgTx", "(", ")", ".", "TxIn", ")", "\n", "}", "\n", "return", "numSpent", "\n", "}" ]
// countSpentOutputs returns the number of utxos the passed block spends.
[ "countSpentOutputs", "returns", "the", "number", "of", "utxos", "the", "passed", "block", "spends", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/chain.go#L802-L809
train
btcsuite/btcd
blockchain/chain.go
BestSnapshot
func (b *BlockChain) BestSnapshot() *BestState { b.stateLock.RLock() snapshot := b.stateSnapshot b.stateLock.RUnlock() return snapshot }
go
func (b *BlockChain) BestSnapshot() *BestState { b.stateLock.RLock() snapshot := b.stateSnapshot b.stateLock.RUnlock() return snapshot }
[ "func", "(", "b", "*", "BlockChain", ")", "BestSnapshot", "(", ")", "*", "BestState", "{", "b", ".", "stateLock", ".", "RLock", "(", ")", "\n", "snapshot", ":=", "b", ".", "stateSnapshot", "\n", "b", ".", "stateLock", ".", "RUnlock", "(", ")", "\n", "return", "snapshot", "\n", "}" ]
// BestSnapshot returns information about the current best chain block and // related state as of the current point in time. The returned instance must be // treated as immutable since it is shared by all callers. // // This function is safe for concurrent access.
[ "BestSnapshot", "returns", "information", "about", "the", "current", "best", "chain", "block", "and", "related", "state", "as", "of", "the", "current", "point", "in", "time", ".", "The", "returned", "instance", "must", "be", "treated", "as", "immutable", "since", "it", "is", "shared", "by", "all", "callers", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/chain.go#L1261-L1266
train
btcsuite/btcd
blockchain/chain.go
HeaderByHash
func (b *BlockChain) HeaderByHash(hash *chainhash.Hash) (wire.BlockHeader, error) { node := b.index.LookupNode(hash) if node == nil { err := fmt.Errorf("block %s is not known", hash) return wire.BlockHeader{}, err } return node.Header(), nil }
go
func (b *BlockChain) HeaderByHash(hash *chainhash.Hash) (wire.BlockHeader, error) { node := b.index.LookupNode(hash) if node == nil { err := fmt.Errorf("block %s is not known", hash) return wire.BlockHeader{}, err } return node.Header(), nil }
[ "func", "(", "b", "*", "BlockChain", ")", "HeaderByHash", "(", "hash", "*", "chainhash", ".", "Hash", ")", "(", "wire", ".", "BlockHeader", ",", "error", ")", "{", "node", ":=", "b", ".", "index", ".", "LookupNode", "(", "hash", ")", "\n", "if", "node", "==", "nil", "{", "err", ":=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hash", ")", "\n", "return", "wire", ".", "BlockHeader", "{", "}", ",", "err", "\n", "}", "\n\n", "return", "node", ".", "Header", "(", ")", ",", "nil", "\n", "}" ]
// HeaderByHash returns the block header identified by the given hash or an // error if it doesn't exist. Note that this will return headers from both the // main and side chains.
[ "HeaderByHash", "returns", "the", "block", "header", "identified", "by", "the", "given", "hash", "or", "an", "error", "if", "it", "doesn", "t", "exist", ".", "Note", "that", "this", "will", "return", "headers", "from", "both", "the", "main", "and", "side", "chains", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/chain.go#L1271-L1279
train
btcsuite/btcd
blockchain/chain.go
MainChainHasBlock
func (b *BlockChain) MainChainHasBlock(hash *chainhash.Hash) bool { node := b.index.LookupNode(hash) return node != nil && b.bestChain.Contains(node) }
go
func (b *BlockChain) MainChainHasBlock(hash *chainhash.Hash) bool { node := b.index.LookupNode(hash) return node != nil && b.bestChain.Contains(node) }
[ "func", "(", "b", "*", "BlockChain", ")", "MainChainHasBlock", "(", "hash", "*", "chainhash", ".", "Hash", ")", "bool", "{", "node", ":=", "b", ".", "index", ".", "LookupNode", "(", "hash", ")", "\n", "return", "node", "!=", "nil", "&&", "b", ".", "bestChain", ".", "Contains", "(", "node", ")", "\n", "}" ]
// MainChainHasBlock returns whether or not the block with the given hash is in // the main chain. // // This function is safe for concurrent access.
[ "MainChainHasBlock", "returns", "whether", "or", "not", "the", "block", "with", "the", "given", "hash", "is", "in", "the", "main", "chain", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/chain.go#L1285-L1288
train
btcsuite/btcd
blockchain/chain.go
BlockHeightByHash
func (b *BlockChain) BlockHeightByHash(hash *chainhash.Hash) (int32, error) { node := b.index.LookupNode(hash) if node == nil || !b.bestChain.Contains(node) { str := fmt.Sprintf("block %s is not in the main chain", hash) return 0, errNotInMainChain(str) } return node.height, nil }
go
func (b *BlockChain) BlockHeightByHash(hash *chainhash.Hash) (int32, error) { node := b.index.LookupNode(hash) if node == nil || !b.bestChain.Contains(node) { str := fmt.Sprintf("block %s is not in the main chain", hash) return 0, errNotInMainChain(str) } return node.height, nil }
[ "func", "(", "b", "*", "BlockChain", ")", "BlockHeightByHash", "(", "hash", "*", "chainhash", ".", "Hash", ")", "(", "int32", ",", "error", ")", "{", "node", ":=", "b", ".", "index", ".", "LookupNode", "(", "hash", ")", "\n", "if", "node", "==", "nil", "||", "!", "b", ".", "bestChain", ".", "Contains", "(", "node", ")", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "hash", ")", "\n", "return", "0", ",", "errNotInMainChain", "(", "str", ")", "\n", "}", "\n\n", "return", "node", ".", "height", ",", "nil", "\n", "}" ]
// BlockHeightByHash returns the height of the block with the given hash in the // main chain. // // This function is safe for concurrent access.
[ "BlockHeightByHash", "returns", "the", "height", "of", "the", "block", "with", "the", "given", "hash", "in", "the", "main", "chain", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/chain.go#L1321-L1329
train
btcsuite/btcd
blockchain/chain.go
BlockHashByHeight
func (b *BlockChain) BlockHashByHeight(blockHeight int32) (*chainhash.Hash, error) { node := b.bestChain.NodeByHeight(blockHeight) if node == nil { str := fmt.Sprintf("no block at height %d exists", blockHeight) return nil, errNotInMainChain(str) } return &node.hash, nil }
go
func (b *BlockChain) BlockHashByHeight(blockHeight int32) (*chainhash.Hash, error) { node := b.bestChain.NodeByHeight(blockHeight) if node == nil { str := fmt.Sprintf("no block at height %d exists", blockHeight) return nil, errNotInMainChain(str) } return &node.hash, nil }
[ "func", "(", "b", "*", "BlockChain", ")", "BlockHashByHeight", "(", "blockHeight", "int32", ")", "(", "*", "chainhash", ".", "Hash", ",", "error", ")", "{", "node", ":=", "b", ".", "bestChain", ".", "NodeByHeight", "(", "blockHeight", ")", "\n", "if", "node", "==", "nil", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "blockHeight", ")", "\n", "return", "nil", ",", "errNotInMainChain", "(", "str", ")", "\n\n", "}", "\n\n", "return", "&", "node", ".", "hash", ",", "nil", "\n", "}" ]
// BlockHashByHeight returns the hash of the block at the given height in the // main chain. // // This function is safe for concurrent access.
[ "BlockHashByHeight", "returns", "the", "hash", "of", "the", "block", "at", "the", "given", "height", "in", "the", "main", "chain", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/chain.go#L1335-L1344
train
btcsuite/btcd
blockchain/chain.go
HeightRange
func (b *BlockChain) HeightRange(startHeight, endHeight int32) ([]chainhash.Hash, error) { // Ensure requested heights are sane. if startHeight < 0 { return nil, fmt.Errorf("start height of fetch range must not "+ "be less than zero - got %d", startHeight) } if endHeight < startHeight { return nil, fmt.Errorf("end height of fetch range must not "+ "be less than the start height - got start %d, end %d", startHeight, endHeight) } // There is nothing to do when the start and end heights are the same, // so return now to avoid the chain view lock. if startHeight == endHeight { return nil, nil } // Grab a lock on the chain view to prevent it from changing due to a // reorg while building the hashes. b.bestChain.mtx.Lock() defer b.bestChain.mtx.Unlock() // When the requested start height is after the most recent best chain // height, there is nothing to do. latestHeight := b.bestChain.tip().height if startHeight > latestHeight { return nil, nil } // Limit the ending height to the latest height of the chain. if endHeight > latestHeight+1 { endHeight = latestHeight + 1 } // Fetch as many as are available within the specified range. hashes := make([]chainhash.Hash, 0, endHeight-startHeight) for i := startHeight; i < endHeight; i++ { hashes = append(hashes, b.bestChain.nodeByHeight(i).hash) } return hashes, nil }
go
func (b *BlockChain) HeightRange(startHeight, endHeight int32) ([]chainhash.Hash, error) { // Ensure requested heights are sane. if startHeight < 0 { return nil, fmt.Errorf("start height of fetch range must not "+ "be less than zero - got %d", startHeight) } if endHeight < startHeight { return nil, fmt.Errorf("end height of fetch range must not "+ "be less than the start height - got start %d, end %d", startHeight, endHeight) } // There is nothing to do when the start and end heights are the same, // so return now to avoid the chain view lock. if startHeight == endHeight { return nil, nil } // Grab a lock on the chain view to prevent it from changing due to a // reorg while building the hashes. b.bestChain.mtx.Lock() defer b.bestChain.mtx.Unlock() // When the requested start height is after the most recent best chain // height, there is nothing to do. latestHeight := b.bestChain.tip().height if startHeight > latestHeight { return nil, nil } // Limit the ending height to the latest height of the chain. if endHeight > latestHeight+1 { endHeight = latestHeight + 1 } // Fetch as many as are available within the specified range. hashes := make([]chainhash.Hash, 0, endHeight-startHeight) for i := startHeight; i < endHeight; i++ { hashes = append(hashes, b.bestChain.nodeByHeight(i).hash) } return hashes, nil }
[ "func", "(", "b", "*", "BlockChain", ")", "HeightRange", "(", "startHeight", ",", "endHeight", "int32", ")", "(", "[", "]", "chainhash", ".", "Hash", ",", "error", ")", "{", "// Ensure requested heights are sane.", "if", "startHeight", "<", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "startHeight", ")", "\n", "}", "\n", "if", "endHeight", "<", "startHeight", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "startHeight", ",", "endHeight", ")", "\n", "}", "\n\n", "// There is nothing to do when the start and end heights are the same,", "// so return now to avoid the chain view lock.", "if", "startHeight", "==", "endHeight", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "// Grab a lock on the chain view to prevent it from changing due to a", "// reorg while building the hashes.", "b", ".", "bestChain", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "b", ".", "bestChain", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "// When the requested start height is after the most recent best chain", "// height, there is nothing to do.", "latestHeight", ":=", "b", ".", "bestChain", ".", "tip", "(", ")", ".", "height", "\n", "if", "startHeight", ">", "latestHeight", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "// Limit the ending height to the latest height of the chain.", "if", "endHeight", ">", "latestHeight", "+", "1", "{", "endHeight", "=", "latestHeight", "+", "1", "\n", "}", "\n\n", "// Fetch as many as are available within the specified range.", "hashes", ":=", "make", "(", "[", "]", "chainhash", ".", "Hash", ",", "0", ",", "endHeight", "-", "startHeight", ")", "\n", "for", "i", ":=", "startHeight", ";", "i", "<", "endHeight", ";", "i", "++", "{", "hashes", "=", "append", "(", "hashes", ",", "b", ".", "bestChain", ".", "nodeByHeight", "(", "i", ")", ".", "hash", ")", "\n", "}", "\n", "return", "hashes", ",", "nil", "\n", "}" ]
// HeightRange returns a range of block hashes for the given start and end // heights. It is inclusive of the start height and exclusive of the end // height. The end height will be limited to the current main chain height. // // This function is safe for concurrent access.
[ "HeightRange", "returns", "a", "range", "of", "block", "hashes", "for", "the", "given", "start", "and", "end", "heights", ".", "It", "is", "inclusive", "of", "the", "start", "height", "and", "exclusive", "of", "the", "end", "height", ".", "The", "end", "height", "will", "be", "limited", "to", "the", "current", "main", "chain", "height", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/chain.go#L1351-L1392
train
btcsuite/btcd
blockchain/chain.go
HeightToHashRange
func (b *BlockChain) HeightToHashRange(startHeight int32, endHash *chainhash.Hash, maxResults int) ([]chainhash.Hash, error) { endNode := b.index.LookupNode(endHash) if endNode == nil { return nil, fmt.Errorf("no known block header with hash %v", endHash) } if !b.index.NodeStatus(endNode).KnownValid() { return nil, fmt.Errorf("block %v is not yet validated", endHash) } endHeight := endNode.height if startHeight < 0 { return nil, fmt.Errorf("start height (%d) is below 0", startHeight) } if startHeight > endHeight { return nil, fmt.Errorf("start height (%d) is past end height (%d)", startHeight, endHeight) } resultsLength := int(endHeight - startHeight + 1) if resultsLength > maxResults { return nil, fmt.Errorf("number of results (%d) would exceed max (%d)", resultsLength, maxResults) } // Walk backwards from endHeight to startHeight, collecting block hashes. node := endNode hashes := make([]chainhash.Hash, resultsLength) for i := resultsLength - 1; i >= 0; i-- { hashes[i] = node.hash node = node.parent } return hashes, nil }
go
func (b *BlockChain) HeightToHashRange(startHeight int32, endHash *chainhash.Hash, maxResults int) ([]chainhash.Hash, error) { endNode := b.index.LookupNode(endHash) if endNode == nil { return nil, fmt.Errorf("no known block header with hash %v", endHash) } if !b.index.NodeStatus(endNode).KnownValid() { return nil, fmt.Errorf("block %v is not yet validated", endHash) } endHeight := endNode.height if startHeight < 0 { return nil, fmt.Errorf("start height (%d) is below 0", startHeight) } if startHeight > endHeight { return nil, fmt.Errorf("start height (%d) is past end height (%d)", startHeight, endHeight) } resultsLength := int(endHeight - startHeight + 1) if resultsLength > maxResults { return nil, fmt.Errorf("number of results (%d) would exceed max (%d)", resultsLength, maxResults) } // Walk backwards from endHeight to startHeight, collecting block hashes. node := endNode hashes := make([]chainhash.Hash, resultsLength) for i := resultsLength - 1; i >= 0; i-- { hashes[i] = node.hash node = node.parent } return hashes, nil }
[ "func", "(", "b", "*", "BlockChain", ")", "HeightToHashRange", "(", "startHeight", "int32", ",", "endHash", "*", "chainhash", ".", "Hash", ",", "maxResults", "int", ")", "(", "[", "]", "chainhash", ".", "Hash", ",", "error", ")", "{", "endNode", ":=", "b", ".", "index", ".", "LookupNode", "(", "endHash", ")", "\n", "if", "endNode", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "endHash", ")", "\n", "}", "\n", "if", "!", "b", ".", "index", ".", "NodeStatus", "(", "endNode", ")", ".", "KnownValid", "(", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "endHash", ")", "\n", "}", "\n", "endHeight", ":=", "endNode", ".", "height", "\n\n", "if", "startHeight", "<", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "startHeight", ")", "\n", "}", "\n", "if", "startHeight", ">", "endHeight", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "startHeight", ",", "endHeight", ")", "\n", "}", "\n\n", "resultsLength", ":=", "int", "(", "endHeight", "-", "startHeight", "+", "1", ")", "\n", "if", "resultsLength", ">", "maxResults", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "resultsLength", ",", "maxResults", ")", "\n", "}", "\n\n", "// Walk backwards from endHeight to startHeight, collecting block hashes.", "node", ":=", "endNode", "\n", "hashes", ":=", "make", "(", "[", "]", "chainhash", ".", "Hash", ",", "resultsLength", ")", "\n", "for", "i", ":=", "resultsLength", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "hashes", "[", "i", "]", "=", "node", ".", "hash", "\n", "node", "=", "node", ".", "parent", "\n", "}", "\n", "return", "hashes", ",", "nil", "\n", "}" ]
// HeightToHashRange returns a range of block hashes for the given start height // and end hash, inclusive on both ends. The hashes are for all blocks that are // ancestors of endHash with height greater than or equal to startHeight. The // end hash must belong to a block that is known to be valid. // // This function is safe for concurrent access.
[ "HeightToHashRange", "returns", "a", "range", "of", "block", "hashes", "for", "the", "given", "start", "height", "and", "end", "hash", "inclusive", "on", "both", "ends", ".", "The", "hashes", "are", "for", "all", "blocks", "that", "are", "ancestors", "of", "endHash", "with", "height", "greater", "than", "or", "equal", "to", "startHeight", ".", "The", "end", "hash", "must", "belong", "to", "a", "block", "that", "is", "known", "to", "be", "valid", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/chain.go#L1400-L1434
train
btcsuite/btcd
blockchain/chain.go
IntervalBlockHashes
func (b *BlockChain) IntervalBlockHashes(endHash *chainhash.Hash, interval int, ) ([]chainhash.Hash, error) { endNode := b.index.LookupNode(endHash) if endNode == nil { return nil, fmt.Errorf("no known block header with hash %v", endHash) } if !b.index.NodeStatus(endNode).KnownValid() { return nil, fmt.Errorf("block %v is not yet validated", endHash) } endHeight := endNode.height resultsLength := int(endHeight) / interval hashes := make([]chainhash.Hash, resultsLength) b.bestChain.mtx.Lock() defer b.bestChain.mtx.Unlock() blockNode := endNode for index := int(endHeight) / interval; index > 0; index-- { // Use the bestChain chainView for faster lookups once lookup intersects // the best chain. blockHeight := int32(index * interval) if b.bestChain.contains(blockNode) { blockNode = b.bestChain.nodeByHeight(blockHeight) } else { blockNode = blockNode.Ancestor(blockHeight) } hashes[index-1] = blockNode.hash } return hashes, nil }
go
func (b *BlockChain) IntervalBlockHashes(endHash *chainhash.Hash, interval int, ) ([]chainhash.Hash, error) { endNode := b.index.LookupNode(endHash) if endNode == nil { return nil, fmt.Errorf("no known block header with hash %v", endHash) } if !b.index.NodeStatus(endNode).KnownValid() { return nil, fmt.Errorf("block %v is not yet validated", endHash) } endHeight := endNode.height resultsLength := int(endHeight) / interval hashes := make([]chainhash.Hash, resultsLength) b.bestChain.mtx.Lock() defer b.bestChain.mtx.Unlock() blockNode := endNode for index := int(endHeight) / interval; index > 0; index-- { // Use the bestChain chainView for faster lookups once lookup intersects // the best chain. blockHeight := int32(index * interval) if b.bestChain.contains(blockNode) { blockNode = b.bestChain.nodeByHeight(blockHeight) } else { blockNode = blockNode.Ancestor(blockHeight) } hashes[index-1] = blockNode.hash } return hashes, nil }
[ "func", "(", "b", "*", "BlockChain", ")", "IntervalBlockHashes", "(", "endHash", "*", "chainhash", ".", "Hash", ",", "interval", "int", ",", ")", "(", "[", "]", "chainhash", ".", "Hash", ",", "error", ")", "{", "endNode", ":=", "b", ".", "index", ".", "LookupNode", "(", "endHash", ")", "\n", "if", "endNode", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "endHash", ")", "\n", "}", "\n", "if", "!", "b", ".", "index", ".", "NodeStatus", "(", "endNode", ")", ".", "KnownValid", "(", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "endHash", ")", "\n", "}", "\n", "endHeight", ":=", "endNode", ".", "height", "\n\n", "resultsLength", ":=", "int", "(", "endHeight", ")", "/", "interval", "\n", "hashes", ":=", "make", "(", "[", "]", "chainhash", ".", "Hash", ",", "resultsLength", ")", "\n\n", "b", ".", "bestChain", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "b", ".", "bestChain", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "blockNode", ":=", "endNode", "\n", "for", "index", ":=", "int", "(", "endHeight", ")", "/", "interval", ";", "index", ">", "0", ";", "index", "--", "{", "// Use the bestChain chainView for faster lookups once lookup intersects", "// the best chain.", "blockHeight", ":=", "int32", "(", "index", "*", "interval", ")", "\n", "if", "b", ".", "bestChain", ".", "contains", "(", "blockNode", ")", "{", "blockNode", "=", "b", ".", "bestChain", ".", "nodeByHeight", "(", "blockHeight", ")", "\n", "}", "else", "{", "blockNode", "=", "blockNode", ".", "Ancestor", "(", "blockHeight", ")", "\n", "}", "\n\n", "hashes", "[", "index", "-", "1", "]", "=", "blockNode", ".", "hash", "\n", "}", "\n\n", "return", "hashes", ",", "nil", "\n", "}" ]
// IntervalBlockHashes returns hashes for all blocks that are ancestors of // endHash where the block height is a positive multiple of interval. // // This function is safe for concurrent access.
[ "IntervalBlockHashes", "returns", "hashes", "for", "all", "blocks", "that", "are", "ancestors", "of", "endHash", "where", "the", "block", "height", "is", "a", "positive", "multiple", "of", "interval", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/chain.go#L1440-L1473
train
btcsuite/btcd
blockchain/chain.go
New
func New(config *Config) (*BlockChain, error) { // Enforce required config fields. if config.DB == nil { return nil, AssertError("blockchain.New database is nil") } if config.ChainParams == nil { return nil, AssertError("blockchain.New chain parameters nil") } if config.TimeSource == nil { return nil, AssertError("blockchain.New timesource is nil") } // Generate a checkpoint by height map from the provided checkpoints // and assert the provided checkpoints are sorted by height as required. var checkpointsByHeight map[int32]*chaincfg.Checkpoint var prevCheckpointHeight int32 if len(config.Checkpoints) > 0 { checkpointsByHeight = make(map[int32]*chaincfg.Checkpoint) for i := range config.Checkpoints { checkpoint := &config.Checkpoints[i] if checkpoint.Height <= prevCheckpointHeight { return nil, AssertError("blockchain.New " + "checkpoints are not sorted by height") } checkpointsByHeight[checkpoint.Height] = checkpoint prevCheckpointHeight = checkpoint.Height } } params := config.ChainParams targetTimespan := int64(params.TargetTimespan / time.Second) targetTimePerBlock := int64(params.TargetTimePerBlock / time.Second) adjustmentFactor := params.RetargetAdjustmentFactor b := BlockChain{ checkpoints: config.Checkpoints, checkpointsByHeight: checkpointsByHeight, db: config.DB, chainParams: params, timeSource: config.TimeSource, sigCache: config.SigCache, indexManager: config.IndexManager, minRetargetTimespan: targetTimespan / adjustmentFactor, maxRetargetTimespan: targetTimespan * adjustmentFactor, blocksPerRetarget: int32(targetTimespan / targetTimePerBlock), index: newBlockIndex(config.DB, params), hashCache: config.HashCache, bestChain: newChainView(nil), orphans: make(map[chainhash.Hash]*orphanBlock), prevOrphans: make(map[chainhash.Hash][]*orphanBlock), warningCaches: newThresholdCaches(vbNumBits), deploymentCaches: newThresholdCaches(chaincfg.DefinedDeployments), } // Initialize the chain state from the passed database. When the db // does not yet contain any chain state, both it and the chain state // will be initialized to contain only the genesis block. if err := b.initChainState(); err != nil { return nil, err } // Perform any upgrades to the various chain-specific buckets as needed. if err := b.maybeUpgradeDbBuckets(config.Interrupt); err != nil { return nil, err } // Initialize and catch up all of the currently active optional indexes // as needed. if config.IndexManager != nil { err := config.IndexManager.Init(&b, config.Interrupt) if err != nil { return nil, err } } // Initialize rule change threshold state caches. if err := b.initThresholdCaches(); err != nil { return nil, err } bestNode := b.bestChain.Tip() log.Infof("Chain state (height %d, hash %v, totaltx %d, work %v)", bestNode.height, bestNode.hash, b.stateSnapshot.TotalTxns, bestNode.workSum) return &b, nil }
go
func New(config *Config) (*BlockChain, error) { // Enforce required config fields. if config.DB == nil { return nil, AssertError("blockchain.New database is nil") } if config.ChainParams == nil { return nil, AssertError("blockchain.New chain parameters nil") } if config.TimeSource == nil { return nil, AssertError("blockchain.New timesource is nil") } // Generate a checkpoint by height map from the provided checkpoints // and assert the provided checkpoints are sorted by height as required. var checkpointsByHeight map[int32]*chaincfg.Checkpoint var prevCheckpointHeight int32 if len(config.Checkpoints) > 0 { checkpointsByHeight = make(map[int32]*chaincfg.Checkpoint) for i := range config.Checkpoints { checkpoint := &config.Checkpoints[i] if checkpoint.Height <= prevCheckpointHeight { return nil, AssertError("blockchain.New " + "checkpoints are not sorted by height") } checkpointsByHeight[checkpoint.Height] = checkpoint prevCheckpointHeight = checkpoint.Height } } params := config.ChainParams targetTimespan := int64(params.TargetTimespan / time.Second) targetTimePerBlock := int64(params.TargetTimePerBlock / time.Second) adjustmentFactor := params.RetargetAdjustmentFactor b := BlockChain{ checkpoints: config.Checkpoints, checkpointsByHeight: checkpointsByHeight, db: config.DB, chainParams: params, timeSource: config.TimeSource, sigCache: config.SigCache, indexManager: config.IndexManager, minRetargetTimespan: targetTimespan / adjustmentFactor, maxRetargetTimespan: targetTimespan * adjustmentFactor, blocksPerRetarget: int32(targetTimespan / targetTimePerBlock), index: newBlockIndex(config.DB, params), hashCache: config.HashCache, bestChain: newChainView(nil), orphans: make(map[chainhash.Hash]*orphanBlock), prevOrphans: make(map[chainhash.Hash][]*orphanBlock), warningCaches: newThresholdCaches(vbNumBits), deploymentCaches: newThresholdCaches(chaincfg.DefinedDeployments), } // Initialize the chain state from the passed database. When the db // does not yet contain any chain state, both it and the chain state // will be initialized to contain only the genesis block. if err := b.initChainState(); err != nil { return nil, err } // Perform any upgrades to the various chain-specific buckets as needed. if err := b.maybeUpgradeDbBuckets(config.Interrupt); err != nil { return nil, err } // Initialize and catch up all of the currently active optional indexes // as needed. if config.IndexManager != nil { err := config.IndexManager.Init(&b, config.Interrupt) if err != nil { return nil, err } } // Initialize rule change threshold state caches. if err := b.initThresholdCaches(); err != nil { return nil, err } bestNode := b.bestChain.Tip() log.Infof("Chain state (height %d, hash %v, totaltx %d, work %v)", bestNode.height, bestNode.hash, b.stateSnapshot.TotalTxns, bestNode.workSum) return &b, nil }
[ "func", "New", "(", "config", "*", "Config", ")", "(", "*", "BlockChain", ",", "error", ")", "{", "// Enforce required config fields.", "if", "config", ".", "DB", "==", "nil", "{", "return", "nil", ",", "AssertError", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "config", ".", "ChainParams", "==", "nil", "{", "return", "nil", ",", "AssertError", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "config", ".", "TimeSource", "==", "nil", "{", "return", "nil", ",", "AssertError", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Generate a checkpoint by height map from the provided checkpoints", "// and assert the provided checkpoints are sorted by height as required.", "var", "checkpointsByHeight", "map", "[", "int32", "]", "*", "chaincfg", ".", "Checkpoint", "\n", "var", "prevCheckpointHeight", "int32", "\n", "if", "len", "(", "config", ".", "Checkpoints", ")", ">", "0", "{", "checkpointsByHeight", "=", "make", "(", "map", "[", "int32", "]", "*", "chaincfg", ".", "Checkpoint", ")", "\n", "for", "i", ":=", "range", "config", ".", "Checkpoints", "{", "checkpoint", ":=", "&", "config", ".", "Checkpoints", "[", "i", "]", "\n", "if", "checkpoint", ".", "Height", "<=", "prevCheckpointHeight", "{", "return", "nil", ",", "AssertError", "(", "\"", "\"", "+", "\"", "\"", ")", "\n", "}", "\n\n", "checkpointsByHeight", "[", "checkpoint", ".", "Height", "]", "=", "checkpoint", "\n", "prevCheckpointHeight", "=", "checkpoint", ".", "Height", "\n", "}", "\n", "}", "\n\n", "params", ":=", "config", ".", "ChainParams", "\n", "targetTimespan", ":=", "int64", "(", "params", ".", "TargetTimespan", "/", "time", ".", "Second", ")", "\n", "targetTimePerBlock", ":=", "int64", "(", "params", ".", "TargetTimePerBlock", "/", "time", ".", "Second", ")", "\n", "adjustmentFactor", ":=", "params", ".", "RetargetAdjustmentFactor", "\n", "b", ":=", "BlockChain", "{", "checkpoints", ":", "config", ".", "Checkpoints", ",", "checkpointsByHeight", ":", "checkpointsByHeight", ",", "db", ":", "config", ".", "DB", ",", "chainParams", ":", "params", ",", "timeSource", ":", "config", ".", "TimeSource", ",", "sigCache", ":", "config", ".", "SigCache", ",", "indexManager", ":", "config", ".", "IndexManager", ",", "minRetargetTimespan", ":", "targetTimespan", "/", "adjustmentFactor", ",", "maxRetargetTimespan", ":", "targetTimespan", "*", "adjustmentFactor", ",", "blocksPerRetarget", ":", "int32", "(", "targetTimespan", "/", "targetTimePerBlock", ")", ",", "index", ":", "newBlockIndex", "(", "config", ".", "DB", ",", "params", ")", ",", "hashCache", ":", "config", ".", "HashCache", ",", "bestChain", ":", "newChainView", "(", "nil", ")", ",", "orphans", ":", "make", "(", "map", "[", "chainhash", ".", "Hash", "]", "*", "orphanBlock", ")", ",", "prevOrphans", ":", "make", "(", "map", "[", "chainhash", ".", "Hash", "]", "[", "]", "*", "orphanBlock", ")", ",", "warningCaches", ":", "newThresholdCaches", "(", "vbNumBits", ")", ",", "deploymentCaches", ":", "newThresholdCaches", "(", "chaincfg", ".", "DefinedDeployments", ")", ",", "}", "\n\n", "// Initialize the chain state from the passed database. When the db", "// does not yet contain any chain state, both it and the chain state", "// will be initialized to contain only the genesis block.", "if", "err", ":=", "b", ".", "initChainState", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Perform any upgrades to the various chain-specific buckets as needed.", "if", "err", ":=", "b", ".", "maybeUpgradeDbBuckets", "(", "config", ".", "Interrupt", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Initialize and catch up all of the currently active optional indexes", "// as needed.", "if", "config", ".", "IndexManager", "!=", "nil", "{", "err", ":=", "config", ".", "IndexManager", ".", "Init", "(", "&", "b", ",", "config", ".", "Interrupt", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "// Initialize rule change threshold state caches.", "if", "err", ":=", "b", ".", "initThresholdCaches", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "bestNode", ":=", "b", ".", "bestChain", ".", "Tip", "(", ")", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "bestNode", ".", "height", ",", "bestNode", ".", "hash", ",", "b", ".", "stateSnapshot", ".", "TotalTxns", ",", "bestNode", ".", "workSum", ")", "\n\n", "return", "&", "b", ",", "nil", "\n", "}" ]
// New returns a BlockChain instance using the provided configuration details.
[ "New", "returns", "a", "BlockChain", "instance", "using", "the", "provided", "configuration", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/chain.go#L1717-L1803
train
btcsuite/btcd
btcjson/btcwalletextcmds.go
NewImportAddressCmd
func NewImportAddressCmd(address string, account string, rescan *bool) *ImportAddressCmd { return &ImportAddressCmd{ Address: address, Account: account, Rescan: rescan, } }
go
func NewImportAddressCmd(address string, account string, rescan *bool) *ImportAddressCmd { return &ImportAddressCmd{ Address: address, Account: account, Rescan: rescan, } }
[ "func", "NewImportAddressCmd", "(", "address", "string", ",", "account", "string", ",", "rescan", "*", "bool", ")", "*", "ImportAddressCmd", "{", "return", "&", "ImportAddressCmd", "{", "Address", ":", "address", ",", "Account", ":", "account", ",", "Rescan", ":", "rescan", ",", "}", "\n", "}" ]
// NewImportAddressCmd returns a new instance which can be used to issue an // importaddress JSON-RPC command.
[ "NewImportAddressCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "an", "importaddress", "JSON", "-", "RPC", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/btcwalletextcmds.go#L45-L51
train
btcsuite/btcd
btcjson/btcwalletextcmds.go
NewImportPubKeyCmd
func NewImportPubKeyCmd(pubKey string, rescan *bool) *ImportPubKeyCmd { return &ImportPubKeyCmd{ PubKey: pubKey, Rescan: rescan, } }
go
func NewImportPubKeyCmd(pubKey string, rescan *bool) *ImportPubKeyCmd { return &ImportPubKeyCmd{ PubKey: pubKey, Rescan: rescan, } }
[ "func", "NewImportPubKeyCmd", "(", "pubKey", "string", ",", "rescan", "*", "bool", ")", "*", "ImportPubKeyCmd", "{", "return", "&", "ImportPubKeyCmd", "{", "PubKey", ":", "pubKey", ",", "Rescan", ":", "rescan", ",", "}", "\n", "}" ]
// NewImportPubKeyCmd returns a new instance which can be used to issue an // importpubkey JSON-RPC command.
[ "NewImportPubKeyCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "an", "importpubkey", "JSON", "-", "RPC", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/btcwalletextcmds.go#L61-L66
train
btcsuite/btcd
btcjson/btcwalletextcmds.go
NewRenameAccountCmd
func NewRenameAccountCmd(oldAccount, newAccount string) *RenameAccountCmd { return &RenameAccountCmd{ OldAccount: oldAccount, NewAccount: newAccount, } }
go
func NewRenameAccountCmd(oldAccount, newAccount string) *RenameAccountCmd { return &RenameAccountCmd{ OldAccount: oldAccount, NewAccount: newAccount, } }
[ "func", "NewRenameAccountCmd", "(", "oldAccount", ",", "newAccount", "string", ")", "*", "RenameAccountCmd", "{", "return", "&", "RenameAccountCmd", "{", "OldAccount", ":", "oldAccount", ",", "NewAccount", ":", "newAccount", ",", "}", "\n", "}" ]
// NewRenameAccountCmd returns a new instance which can be used to issue a // renameaccount JSON-RPC command.
[ "NewRenameAccountCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "renameaccount", "JSON", "-", "RPC", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/btcwalletextcmds.go#L89-L94
train
btcsuite/btcd
wire/msgcfilter.go
NewMsgCFilter
func NewMsgCFilter(filterType FilterType, blockHash *chainhash.Hash, data []byte) *MsgCFilter { return &MsgCFilter{ FilterType: filterType, BlockHash: *blockHash, Data: data, } }
go
func NewMsgCFilter(filterType FilterType, blockHash *chainhash.Hash, data []byte) *MsgCFilter { return &MsgCFilter{ FilterType: filterType, BlockHash: *blockHash, Data: data, } }
[ "func", "NewMsgCFilter", "(", "filterType", "FilterType", ",", "blockHash", "*", "chainhash", ".", "Hash", ",", "data", "[", "]", "byte", ")", "*", "MsgCFilter", "{", "return", "&", "MsgCFilter", "{", "FilterType", ":", "filterType", ",", "BlockHash", ":", "*", "blockHash", ",", "Data", ":", "data", ",", "}", "\n", "}" ]
// NewMsgCFilter returns a new bitcoin cfilter message that conforms to the // Message interface. See MsgCFilter for details.
[ "NewMsgCFilter", "returns", "a", "new", "bitcoin", "cfilter", "message", "that", "conforms", "to", "the", "Message", "interface", ".", "See", "MsgCFilter", "for", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgcfilter.go#L112-L119
train
btcsuite/btcd
peer/log.go
formatLockTime
func formatLockTime(lockTime uint32) string { // The lock time field of a transaction is either a block height at // which the transaction is finalized or a timestamp depending on if the // value is before the lockTimeThreshold. When it is under the // threshold it is a block height. if lockTime < txscript.LockTimeThreshold { return fmt.Sprintf("height %d", lockTime) } return time.Unix(int64(lockTime), 0).String() }
go
func formatLockTime(lockTime uint32) string { // The lock time field of a transaction is either a block height at // which the transaction is finalized or a timestamp depending on if the // value is before the lockTimeThreshold. When it is under the // threshold it is a block height. if lockTime < txscript.LockTimeThreshold { return fmt.Sprintf("height %d", lockTime) } return time.Unix(int64(lockTime), 0).String() }
[ "func", "formatLockTime", "(", "lockTime", "uint32", ")", "string", "{", "// The lock time field of a transaction is either a block height at", "// which the transaction is finalized or a timestamp depending on if the", "// value is before the lockTimeThreshold. When it is under the", "// threshold it is a block height.", "if", "lockTime", "<", "txscript", ".", "LockTimeThreshold", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "lockTime", ")", "\n", "}", "\n\n", "return", "time", ".", "Unix", "(", "int64", "(", "lockTime", ")", ",", "0", ")", ".", "String", "(", ")", "\n", "}" ]
// formatLockTime returns a transaction lock time as a human-readable string.
[ "formatLockTime", "returns", "a", "transaction", "lock", "time", "as", "a", "human", "-", "readable", "string", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/log.go#L68-L78
train
btcsuite/btcd
peer/log.go
invSummary
func invSummary(invList []*wire.InvVect) string { // No inventory. invLen := len(invList) if invLen == 0 { return "empty" } // One inventory item. if invLen == 1 { iv := invList[0] switch iv.Type { case wire.InvTypeError: return fmt.Sprintf("error %s", iv.Hash) case wire.InvTypeWitnessBlock: return fmt.Sprintf("witness block %s", iv.Hash) case wire.InvTypeBlock: return fmt.Sprintf("block %s", iv.Hash) case wire.InvTypeWitnessTx: return fmt.Sprintf("witness tx %s", iv.Hash) case wire.InvTypeTx: return fmt.Sprintf("tx %s", iv.Hash) } return fmt.Sprintf("unknown (%d) %s", uint32(iv.Type), iv.Hash) } // More than one inv item. return fmt.Sprintf("size %d", invLen) }
go
func invSummary(invList []*wire.InvVect) string { // No inventory. invLen := len(invList) if invLen == 0 { return "empty" } // One inventory item. if invLen == 1 { iv := invList[0] switch iv.Type { case wire.InvTypeError: return fmt.Sprintf("error %s", iv.Hash) case wire.InvTypeWitnessBlock: return fmt.Sprintf("witness block %s", iv.Hash) case wire.InvTypeBlock: return fmt.Sprintf("block %s", iv.Hash) case wire.InvTypeWitnessTx: return fmt.Sprintf("witness tx %s", iv.Hash) case wire.InvTypeTx: return fmt.Sprintf("tx %s", iv.Hash) } return fmt.Sprintf("unknown (%d) %s", uint32(iv.Type), iv.Hash) } // More than one inv item. return fmt.Sprintf("size %d", invLen) }
[ "func", "invSummary", "(", "invList", "[", "]", "*", "wire", ".", "InvVect", ")", "string", "{", "// No inventory.", "invLen", ":=", "len", "(", "invList", ")", "\n", "if", "invLen", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n\n", "// One inventory item.", "if", "invLen", "==", "1", "{", "iv", ":=", "invList", "[", "0", "]", "\n", "switch", "iv", ".", "Type", "{", "case", "wire", ".", "InvTypeError", ":", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "iv", ".", "Hash", ")", "\n", "case", "wire", ".", "InvTypeWitnessBlock", ":", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "iv", ".", "Hash", ")", "\n", "case", "wire", ".", "InvTypeBlock", ":", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "iv", ".", "Hash", ")", "\n", "case", "wire", ".", "InvTypeWitnessTx", ":", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "iv", ".", "Hash", ")", "\n", "case", "wire", ".", "InvTypeTx", ":", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "iv", ".", "Hash", ")", "\n", "}", "\n\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "uint32", "(", "iv", ".", "Type", ")", ",", "iv", ".", "Hash", ")", "\n", "}", "\n\n", "// More than one inv item.", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "invLen", ")", "\n", "}" ]
// invSummary returns an inventory message as a human-readable string.
[ "invSummary", "returns", "an", "inventory", "message", "as", "a", "human", "-", "readable", "string", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/log.go#L81-L109
train
btcsuite/btcd
peer/log.go
locatorSummary
func locatorSummary(locator []*chainhash.Hash, stopHash *chainhash.Hash) string { if len(locator) > 0 { return fmt.Sprintf("locator %s, stop %s", locator[0], stopHash) } return fmt.Sprintf("no locator, stop %s", stopHash) }
go
func locatorSummary(locator []*chainhash.Hash, stopHash *chainhash.Hash) string { if len(locator) > 0 { return fmt.Sprintf("locator %s, stop %s", locator[0], stopHash) } return fmt.Sprintf("no locator, stop %s", stopHash) }
[ "func", "locatorSummary", "(", "locator", "[", "]", "*", "chainhash", ".", "Hash", ",", "stopHash", "*", "chainhash", ".", "Hash", ")", "string", "{", "if", "len", "(", "locator", ")", ">", "0", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "locator", "[", "0", "]", ",", "stopHash", ")", "\n", "}", "\n\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "stopHash", ")", "\n\n", "}" ]
// locatorSummary returns a block locator as a human-readable string.
[ "locatorSummary", "returns", "a", "block", "locator", "as", "a", "human", "-", "readable", "string", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/log.go#L112-L119
train
btcsuite/btcd
peer/log.go
sanitizeString
func sanitizeString(str string, maxLength uint) string { const safeChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY" + "Z01234567890 .,;_/:?@" // Strip any characters not in the safeChars string removed. str = strings.Map(func(r rune) rune { if strings.ContainsRune(safeChars, r) { return r } return -1 }, str) // Limit the string to the max allowed length. if maxLength > 0 && uint(len(str)) > maxLength { str = str[:maxLength] str = str + "..." } return str }
go
func sanitizeString(str string, maxLength uint) string { const safeChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY" + "Z01234567890 .,;_/:?@" // Strip any characters not in the safeChars string removed. str = strings.Map(func(r rune) rune { if strings.ContainsRune(safeChars, r) { return r } return -1 }, str) // Limit the string to the max allowed length. if maxLength > 0 && uint(len(str)) > maxLength { str = str[:maxLength] str = str + "..." } return str }
[ "func", "sanitizeString", "(", "str", "string", ",", "maxLength", "uint", ")", "string", "{", "const", "safeChars", "=", "\"", "\"", "+", "\"", "\"", "\n\n", "// Strip any characters not in the safeChars string removed.", "str", "=", "strings", ".", "Map", "(", "func", "(", "r", "rune", ")", "rune", "{", "if", "strings", ".", "ContainsRune", "(", "safeChars", ",", "r", ")", "{", "return", "r", "\n", "}", "\n", "return", "-", "1", "\n", "}", ",", "str", ")", "\n\n", "// Limit the string to the max allowed length.", "if", "maxLength", ">", "0", "&&", "uint", "(", "len", "(", "str", ")", ")", ">", "maxLength", "{", "str", "=", "str", "[", ":", "maxLength", "]", "\n", "str", "=", "str", "+", "\"", "\"", "\n", "}", "\n", "return", "str", "\n", "}" ]
// sanitizeString strips any characters which are even remotely dangerous, such // as html control characters, from the passed string. It also limits it to // the passed maximum size, which can be 0 for unlimited. When the string is // limited, it will also add "..." to the string to indicate it was truncated.
[ "sanitizeString", "strips", "any", "characters", "which", "are", "even", "remotely", "dangerous", "such", "as", "html", "control", "characters", "from", "the", "passed", "string", ".", "It", "also", "limits", "it", "to", "the", "passed", "maximum", "size", "which", "can", "be", "0", "for", "unlimited", ".", "When", "the", "string", "is", "limited", "it", "will", "also", "add", "...", "to", "the", "string", "to", "indicate", "it", "was", "truncated", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/log.go#L125-L143
train
btcsuite/btcd
peer/log.go
messageSummary
func messageSummary(msg wire.Message) string { switch msg := msg.(type) { case *wire.MsgVersion: return fmt.Sprintf("agent %s, pver %d, block %d", msg.UserAgent, msg.ProtocolVersion, msg.LastBlock) case *wire.MsgVerAck: // No summary. case *wire.MsgGetAddr: // No summary. case *wire.MsgAddr: return fmt.Sprintf("%d addr", len(msg.AddrList)) case *wire.MsgPing: // No summary - perhaps add nonce. case *wire.MsgPong: // No summary - perhaps add nonce. case *wire.MsgAlert: // No summary. case *wire.MsgMemPool: // No summary. case *wire.MsgTx: return fmt.Sprintf("hash %s, %d inputs, %d outputs, lock %s", msg.TxHash(), len(msg.TxIn), len(msg.TxOut), formatLockTime(msg.LockTime)) case *wire.MsgBlock: header := &msg.Header return fmt.Sprintf("hash %s, ver %d, %d tx, %s", msg.BlockHash(), header.Version, len(msg.Transactions), header.Timestamp) case *wire.MsgInv: return invSummary(msg.InvList) case *wire.MsgNotFound: return invSummary(msg.InvList) case *wire.MsgGetData: return invSummary(msg.InvList) case *wire.MsgGetBlocks: return locatorSummary(msg.BlockLocatorHashes, &msg.HashStop) case *wire.MsgGetHeaders: return locatorSummary(msg.BlockLocatorHashes, &msg.HashStop) case *wire.MsgHeaders: return fmt.Sprintf("num %d", len(msg.Headers)) case *wire.MsgGetCFHeaders: return fmt.Sprintf("start_height=%d, stop_hash=%v", msg.StartHeight, msg.StopHash) case *wire.MsgCFHeaders: return fmt.Sprintf("stop_hash=%v, num_filter_hashes=%d", msg.StopHash, len(msg.FilterHashes)) case *wire.MsgReject: // Ensure the variable length strings don't contain any // characters which are even remotely dangerous such as HTML // control characters, etc. Also limit them to sane length for // logging. rejCommand := sanitizeString(msg.Cmd, wire.CommandSize) rejReason := sanitizeString(msg.Reason, maxRejectReasonLen) summary := fmt.Sprintf("cmd %v, code %v, reason %v", rejCommand, msg.Code, rejReason) if rejCommand == wire.CmdBlock || rejCommand == wire.CmdTx { summary += fmt.Sprintf(", hash %v", msg.Hash) } return summary } // No summary for other messages. return "" }
go
func messageSummary(msg wire.Message) string { switch msg := msg.(type) { case *wire.MsgVersion: return fmt.Sprintf("agent %s, pver %d, block %d", msg.UserAgent, msg.ProtocolVersion, msg.LastBlock) case *wire.MsgVerAck: // No summary. case *wire.MsgGetAddr: // No summary. case *wire.MsgAddr: return fmt.Sprintf("%d addr", len(msg.AddrList)) case *wire.MsgPing: // No summary - perhaps add nonce. case *wire.MsgPong: // No summary - perhaps add nonce. case *wire.MsgAlert: // No summary. case *wire.MsgMemPool: // No summary. case *wire.MsgTx: return fmt.Sprintf("hash %s, %d inputs, %d outputs, lock %s", msg.TxHash(), len(msg.TxIn), len(msg.TxOut), formatLockTime(msg.LockTime)) case *wire.MsgBlock: header := &msg.Header return fmt.Sprintf("hash %s, ver %d, %d tx, %s", msg.BlockHash(), header.Version, len(msg.Transactions), header.Timestamp) case *wire.MsgInv: return invSummary(msg.InvList) case *wire.MsgNotFound: return invSummary(msg.InvList) case *wire.MsgGetData: return invSummary(msg.InvList) case *wire.MsgGetBlocks: return locatorSummary(msg.BlockLocatorHashes, &msg.HashStop) case *wire.MsgGetHeaders: return locatorSummary(msg.BlockLocatorHashes, &msg.HashStop) case *wire.MsgHeaders: return fmt.Sprintf("num %d", len(msg.Headers)) case *wire.MsgGetCFHeaders: return fmt.Sprintf("start_height=%d, stop_hash=%v", msg.StartHeight, msg.StopHash) case *wire.MsgCFHeaders: return fmt.Sprintf("stop_hash=%v, num_filter_hashes=%d", msg.StopHash, len(msg.FilterHashes)) case *wire.MsgReject: // Ensure the variable length strings don't contain any // characters which are even remotely dangerous such as HTML // control characters, etc. Also limit them to sane length for // logging. rejCommand := sanitizeString(msg.Cmd, wire.CommandSize) rejReason := sanitizeString(msg.Reason, maxRejectReasonLen) summary := fmt.Sprintf("cmd %v, code %v, reason %v", rejCommand, msg.Code, rejReason) if rejCommand == wire.CmdBlock || rejCommand == wire.CmdTx { summary += fmt.Sprintf(", hash %v", msg.Hash) } return summary } // No summary for other messages. return "" }
[ "func", "messageSummary", "(", "msg", "wire", ".", "Message", ")", "string", "{", "switch", "msg", ":=", "msg", ".", "(", "type", ")", "{", "case", "*", "wire", ".", "MsgVersion", ":", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "msg", ".", "UserAgent", ",", "msg", ".", "ProtocolVersion", ",", "msg", ".", "LastBlock", ")", "\n\n", "case", "*", "wire", ".", "MsgVerAck", ":", "// No summary.", "case", "*", "wire", ".", "MsgGetAddr", ":", "// No summary.", "case", "*", "wire", ".", "MsgAddr", ":", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "len", "(", "msg", ".", "AddrList", ")", ")", "\n\n", "case", "*", "wire", ".", "MsgPing", ":", "// No summary - perhaps add nonce.", "case", "*", "wire", ".", "MsgPong", ":", "// No summary - perhaps add nonce.", "case", "*", "wire", ".", "MsgAlert", ":", "// No summary.", "case", "*", "wire", ".", "MsgMemPool", ":", "// No summary.", "case", "*", "wire", ".", "MsgTx", ":", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "msg", ".", "TxHash", "(", ")", ",", "len", "(", "msg", ".", "TxIn", ")", ",", "len", "(", "msg", ".", "TxOut", ")", ",", "formatLockTime", "(", "msg", ".", "LockTime", ")", ")", "\n\n", "case", "*", "wire", ".", "MsgBlock", ":", "header", ":=", "&", "msg", ".", "Header", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "msg", ".", "BlockHash", "(", ")", ",", "header", ".", "Version", ",", "len", "(", "msg", ".", "Transactions", ")", ",", "header", ".", "Timestamp", ")", "\n\n", "case", "*", "wire", ".", "MsgInv", ":", "return", "invSummary", "(", "msg", ".", "InvList", ")", "\n\n", "case", "*", "wire", ".", "MsgNotFound", ":", "return", "invSummary", "(", "msg", ".", "InvList", ")", "\n\n", "case", "*", "wire", ".", "MsgGetData", ":", "return", "invSummary", "(", "msg", ".", "InvList", ")", "\n\n", "case", "*", "wire", ".", "MsgGetBlocks", ":", "return", "locatorSummary", "(", "msg", ".", "BlockLocatorHashes", ",", "&", "msg", ".", "HashStop", ")", "\n\n", "case", "*", "wire", ".", "MsgGetHeaders", ":", "return", "locatorSummary", "(", "msg", ".", "BlockLocatorHashes", ",", "&", "msg", ".", "HashStop", ")", "\n\n", "case", "*", "wire", ".", "MsgHeaders", ":", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "len", "(", "msg", ".", "Headers", ")", ")", "\n\n", "case", "*", "wire", ".", "MsgGetCFHeaders", ":", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "msg", ".", "StartHeight", ",", "msg", ".", "StopHash", ")", "\n\n", "case", "*", "wire", ".", "MsgCFHeaders", ":", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "msg", ".", "StopHash", ",", "len", "(", "msg", ".", "FilterHashes", ")", ")", "\n\n", "case", "*", "wire", ".", "MsgReject", ":", "// Ensure the variable length strings don't contain any", "// characters which are even remotely dangerous such as HTML", "// control characters, etc. Also limit them to sane length for", "// logging.", "rejCommand", ":=", "sanitizeString", "(", "msg", ".", "Cmd", ",", "wire", ".", "CommandSize", ")", "\n", "rejReason", ":=", "sanitizeString", "(", "msg", ".", "Reason", ",", "maxRejectReasonLen", ")", "\n", "summary", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "rejCommand", ",", "msg", ".", "Code", ",", "rejReason", ")", "\n", "if", "rejCommand", "==", "wire", ".", "CmdBlock", "||", "rejCommand", "==", "wire", ".", "CmdTx", "{", "summary", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "msg", ".", "Hash", ")", "\n", "}", "\n", "return", "summary", "\n", "}", "\n\n", "// No summary for other messages.", "return", "\"", "\"", "\n", "}" ]
// messageSummary returns a human-readable string which summarizes a message. // Not all messages have or need a summary. This is used for debug logging.
[ "messageSummary", "returns", "a", "human", "-", "readable", "string", "which", "summarizes", "a", "message", ".", "Not", "all", "messages", "have", "or", "need", "a", "summary", ".", "This", "is", "used", "for", "debug", "logging", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/log.go#L147-L227
train
btcsuite/btcd
txscript/sigcache.go
NewSigCache
func NewSigCache(maxEntries uint) *SigCache { return &SigCache{ validSigs: make(map[chainhash.Hash]sigCacheEntry, maxEntries), maxEntries: maxEntries, } }
go
func NewSigCache(maxEntries uint) *SigCache { return &SigCache{ validSigs: make(map[chainhash.Hash]sigCacheEntry, maxEntries), maxEntries: maxEntries, } }
[ "func", "NewSigCache", "(", "maxEntries", "uint", ")", "*", "SigCache", "{", "return", "&", "SigCache", "{", "validSigs", ":", "make", "(", "map", "[", "chainhash", ".", "Hash", "]", "sigCacheEntry", ",", "maxEntries", ")", ",", "maxEntries", ":", "maxEntries", ",", "}", "\n", "}" ]
// NewSigCache creates and initializes a new instance of SigCache. Its sole // parameter 'maxEntries' represents the maximum number of entries allowed to // exist in the SigCache at any particular moment. Random entries are evicted // to make room for new entries that would cause the number of entries in the // cache to exceed the max.
[ "NewSigCache", "creates", "and", "initializes", "a", "new", "instance", "of", "SigCache", ".", "Its", "sole", "parameter", "maxEntries", "represents", "the", "maximum", "number", "of", "entries", "allowed", "to", "exist", "in", "the", "SigCache", "at", "any", "particular", "moment", ".", "Random", "entries", "are", "evicted", "to", "make", "room", "for", "new", "entries", "that", "would", "cause", "the", "number", "of", "entries", "in", "the", "cache", "to", "exceed", "the", "max", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/sigcache.go#L46-L51
train
btcsuite/btcd
wire/common.go
Borrow
func (l binaryFreeList) Borrow() []byte { var buf []byte select { case buf = <-l: default: buf = make([]byte, 8) } return buf[:8] }
go
func (l binaryFreeList) Borrow() []byte { var buf []byte select { case buf = <-l: default: buf = make([]byte, 8) } return buf[:8] }
[ "func", "(", "l", "binaryFreeList", ")", "Borrow", "(", ")", "[", "]", "byte", "{", "var", "buf", "[", "]", "byte", "\n", "select", "{", "case", "buf", "=", "<-", "l", ":", "default", ":", "buf", "=", "make", "(", "[", "]", "byte", ",", "8", ")", "\n", "}", "\n", "return", "buf", "[", ":", "8", "]", "\n", "}" ]
// Borrow returns a byte slice from the free list with a length of 8. A new // buffer is allocated if there are not any available on the free list.
[ "Borrow", "returns", "a", "byte", "slice", "from", "the", "free", "list", "with", "a", "length", "of", "8", ".", "A", "new", "buffer", "is", "allocated", "if", "there", "are", "not", "any", "available", "on", "the", "free", "list", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/common.go#L52-L60
train
btcsuite/btcd
wire/common.go
Uint8
func (l binaryFreeList) Uint8(r io.Reader) (uint8, error) { buf := l.Borrow()[:1] if _, err := io.ReadFull(r, buf); err != nil { l.Return(buf) return 0, err } rv := buf[0] l.Return(buf) return rv, nil }
go
func (l binaryFreeList) Uint8(r io.Reader) (uint8, error) { buf := l.Borrow()[:1] if _, err := io.ReadFull(r, buf); err != nil { l.Return(buf) return 0, err } rv := buf[0] l.Return(buf) return rv, nil }
[ "func", "(", "l", "binaryFreeList", ")", "Uint8", "(", "r", "io", ".", "Reader", ")", "(", "uint8", ",", "error", ")", "{", "buf", ":=", "l", ".", "Borrow", "(", ")", "[", ":", "1", "]", "\n", "if", "_", ",", "err", ":=", "io", ".", "ReadFull", "(", "r", ",", "buf", ")", ";", "err", "!=", "nil", "{", "l", ".", "Return", "(", "buf", ")", "\n", "return", "0", ",", "err", "\n", "}", "\n", "rv", ":=", "buf", "[", "0", "]", "\n", "l", ".", "Return", "(", "buf", ")", "\n", "return", "rv", ",", "nil", "\n", "}" ]
// Uint8 reads a single byte from the provided reader using a buffer from the // free list and returns it as a uint8.
[ "Uint8", "reads", "a", "single", "byte", "from", "the", "provided", "reader", "using", "a", "buffer", "from", "the", "free", "list", "and", "returns", "it", "as", "a", "uint8", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/common.go#L74-L83
train