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 | wire/common.go | Uint16 | func (l binaryFreeList) Uint16(r io.Reader, byteOrder binary.ByteOrder) (uint16, error) {
buf := l.Borrow()[:2]
if _, err := io.ReadFull(r, buf); err != nil {
l.Return(buf)
return 0, err
}
rv := byteOrder.Uint16(buf)
l.Return(buf)
return rv, nil
} | go | func (l binaryFreeList) Uint16(r io.Reader, byteOrder binary.ByteOrder) (uint16, error) {
buf := l.Borrow()[:2]
if _, err := io.ReadFull(r, buf); err != nil {
l.Return(buf)
return 0, err
}
rv := byteOrder.Uint16(buf)
l.Return(buf)
return rv, nil
} | [
"func",
"(",
"l",
"binaryFreeList",
")",
"Uint16",
"(",
"r",
"io",
".",
"Reader",
",",
"byteOrder",
"binary",
".",
"ByteOrder",
")",
"(",
"uint16",
",",
"error",
")",
"{",
"buf",
":=",
"l",
".",
"Borrow",
"(",
")",
"[",
":",
"2",
"]",
"\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"buf",
")",
";",
"err",
"!=",
"nil",
"{",
"l",
".",
"Return",
"(",
"buf",
")",
"\n",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"rv",
":=",
"byteOrder",
".",
"Uint16",
"(",
"buf",
")",
"\n",
"l",
".",
"Return",
"(",
"buf",
")",
"\n",
"return",
"rv",
",",
"nil",
"\n",
"}"
] | // Uint16 reads two bytes from the provided reader using a buffer from the
// free list, converts it to a number using the provided byte order, and returns
// the resulting uint16. | [
"Uint16",
"reads",
"two",
"bytes",
"from",
"the",
"provided",
"reader",
"using",
"a",
"buffer",
"from",
"the",
"free",
"list",
"converts",
"it",
"to",
"a",
"number",
"using",
"the",
"provided",
"byte",
"order",
"and",
"returns",
"the",
"resulting",
"uint16",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/common.go#L88-L97 | train |
btcsuite/btcd | wire/common.go | PutUint8 | func (l binaryFreeList) PutUint8(w io.Writer, val uint8) error {
buf := l.Borrow()[:1]
buf[0] = val
_, err := w.Write(buf)
l.Return(buf)
return err
} | go | func (l binaryFreeList) PutUint8(w io.Writer, val uint8) error {
buf := l.Borrow()[:1]
buf[0] = val
_, err := w.Write(buf)
l.Return(buf)
return err
} | [
"func",
"(",
"l",
"binaryFreeList",
")",
"PutUint8",
"(",
"w",
"io",
".",
"Writer",
",",
"val",
"uint8",
")",
"error",
"{",
"buf",
":=",
"l",
".",
"Borrow",
"(",
")",
"[",
":",
"1",
"]",
"\n",
"buf",
"[",
"0",
"]",
"=",
"val",
"\n",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"buf",
")",
"\n",
"l",
".",
"Return",
"(",
"buf",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // PutUint8 copies the provided uint8 into a buffer from the free list and
// writes the resulting byte to the given writer. | [
"PutUint8",
"copies",
"the",
"provided",
"uint8",
"into",
"a",
"buffer",
"from",
"the",
"free",
"list",
"and",
"writes",
"the",
"resulting",
"byte",
"to",
"the",
"given",
"writer",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/common.go#L129-L135 | train |
btcsuite/btcd | wire/common.go | PutUint16 | func (l binaryFreeList) PutUint16(w io.Writer, byteOrder binary.ByteOrder, val uint16) error {
buf := l.Borrow()[:2]
byteOrder.PutUint16(buf, val)
_, err := w.Write(buf)
l.Return(buf)
return err
} | go | func (l binaryFreeList) PutUint16(w io.Writer, byteOrder binary.ByteOrder, val uint16) error {
buf := l.Borrow()[:2]
byteOrder.PutUint16(buf, val)
_, err := w.Write(buf)
l.Return(buf)
return err
} | [
"func",
"(",
"l",
"binaryFreeList",
")",
"PutUint16",
"(",
"w",
"io",
".",
"Writer",
",",
"byteOrder",
"binary",
".",
"ByteOrder",
",",
"val",
"uint16",
")",
"error",
"{",
"buf",
":=",
"l",
".",
"Borrow",
"(",
")",
"[",
":",
"2",
"]",
"\n",
"byteOrder",
".",
"PutUint16",
"(",
"buf",
",",
"val",
")",
"\n",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"buf",
")",
"\n",
"l",
".",
"Return",
"(",
"buf",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // PutUint16 serializes the provided uint16 using the given byte order into a
// buffer from the free list and writes the resulting two bytes to the given
// writer. | [
"PutUint16",
"serializes",
"the",
"provided",
"uint16",
"using",
"the",
"given",
"byte",
"order",
"into",
"a",
"buffer",
"from",
"the",
"free",
"list",
"and",
"writes",
"the",
"resulting",
"two",
"bytes",
"to",
"the",
"given",
"writer",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/common.go#L140-L146 | train |
btcsuite/btcd | wire/common.go | readElements | func readElements(r io.Reader, elements ...interface{}) error {
for _, element := range elements {
err := readElement(r, element)
if err != nil {
return err
}
}
return nil
} | go | func readElements(r io.Reader, elements ...interface{}) error {
for _, element := range elements {
err := readElement(r, element)
if err != nil {
return err
}
}
return nil
} | [
"func",
"readElements",
"(",
"r",
"io",
".",
"Reader",
",",
"elements",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"for",
"_",
",",
"element",
":=",
"range",
"elements",
"{",
"err",
":=",
"readElement",
"(",
"r",
",",
"element",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // readElements reads multiple items from r. It is equivalent to multiple
// calls to readElement. | [
"readElements",
"reads",
"multiple",
"items",
"from",
"r",
".",
"It",
"is",
"equivalent",
"to",
"multiple",
"calls",
"to",
"readElement",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/common.go#L336-L344 | train |
btcsuite/btcd | wire/common.go | writeElement | func writeElement(w io.Writer, element interface{}) error {
// Attempt to write the element based on the concrete type via fast
// type assertions first.
switch e := element.(type) {
case int32:
err := binarySerializer.PutUint32(w, littleEndian, uint32(e))
if err != nil {
return err
}
return nil
case uint32:
err := binarySerializer.PutUint32(w, littleEndian, e)
if err != nil {
return err
}
return nil
case int64:
err := binarySerializer.PutUint64(w, littleEndian, uint64(e))
if err != nil {
return err
}
return nil
case uint64:
err := binarySerializer.PutUint64(w, littleEndian, e)
if err != nil {
return err
}
return nil
case bool:
var err error
if e {
err = binarySerializer.PutUint8(w, 0x01)
} else {
err = binarySerializer.PutUint8(w, 0x00)
}
if err != nil {
return err
}
return nil
// Message header checksum.
case [4]byte:
_, err := w.Write(e[:])
if err != nil {
return err
}
return nil
// Message header command.
case [CommandSize]uint8:
_, err := w.Write(e[:])
if err != nil {
return err
}
return nil
// IP address.
case [16]byte:
_, err := w.Write(e[:])
if err != nil {
return err
}
return nil
case *chainhash.Hash:
_, err := w.Write(e[:])
if err != nil {
return err
}
return nil
case ServiceFlag:
err := binarySerializer.PutUint64(w, littleEndian, uint64(e))
if err != nil {
return err
}
return nil
case InvType:
err := binarySerializer.PutUint32(w, littleEndian, uint32(e))
if err != nil {
return err
}
return nil
case BitcoinNet:
err := binarySerializer.PutUint32(w, littleEndian, uint32(e))
if err != nil {
return err
}
return nil
case BloomUpdateType:
err := binarySerializer.PutUint8(w, uint8(e))
if err != nil {
return err
}
return nil
case RejectCode:
err := binarySerializer.PutUint8(w, uint8(e))
if err != nil {
return err
}
return nil
}
// Fall back to the slower binary.Write if a fast path was not available
// above.
return binary.Write(w, littleEndian, element)
} | go | func writeElement(w io.Writer, element interface{}) error {
// Attempt to write the element based on the concrete type via fast
// type assertions first.
switch e := element.(type) {
case int32:
err := binarySerializer.PutUint32(w, littleEndian, uint32(e))
if err != nil {
return err
}
return nil
case uint32:
err := binarySerializer.PutUint32(w, littleEndian, e)
if err != nil {
return err
}
return nil
case int64:
err := binarySerializer.PutUint64(w, littleEndian, uint64(e))
if err != nil {
return err
}
return nil
case uint64:
err := binarySerializer.PutUint64(w, littleEndian, e)
if err != nil {
return err
}
return nil
case bool:
var err error
if e {
err = binarySerializer.PutUint8(w, 0x01)
} else {
err = binarySerializer.PutUint8(w, 0x00)
}
if err != nil {
return err
}
return nil
// Message header checksum.
case [4]byte:
_, err := w.Write(e[:])
if err != nil {
return err
}
return nil
// Message header command.
case [CommandSize]uint8:
_, err := w.Write(e[:])
if err != nil {
return err
}
return nil
// IP address.
case [16]byte:
_, err := w.Write(e[:])
if err != nil {
return err
}
return nil
case *chainhash.Hash:
_, err := w.Write(e[:])
if err != nil {
return err
}
return nil
case ServiceFlag:
err := binarySerializer.PutUint64(w, littleEndian, uint64(e))
if err != nil {
return err
}
return nil
case InvType:
err := binarySerializer.PutUint32(w, littleEndian, uint32(e))
if err != nil {
return err
}
return nil
case BitcoinNet:
err := binarySerializer.PutUint32(w, littleEndian, uint32(e))
if err != nil {
return err
}
return nil
case BloomUpdateType:
err := binarySerializer.PutUint8(w, uint8(e))
if err != nil {
return err
}
return nil
case RejectCode:
err := binarySerializer.PutUint8(w, uint8(e))
if err != nil {
return err
}
return nil
}
// Fall back to the slower binary.Write if a fast path was not available
// above.
return binary.Write(w, littleEndian, element)
} | [
"func",
"writeElement",
"(",
"w",
"io",
".",
"Writer",
",",
"element",
"interface",
"{",
"}",
")",
"error",
"{",
"// Attempt to write the element based on the concrete type via fast",
"// type assertions first.",
"switch",
"e",
":=",
"element",
".",
"(",
"type",
")",
"{",
"case",
"int32",
":",
"err",
":=",
"binarySerializer",
".",
"PutUint32",
"(",
"w",
",",
"littleEndian",
",",
"uint32",
"(",
"e",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n\n",
"case",
"uint32",
":",
"err",
":=",
"binarySerializer",
".",
"PutUint32",
"(",
"w",
",",
"littleEndian",
",",
"e",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n\n",
"case",
"int64",
":",
"err",
":=",
"binarySerializer",
".",
"PutUint64",
"(",
"w",
",",
"littleEndian",
",",
"uint64",
"(",
"e",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n\n",
"case",
"uint64",
":",
"err",
":=",
"binarySerializer",
".",
"PutUint64",
"(",
"w",
",",
"littleEndian",
",",
"e",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n\n",
"case",
"bool",
":",
"var",
"err",
"error",
"\n",
"if",
"e",
"{",
"err",
"=",
"binarySerializer",
".",
"PutUint8",
"(",
"w",
",",
"0x01",
")",
"\n",
"}",
"else",
"{",
"err",
"=",
"binarySerializer",
".",
"PutUint8",
"(",
"w",
",",
"0x00",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n\n",
"// Message header checksum.",
"case",
"[",
"4",
"]",
"byte",
":",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"e",
"[",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n\n",
"// Message header command.",
"case",
"[",
"CommandSize",
"]",
"uint8",
":",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"e",
"[",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n\n",
"// IP address.",
"case",
"[",
"16",
"]",
"byte",
":",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"e",
"[",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n\n",
"case",
"*",
"chainhash",
".",
"Hash",
":",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"e",
"[",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n\n",
"case",
"ServiceFlag",
":",
"err",
":=",
"binarySerializer",
".",
"PutUint64",
"(",
"w",
",",
"littleEndian",
",",
"uint64",
"(",
"e",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n\n",
"case",
"InvType",
":",
"err",
":=",
"binarySerializer",
".",
"PutUint32",
"(",
"w",
",",
"littleEndian",
",",
"uint32",
"(",
"e",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n\n",
"case",
"BitcoinNet",
":",
"err",
":=",
"binarySerializer",
".",
"PutUint32",
"(",
"w",
",",
"littleEndian",
",",
"uint32",
"(",
"e",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n\n",
"case",
"BloomUpdateType",
":",
"err",
":=",
"binarySerializer",
".",
"PutUint8",
"(",
"w",
",",
"uint8",
"(",
"e",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n\n",
"case",
"RejectCode",
":",
"err",
":=",
"binarySerializer",
".",
"PutUint8",
"(",
"w",
",",
"uint8",
"(",
"e",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Fall back to the slower binary.Write if a fast path was not available",
"// above.",
"return",
"binary",
".",
"Write",
"(",
"w",
",",
"littleEndian",
",",
"element",
")",
"\n",
"}"
] | // writeElement writes the little endian representation of element to w. | [
"writeElement",
"writes",
"the",
"little",
"endian",
"representation",
"of",
"element",
"to",
"w",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/common.go#L347-L461 | train |
btcsuite/btcd | wire/common.go | writeElements | func writeElements(w io.Writer, elements ...interface{}) error {
for _, element := range elements {
err := writeElement(w, element)
if err != nil {
return err
}
}
return nil
} | go | func writeElements(w io.Writer, elements ...interface{}) error {
for _, element := range elements {
err := writeElement(w, element)
if err != nil {
return err
}
}
return nil
} | [
"func",
"writeElements",
"(",
"w",
"io",
".",
"Writer",
",",
"elements",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"for",
"_",
",",
"element",
":=",
"range",
"elements",
"{",
"err",
":=",
"writeElement",
"(",
"w",
",",
"element",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // writeElements writes multiple items to w. It is equivalent to multiple
// calls to writeElement. | [
"writeElements",
"writes",
"multiple",
"items",
"to",
"w",
".",
"It",
"is",
"equivalent",
"to",
"multiple",
"calls",
"to",
"writeElement",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/common.go#L465-L473 | train |
btcsuite/btcd | wire/common.go | ReadVarInt | func ReadVarInt(r io.Reader, pver uint32) (uint64, error) {
discriminant, err := binarySerializer.Uint8(r)
if err != nil {
return 0, err
}
var rv uint64
switch discriminant {
case 0xff:
sv, err := binarySerializer.Uint64(r, littleEndian)
if err != nil {
return 0, err
}
rv = sv
// The encoding is not canonical if the value could have been
// encoded using fewer bytes.
min := uint64(0x100000000)
if rv < min {
return 0, messageError("ReadVarInt", fmt.Sprintf(
errNonCanonicalVarInt, rv, discriminant, min))
}
case 0xfe:
sv, err := binarySerializer.Uint32(r, littleEndian)
if err != nil {
return 0, err
}
rv = uint64(sv)
// The encoding is not canonical if the value could have been
// encoded using fewer bytes.
min := uint64(0x10000)
if rv < min {
return 0, messageError("ReadVarInt", fmt.Sprintf(
errNonCanonicalVarInt, rv, discriminant, min))
}
case 0xfd:
sv, err := binarySerializer.Uint16(r, littleEndian)
if err != nil {
return 0, err
}
rv = uint64(sv)
// The encoding is not canonical if the value could have been
// encoded using fewer bytes.
min := uint64(0xfd)
if rv < min {
return 0, messageError("ReadVarInt", fmt.Sprintf(
errNonCanonicalVarInt, rv, discriminant, min))
}
default:
rv = uint64(discriminant)
}
return rv, nil
} | go | func ReadVarInt(r io.Reader, pver uint32) (uint64, error) {
discriminant, err := binarySerializer.Uint8(r)
if err != nil {
return 0, err
}
var rv uint64
switch discriminant {
case 0xff:
sv, err := binarySerializer.Uint64(r, littleEndian)
if err != nil {
return 0, err
}
rv = sv
// The encoding is not canonical if the value could have been
// encoded using fewer bytes.
min := uint64(0x100000000)
if rv < min {
return 0, messageError("ReadVarInt", fmt.Sprintf(
errNonCanonicalVarInt, rv, discriminant, min))
}
case 0xfe:
sv, err := binarySerializer.Uint32(r, littleEndian)
if err != nil {
return 0, err
}
rv = uint64(sv)
// The encoding is not canonical if the value could have been
// encoded using fewer bytes.
min := uint64(0x10000)
if rv < min {
return 0, messageError("ReadVarInt", fmt.Sprintf(
errNonCanonicalVarInt, rv, discriminant, min))
}
case 0xfd:
sv, err := binarySerializer.Uint16(r, littleEndian)
if err != nil {
return 0, err
}
rv = uint64(sv)
// The encoding is not canonical if the value could have been
// encoded using fewer bytes.
min := uint64(0xfd)
if rv < min {
return 0, messageError("ReadVarInt", fmt.Sprintf(
errNonCanonicalVarInt, rv, discriminant, min))
}
default:
rv = uint64(discriminant)
}
return rv, nil
} | [
"func",
"ReadVarInt",
"(",
"r",
"io",
".",
"Reader",
",",
"pver",
"uint32",
")",
"(",
"uint64",
",",
"error",
")",
"{",
"discriminant",
",",
"err",
":=",
"binarySerializer",
".",
"Uint8",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"rv",
"uint64",
"\n",
"switch",
"discriminant",
"{",
"case",
"0xff",
":",
"sv",
",",
"err",
":=",
"binarySerializer",
".",
"Uint64",
"(",
"r",
",",
"littleEndian",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"rv",
"=",
"sv",
"\n\n",
"// The encoding is not canonical if the value could have been",
"// encoded using fewer bytes.",
"min",
":=",
"uint64",
"(",
"0x100000000",
")",
"\n",
"if",
"rv",
"<",
"min",
"{",
"return",
"0",
",",
"messageError",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"errNonCanonicalVarInt",
",",
"rv",
",",
"discriminant",
",",
"min",
")",
")",
"\n",
"}",
"\n\n",
"case",
"0xfe",
":",
"sv",
",",
"err",
":=",
"binarySerializer",
".",
"Uint32",
"(",
"r",
",",
"littleEndian",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"rv",
"=",
"uint64",
"(",
"sv",
")",
"\n\n",
"// The encoding is not canonical if the value could have been",
"// encoded using fewer bytes.",
"min",
":=",
"uint64",
"(",
"0x10000",
")",
"\n",
"if",
"rv",
"<",
"min",
"{",
"return",
"0",
",",
"messageError",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"errNonCanonicalVarInt",
",",
"rv",
",",
"discriminant",
",",
"min",
")",
")",
"\n",
"}",
"\n\n",
"case",
"0xfd",
":",
"sv",
",",
"err",
":=",
"binarySerializer",
".",
"Uint16",
"(",
"r",
",",
"littleEndian",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"rv",
"=",
"uint64",
"(",
"sv",
")",
"\n\n",
"// The encoding is not canonical if the value could have been",
"// encoded using fewer bytes.",
"min",
":=",
"uint64",
"(",
"0xfd",
")",
"\n",
"if",
"rv",
"<",
"min",
"{",
"return",
"0",
",",
"messageError",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"errNonCanonicalVarInt",
",",
"rv",
",",
"discriminant",
",",
"min",
")",
")",
"\n",
"}",
"\n\n",
"default",
":",
"rv",
"=",
"uint64",
"(",
"discriminant",
")",
"\n",
"}",
"\n\n",
"return",
"rv",
",",
"nil",
"\n",
"}"
] | // ReadVarInt reads a variable length integer from r and returns it as a uint64. | [
"ReadVarInt",
"reads",
"a",
"variable",
"length",
"integer",
"from",
"r",
"and",
"returns",
"it",
"as",
"a",
"uint64",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/common.go#L476-L534 | train |
btcsuite/btcd | wire/common.go | WriteVarInt | func WriteVarInt(w io.Writer, pver uint32, val uint64) error {
if val < 0xfd {
return binarySerializer.PutUint8(w, uint8(val))
}
if val <= math.MaxUint16 {
err := binarySerializer.PutUint8(w, 0xfd)
if err != nil {
return err
}
return binarySerializer.PutUint16(w, littleEndian, uint16(val))
}
if val <= math.MaxUint32 {
err := binarySerializer.PutUint8(w, 0xfe)
if err != nil {
return err
}
return binarySerializer.PutUint32(w, littleEndian, uint32(val))
}
err := binarySerializer.PutUint8(w, 0xff)
if err != nil {
return err
}
return binarySerializer.PutUint64(w, littleEndian, val)
} | go | func WriteVarInt(w io.Writer, pver uint32, val uint64) error {
if val < 0xfd {
return binarySerializer.PutUint8(w, uint8(val))
}
if val <= math.MaxUint16 {
err := binarySerializer.PutUint8(w, 0xfd)
if err != nil {
return err
}
return binarySerializer.PutUint16(w, littleEndian, uint16(val))
}
if val <= math.MaxUint32 {
err := binarySerializer.PutUint8(w, 0xfe)
if err != nil {
return err
}
return binarySerializer.PutUint32(w, littleEndian, uint32(val))
}
err := binarySerializer.PutUint8(w, 0xff)
if err != nil {
return err
}
return binarySerializer.PutUint64(w, littleEndian, val)
} | [
"func",
"WriteVarInt",
"(",
"w",
"io",
".",
"Writer",
",",
"pver",
"uint32",
",",
"val",
"uint64",
")",
"error",
"{",
"if",
"val",
"<",
"0xfd",
"{",
"return",
"binarySerializer",
".",
"PutUint8",
"(",
"w",
",",
"uint8",
"(",
"val",
")",
")",
"\n",
"}",
"\n\n",
"if",
"val",
"<=",
"math",
".",
"MaxUint16",
"{",
"err",
":=",
"binarySerializer",
".",
"PutUint8",
"(",
"w",
",",
"0xfd",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"binarySerializer",
".",
"PutUint16",
"(",
"w",
",",
"littleEndian",
",",
"uint16",
"(",
"val",
")",
")",
"\n",
"}",
"\n\n",
"if",
"val",
"<=",
"math",
".",
"MaxUint32",
"{",
"err",
":=",
"binarySerializer",
".",
"PutUint8",
"(",
"w",
",",
"0xfe",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"binarySerializer",
".",
"PutUint32",
"(",
"w",
",",
"littleEndian",
",",
"uint32",
"(",
"val",
")",
")",
"\n",
"}",
"\n\n",
"err",
":=",
"binarySerializer",
".",
"PutUint8",
"(",
"w",
",",
"0xff",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"binarySerializer",
".",
"PutUint64",
"(",
"w",
",",
"littleEndian",
",",
"val",
")",
"\n",
"}"
] | // WriteVarInt serializes val to w using a variable number of bytes depending
// on its value. | [
"WriteVarInt",
"serializes",
"val",
"to",
"w",
"using",
"a",
"variable",
"number",
"of",
"bytes",
"depending",
"on",
"its",
"value",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/common.go#L538-L564 | train |
btcsuite/btcd | wire/common.go | VarIntSerializeSize | func VarIntSerializeSize(val uint64) int {
// The value is small enough to be represented by itself, so it's
// just 1 byte.
if val < 0xfd {
return 1
}
// Discriminant 1 byte plus 2 bytes for the uint16.
if val <= math.MaxUint16 {
return 3
}
// Discriminant 1 byte plus 4 bytes for the uint32.
if val <= math.MaxUint32 {
return 5
}
// Discriminant 1 byte plus 8 bytes for the uint64.
return 9
} | go | func VarIntSerializeSize(val uint64) int {
// The value is small enough to be represented by itself, so it's
// just 1 byte.
if val < 0xfd {
return 1
}
// Discriminant 1 byte plus 2 bytes for the uint16.
if val <= math.MaxUint16 {
return 3
}
// Discriminant 1 byte plus 4 bytes for the uint32.
if val <= math.MaxUint32 {
return 5
}
// Discriminant 1 byte plus 8 bytes for the uint64.
return 9
} | [
"func",
"VarIntSerializeSize",
"(",
"val",
"uint64",
")",
"int",
"{",
"// The value is small enough to be represented by itself, so it's",
"// just 1 byte.",
"if",
"val",
"<",
"0xfd",
"{",
"return",
"1",
"\n",
"}",
"\n\n",
"// Discriminant 1 byte plus 2 bytes for the uint16.",
"if",
"val",
"<=",
"math",
".",
"MaxUint16",
"{",
"return",
"3",
"\n",
"}",
"\n\n",
"// Discriminant 1 byte plus 4 bytes for the uint32.",
"if",
"val",
"<=",
"math",
".",
"MaxUint32",
"{",
"return",
"5",
"\n",
"}",
"\n\n",
"// Discriminant 1 byte plus 8 bytes for the uint64.",
"return",
"9",
"\n",
"}"
] | // VarIntSerializeSize returns the number of bytes it would take to serialize
// val as a variable length integer. | [
"VarIntSerializeSize",
"returns",
"the",
"number",
"of",
"bytes",
"it",
"would",
"take",
"to",
"serialize",
"val",
"as",
"a",
"variable",
"length",
"integer",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/common.go#L568-L587 | train |
btcsuite/btcd | wire/common.go | ReadVarString | func ReadVarString(r io.Reader, pver uint32) (string, error) {
count, err := ReadVarInt(r, pver)
if err != nil {
return "", err
}
// Prevent variable length strings that are larger than the maximum
// message size. It would be possible to cause memory exhaustion and
// panics without a sane upper bound on this count.
if count > MaxMessagePayload {
str := fmt.Sprintf("variable length string is too long "+
"[count %d, max %d]", count, MaxMessagePayload)
return "", messageError("ReadVarString", str)
}
buf := make([]byte, count)
_, err = io.ReadFull(r, buf)
if err != nil {
return "", err
}
return string(buf), nil
} | go | func ReadVarString(r io.Reader, pver uint32) (string, error) {
count, err := ReadVarInt(r, pver)
if err != nil {
return "", err
}
// Prevent variable length strings that are larger than the maximum
// message size. It would be possible to cause memory exhaustion and
// panics without a sane upper bound on this count.
if count > MaxMessagePayload {
str := fmt.Sprintf("variable length string is too long "+
"[count %d, max %d]", count, MaxMessagePayload)
return "", messageError("ReadVarString", str)
}
buf := make([]byte, count)
_, err = io.ReadFull(r, buf)
if err != nil {
return "", err
}
return string(buf), nil
} | [
"func",
"ReadVarString",
"(",
"r",
"io",
".",
"Reader",
",",
"pver",
"uint32",
")",
"(",
"string",
",",
"error",
")",
"{",
"count",
",",
"err",
":=",
"ReadVarInt",
"(",
"r",
",",
"pver",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"// Prevent variable length strings that are larger than the maximum",
"// message size. It would be possible to cause memory exhaustion and",
"// panics without a sane upper bound on this count.",
"if",
"count",
">",
"MaxMessagePayload",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"count",
",",
"MaxMessagePayload",
")",
"\n",
"return",
"\"",
"\"",
",",
"messageError",
"(",
"\"",
"\"",
",",
"str",
")",
"\n",
"}",
"\n\n",
"buf",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"count",
")",
"\n",
"_",
",",
"err",
"=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"buf",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"string",
"(",
"buf",
")",
",",
"nil",
"\n",
"}"
] | // ReadVarString reads a variable length string from r and returns it as a Go
// string. A variable length string is encoded as a variable length integer
// containing the length of the string followed by the bytes that represent the
// string itself. An error is returned if the length is greater than the
// maximum block payload size since it helps protect against memory exhaustion
// attacks and forced panics through malformed messages. | [
"ReadVarString",
"reads",
"a",
"variable",
"length",
"string",
"from",
"r",
"and",
"returns",
"it",
"as",
"a",
"Go",
"string",
".",
"A",
"variable",
"length",
"string",
"is",
"encoded",
"as",
"a",
"variable",
"length",
"integer",
"containing",
"the",
"length",
"of",
"the",
"string",
"followed",
"by",
"the",
"bytes",
"that",
"represent",
"the",
"string",
"itself",
".",
"An",
"error",
"is",
"returned",
"if",
"the",
"length",
"is",
"greater",
"than",
"the",
"maximum",
"block",
"payload",
"size",
"since",
"it",
"helps",
"protect",
"against",
"memory",
"exhaustion",
"attacks",
"and",
"forced",
"panics",
"through",
"malformed",
"messages",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/common.go#L595-L616 | train |
btcsuite/btcd | wire/common.go | WriteVarString | func WriteVarString(w io.Writer, pver uint32, str string) error {
err := WriteVarInt(w, pver, uint64(len(str)))
if err != nil {
return err
}
_, err = w.Write([]byte(str))
return err
} | go | func WriteVarString(w io.Writer, pver uint32, str string) error {
err := WriteVarInt(w, pver, uint64(len(str)))
if err != nil {
return err
}
_, err = w.Write([]byte(str))
return err
} | [
"func",
"WriteVarString",
"(",
"w",
"io",
".",
"Writer",
",",
"pver",
"uint32",
",",
"str",
"string",
")",
"error",
"{",
"err",
":=",
"WriteVarInt",
"(",
"w",
",",
"pver",
",",
"uint64",
"(",
"len",
"(",
"str",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"str",
")",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // WriteVarString serializes str to w as a variable length integer containing
// the length of the string followed by the bytes that represent the string
// itself. | [
"WriteVarString",
"serializes",
"str",
"to",
"w",
"as",
"a",
"variable",
"length",
"integer",
"containing",
"the",
"length",
"of",
"the",
"string",
"followed",
"by",
"the",
"bytes",
"that",
"represent",
"the",
"string",
"itself",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/common.go#L621-L628 | train |
btcsuite/btcd | wire/common.go | ReadVarBytes | func ReadVarBytes(r io.Reader, pver uint32, maxAllowed uint32,
fieldName string) ([]byte, error) {
count, err := ReadVarInt(r, pver)
if err != nil {
return nil, err
}
// Prevent byte array larger than the max message size. It would
// be possible to cause memory exhaustion and panics without a sane
// upper bound on this count.
if count > uint64(maxAllowed) {
str := fmt.Sprintf("%s is larger than the max allowed size "+
"[count %d, max %d]", fieldName, count, maxAllowed)
return nil, messageError("ReadVarBytes", str)
}
b := make([]byte, count)
_, err = io.ReadFull(r, b)
if err != nil {
return nil, err
}
return b, nil
} | go | func ReadVarBytes(r io.Reader, pver uint32, maxAllowed uint32,
fieldName string) ([]byte, error) {
count, err := ReadVarInt(r, pver)
if err != nil {
return nil, err
}
// Prevent byte array larger than the max message size. It would
// be possible to cause memory exhaustion and panics without a sane
// upper bound on this count.
if count > uint64(maxAllowed) {
str := fmt.Sprintf("%s is larger than the max allowed size "+
"[count %d, max %d]", fieldName, count, maxAllowed)
return nil, messageError("ReadVarBytes", str)
}
b := make([]byte, count)
_, err = io.ReadFull(r, b)
if err != nil {
return nil, err
}
return b, nil
} | [
"func",
"ReadVarBytes",
"(",
"r",
"io",
".",
"Reader",
",",
"pver",
"uint32",
",",
"maxAllowed",
"uint32",
",",
"fieldName",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"count",
",",
"err",
":=",
"ReadVarInt",
"(",
"r",
",",
"pver",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Prevent byte array larger than the max message size. It would",
"// be possible to cause memory exhaustion and panics without a sane",
"// upper bound on this count.",
"if",
"count",
">",
"uint64",
"(",
"maxAllowed",
")",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"fieldName",
",",
"count",
",",
"maxAllowed",
")",
"\n",
"return",
"nil",
",",
"messageError",
"(",
"\"",
"\"",
",",
"str",
")",
"\n",
"}",
"\n\n",
"b",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"count",
")",
"\n",
"_",
",",
"err",
"=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"b",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"b",
",",
"nil",
"\n",
"}"
] | // ReadVarBytes reads a variable length byte array. A byte array is encoded
// as a varInt containing the length of the array followed by the bytes
// themselves. An error is returned if the length is greater than the
// passed maxAllowed parameter which helps protect against memory exhaustion
// attacks and forced panics through malformed messages. The fieldName
// parameter is only used for the error message so it provides more context in
// the error. | [
"ReadVarBytes",
"reads",
"a",
"variable",
"length",
"byte",
"array",
".",
"A",
"byte",
"array",
"is",
"encoded",
"as",
"a",
"varInt",
"containing",
"the",
"length",
"of",
"the",
"array",
"followed",
"by",
"the",
"bytes",
"themselves",
".",
"An",
"error",
"is",
"returned",
"if",
"the",
"length",
"is",
"greater",
"than",
"the",
"passed",
"maxAllowed",
"parameter",
"which",
"helps",
"protect",
"against",
"memory",
"exhaustion",
"attacks",
"and",
"forced",
"panics",
"through",
"malformed",
"messages",
".",
"The",
"fieldName",
"parameter",
"is",
"only",
"used",
"for",
"the",
"error",
"message",
"so",
"it",
"provides",
"more",
"context",
"in",
"the",
"error",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/common.go#L637-L660 | train |
btcsuite/btcd | wire/common.go | WriteVarBytes | func WriteVarBytes(w io.Writer, pver uint32, bytes []byte) error {
slen := uint64(len(bytes))
err := WriteVarInt(w, pver, slen)
if err != nil {
return err
}
_, err = w.Write(bytes)
return err
} | go | func WriteVarBytes(w io.Writer, pver uint32, bytes []byte) error {
slen := uint64(len(bytes))
err := WriteVarInt(w, pver, slen)
if err != nil {
return err
}
_, err = w.Write(bytes)
return err
} | [
"func",
"WriteVarBytes",
"(",
"w",
"io",
".",
"Writer",
",",
"pver",
"uint32",
",",
"bytes",
"[",
"]",
"byte",
")",
"error",
"{",
"slen",
":=",
"uint64",
"(",
"len",
"(",
"bytes",
")",
")",
"\n",
"err",
":=",
"WriteVarInt",
"(",
"w",
",",
"pver",
",",
"slen",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"_",
",",
"err",
"=",
"w",
".",
"Write",
"(",
"bytes",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // WriteVarBytes serializes a variable length byte array to w as a varInt
// containing the number of bytes, followed by the bytes themselves. | [
"WriteVarBytes",
"serializes",
"a",
"variable",
"length",
"byte",
"array",
"to",
"w",
"as",
"a",
"varInt",
"containing",
"the",
"number",
"of",
"bytes",
"followed",
"by",
"the",
"bytes",
"themselves",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/common.go#L664-L673 | train |
btcsuite/btcd | wire/common.go | randomUint64 | func randomUint64(r io.Reader) (uint64, error) {
rv, err := binarySerializer.Uint64(r, bigEndian)
if err != nil {
return 0, err
}
return rv, nil
} | go | func randomUint64(r io.Reader) (uint64, error) {
rv, err := binarySerializer.Uint64(r, bigEndian)
if err != nil {
return 0, err
}
return rv, nil
} | [
"func",
"randomUint64",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"uint64",
",",
"error",
")",
"{",
"rv",
",",
"err",
":=",
"binarySerializer",
".",
"Uint64",
"(",
"r",
",",
"bigEndian",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"return",
"rv",
",",
"nil",
"\n",
"}"
] | // randomUint64 returns a cryptographically random uint64 value. This
// unexported version takes a reader primarily to ensure the error paths
// can be properly tested by passing a fake reader in the tests. | [
"randomUint64",
"returns",
"a",
"cryptographically",
"random",
"uint64",
"value",
".",
"This",
"unexported",
"version",
"takes",
"a",
"reader",
"primarily",
"to",
"ensure",
"the",
"error",
"paths",
"can",
"be",
"properly",
"tested",
"by",
"passing",
"a",
"fake",
"reader",
"in",
"the",
"tests",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/common.go#L678-L684 | train |
btcsuite/btcd | btcjson/chainsvrcmds.go | NewAddNodeCmd | func NewAddNodeCmd(addr string, subCmd AddNodeSubCmd) *AddNodeCmd {
return &AddNodeCmd{
Addr: addr,
SubCmd: subCmd,
}
} | go | func NewAddNodeCmd(addr string, subCmd AddNodeSubCmd) *AddNodeCmd {
return &AddNodeCmd{
Addr: addr,
SubCmd: subCmd,
}
} | [
"func",
"NewAddNodeCmd",
"(",
"addr",
"string",
",",
"subCmd",
"AddNodeSubCmd",
")",
"*",
"AddNodeCmd",
"{",
"return",
"&",
"AddNodeCmd",
"{",
"Addr",
":",
"addr",
",",
"SubCmd",
":",
"subCmd",
",",
"}",
"\n",
"}"
] | // NewAddNodeCmd returns a new instance which can be used to issue an addnode
// JSON-RPC command. | [
"NewAddNodeCmd",
"returns",
"a",
"new",
"instance",
"which",
"can",
"be",
"used",
"to",
"issue",
"an",
"addnode",
"JSON",
"-",
"RPC",
"command",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/chainsvrcmds.go#L42-L47 | train |
btcsuite/btcd | btcjson/chainsvrcmds.go | NewCreateRawTransactionCmd | func NewCreateRawTransactionCmd(inputs []TransactionInput, amounts map[string]float64,
lockTime *int64) *CreateRawTransactionCmd {
return &CreateRawTransactionCmd{
Inputs: inputs,
Amounts: amounts,
LockTime: lockTime,
}
} | go | func NewCreateRawTransactionCmd(inputs []TransactionInput, amounts map[string]float64,
lockTime *int64) *CreateRawTransactionCmd {
return &CreateRawTransactionCmd{
Inputs: inputs,
Amounts: amounts,
LockTime: lockTime,
}
} | [
"func",
"NewCreateRawTransactionCmd",
"(",
"inputs",
"[",
"]",
"TransactionInput",
",",
"amounts",
"map",
"[",
"string",
"]",
"float64",
",",
"lockTime",
"*",
"int64",
")",
"*",
"CreateRawTransactionCmd",
"{",
"return",
"&",
"CreateRawTransactionCmd",
"{",
"Inputs",
":",
"inputs",
",",
"Amounts",
":",
"amounts",
",",
"LockTime",
":",
"lockTime",
",",
"}",
"\n",
"}"
] | // NewCreateRawTransactionCmd returns a new instance which can be used to issue
// a createrawtransaction JSON-RPC command.
//
// Amounts are in BTC. | [
"NewCreateRawTransactionCmd",
"returns",
"a",
"new",
"instance",
"which",
"can",
"be",
"used",
"to",
"issue",
"a",
"createrawtransaction",
"JSON",
"-",
"RPC",
"command",
".",
"Amounts",
"are",
"in",
"BTC",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/chainsvrcmds.go#L67-L75 | train |
btcsuite/btcd | btcjson/chainsvrcmds.go | NewGetAddedNodeInfoCmd | func NewGetAddedNodeInfoCmd(dns bool, node *string) *GetAddedNodeInfoCmd {
return &GetAddedNodeInfoCmd{
DNS: dns,
Node: node,
}
} | go | func NewGetAddedNodeInfoCmd(dns bool, node *string) *GetAddedNodeInfoCmd {
return &GetAddedNodeInfoCmd{
DNS: dns,
Node: node,
}
} | [
"func",
"NewGetAddedNodeInfoCmd",
"(",
"dns",
"bool",
",",
"node",
"*",
"string",
")",
"*",
"GetAddedNodeInfoCmd",
"{",
"return",
"&",
"GetAddedNodeInfoCmd",
"{",
"DNS",
":",
"dns",
",",
"Node",
":",
"node",
",",
"}",
"\n",
"}"
] | // NewGetAddedNodeInfoCmd returns a new instance which can be used to issue a
// getaddednodeinfo JSON-RPC command.
//
// The parameters which are pointers indicate they are optional. Passing nil
// for optional parameters will use the default value. | [
"NewGetAddedNodeInfoCmd",
"returns",
"a",
"new",
"instance",
"which",
"can",
"be",
"used",
"to",
"issue",
"a",
"getaddednodeinfo",
"JSON",
"-",
"RPC",
"command",
".",
"The",
"parameters",
"which",
"are",
"pointers",
"indicate",
"they",
"are",
"optional",
".",
"Passing",
"nil",
"for",
"optional",
"parameters",
"will",
"use",
"the",
"default",
"value",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/chainsvrcmds.go#L114-L119 | train |
btcsuite/btcd | btcjson/chainsvrcmds.go | NewGetBlockCmd | func NewGetBlockCmd(hash string, verbose, verboseTx *bool) *GetBlockCmd {
return &GetBlockCmd{
Hash: hash,
Verbose: verbose,
VerboseTx: verboseTx,
}
} | go | func NewGetBlockCmd(hash string, verbose, verboseTx *bool) *GetBlockCmd {
return &GetBlockCmd{
Hash: hash,
Verbose: verbose,
VerboseTx: verboseTx,
}
} | [
"func",
"NewGetBlockCmd",
"(",
"hash",
"string",
",",
"verbose",
",",
"verboseTx",
"*",
"bool",
")",
"*",
"GetBlockCmd",
"{",
"return",
"&",
"GetBlockCmd",
"{",
"Hash",
":",
"hash",
",",
"Verbose",
":",
"verbose",
",",
"VerboseTx",
":",
"verboseTx",
",",
"}",
"\n",
"}"
] | // NewGetBlockCmd returns a new instance which can be used to issue a getblock
// JSON-RPC command.
//
// The parameters which are pointers indicate they are optional. Passing nil
// for optional parameters will use the default value. | [
"NewGetBlockCmd",
"returns",
"a",
"new",
"instance",
"which",
"can",
"be",
"used",
"to",
"issue",
"a",
"getblock",
"JSON",
"-",
"RPC",
"command",
".",
"The",
"parameters",
"which",
"are",
"pointers",
"indicate",
"they",
"are",
"optional",
".",
"Passing",
"nil",
"for",
"optional",
"parameters",
"will",
"use",
"the",
"default",
"value",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/chainsvrcmds.go#L142-L148 | train |
btcsuite/btcd | btcjson/chainsvrcmds.go | NewGetBlockHeaderCmd | func NewGetBlockHeaderCmd(hash string, verbose *bool) *GetBlockHeaderCmd {
return &GetBlockHeaderCmd{
Hash: hash,
Verbose: verbose,
}
} | go | func NewGetBlockHeaderCmd(hash string, verbose *bool) *GetBlockHeaderCmd {
return &GetBlockHeaderCmd{
Hash: hash,
Verbose: verbose,
}
} | [
"func",
"NewGetBlockHeaderCmd",
"(",
"hash",
"string",
",",
"verbose",
"*",
"bool",
")",
"*",
"GetBlockHeaderCmd",
"{",
"return",
"&",
"GetBlockHeaderCmd",
"{",
"Hash",
":",
"hash",
",",
"Verbose",
":",
"verbose",
",",
"}",
"\n",
"}"
] | // NewGetBlockHeaderCmd returns a new instance which can be used to issue a
// getblockheader JSON-RPC command. | [
"NewGetBlockHeaderCmd",
"returns",
"a",
"new",
"instance",
"which",
"can",
"be",
"used",
"to",
"issue",
"a",
"getblockheader",
"JSON",
"-",
"RPC",
"command",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/chainsvrcmds.go#L189-L194 | train |
btcsuite/btcd | btcjson/chainsvrcmds.go | convertTemplateRequestField | func convertTemplateRequestField(fieldName string, iface interface{}) (interface{}, error) {
switch val := iface.(type) {
case nil:
return nil, nil
case bool:
return val, nil
case float64:
if val == float64(int64(val)) {
return int64(val), nil
}
}
str := fmt.Sprintf("the %s field must be unspecified, a boolean, or "+
"a 64-bit integer", fieldName)
return nil, makeError(ErrInvalidType, str)
} | go | func convertTemplateRequestField(fieldName string, iface interface{}) (interface{}, error) {
switch val := iface.(type) {
case nil:
return nil, nil
case bool:
return val, nil
case float64:
if val == float64(int64(val)) {
return int64(val), nil
}
}
str := fmt.Sprintf("the %s field must be unspecified, a boolean, or "+
"a 64-bit integer", fieldName)
return nil, makeError(ErrInvalidType, str)
} | [
"func",
"convertTemplateRequestField",
"(",
"fieldName",
"string",
",",
"iface",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"switch",
"val",
":=",
"iface",
".",
"(",
"type",
")",
"{",
"case",
"nil",
":",
"return",
"nil",
",",
"nil",
"\n",
"case",
"bool",
":",
"return",
"val",
",",
"nil",
"\n",
"case",
"float64",
":",
"if",
"val",
"==",
"float64",
"(",
"int64",
"(",
"val",
")",
")",
"{",
"return",
"int64",
"(",
"val",
")",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"fieldName",
")",
"\n",
"return",
"nil",
",",
"makeError",
"(",
"ErrInvalidType",
",",
"str",
")",
"\n",
"}"
] | // convertTemplateRequestField potentially converts the provided value as
// needed. | [
"convertTemplateRequestField",
"potentially",
"converts",
"the",
"provided",
"value",
"as",
"needed",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/chainsvrcmds.go#L223-L238 | train |
btcsuite/btcd | btcjson/chainsvrcmds.go | UnmarshalJSON | func (t *TemplateRequest) UnmarshalJSON(data []byte) error {
type templateRequest TemplateRequest
request := (*templateRequest)(t)
if err := json.Unmarshal(data, &request); err != nil {
return err
}
// The SigOpLimit field can only be nil, bool, or int64.
val, err := convertTemplateRequestField("sigoplimit", request.SigOpLimit)
if err != nil {
return err
}
request.SigOpLimit = val
// The SizeLimit field can only be nil, bool, or int64.
val, err = convertTemplateRequestField("sizelimit", request.SizeLimit)
if err != nil {
return err
}
request.SizeLimit = val
return nil
} | go | func (t *TemplateRequest) UnmarshalJSON(data []byte) error {
type templateRequest TemplateRequest
request := (*templateRequest)(t)
if err := json.Unmarshal(data, &request); err != nil {
return err
}
// The SigOpLimit field can only be nil, bool, or int64.
val, err := convertTemplateRequestField("sigoplimit", request.SigOpLimit)
if err != nil {
return err
}
request.SigOpLimit = val
// The SizeLimit field can only be nil, bool, or int64.
val, err = convertTemplateRequestField("sizelimit", request.SizeLimit)
if err != nil {
return err
}
request.SizeLimit = val
return nil
} | [
"func",
"(",
"t",
"*",
"TemplateRequest",
")",
"UnmarshalJSON",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"type",
"templateRequest",
"TemplateRequest",
"\n\n",
"request",
":=",
"(",
"*",
"templateRequest",
")",
"(",
"t",
")",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"&",
"request",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// The SigOpLimit field can only be nil, bool, or int64.",
"val",
",",
"err",
":=",
"convertTemplateRequestField",
"(",
"\"",
"\"",
",",
"request",
".",
"SigOpLimit",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"request",
".",
"SigOpLimit",
"=",
"val",
"\n\n",
"// The SizeLimit field can only be nil, bool, or int64.",
"val",
",",
"err",
"=",
"convertTemplateRequestField",
"(",
"\"",
"\"",
",",
"request",
".",
"SizeLimit",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"request",
".",
"SizeLimit",
"=",
"val",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // UnmarshalJSON provides a custom Unmarshal method for TemplateRequest. This
// is necessary because the SigOpLimit and SizeLimit fields can only be specific
// types. | [
"UnmarshalJSON",
"provides",
"a",
"custom",
"Unmarshal",
"method",
"for",
"TemplateRequest",
".",
"This",
"is",
"necessary",
"because",
"the",
"SigOpLimit",
"and",
"SizeLimit",
"fields",
"can",
"only",
"be",
"specific",
"types",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/chainsvrcmds.go#L243-L266 | train |
btcsuite/btcd | btcjson/chainsvrcmds.go | NewGetCFilterCmd | func NewGetCFilterCmd(hash string, filterType wire.FilterType) *GetCFilterCmd {
return &GetCFilterCmd{
Hash: hash,
FilterType: filterType,
}
} | go | func NewGetCFilterCmd(hash string, filterType wire.FilterType) *GetCFilterCmd {
return &GetCFilterCmd{
Hash: hash,
FilterType: filterType,
}
} | [
"func",
"NewGetCFilterCmd",
"(",
"hash",
"string",
",",
"filterType",
"wire",
".",
"FilterType",
")",
"*",
"GetCFilterCmd",
"{",
"return",
"&",
"GetCFilterCmd",
"{",
"Hash",
":",
"hash",
",",
"FilterType",
":",
"filterType",
",",
"}",
"\n",
"}"
] | // NewGetCFilterCmd returns a new instance which can be used to issue a
// getcfilter JSON-RPC command. | [
"NewGetCFilterCmd",
"returns",
"a",
"new",
"instance",
"which",
"can",
"be",
"used",
"to",
"issue",
"a",
"getcfilter",
"JSON",
"-",
"RPC",
"command",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/chainsvrcmds.go#L292-L297 | train |
btcsuite/btcd | btcjson/chainsvrcmds.go | NewGetCFilterHeaderCmd | func NewGetCFilterHeaderCmd(hash string,
filterType wire.FilterType) *GetCFilterHeaderCmd {
return &GetCFilterHeaderCmd{
Hash: hash,
FilterType: filterType,
}
} | go | func NewGetCFilterHeaderCmd(hash string,
filterType wire.FilterType) *GetCFilterHeaderCmd {
return &GetCFilterHeaderCmd{
Hash: hash,
FilterType: filterType,
}
} | [
"func",
"NewGetCFilterHeaderCmd",
"(",
"hash",
"string",
",",
"filterType",
"wire",
".",
"FilterType",
")",
"*",
"GetCFilterHeaderCmd",
"{",
"return",
"&",
"GetCFilterHeaderCmd",
"{",
"Hash",
":",
"hash",
",",
"FilterType",
":",
"filterType",
",",
"}",
"\n",
"}"
] | // NewGetCFilterHeaderCmd returns a new instance which can be used to issue a
// getcfilterheader JSON-RPC command. | [
"NewGetCFilterHeaderCmd",
"returns",
"a",
"new",
"instance",
"which",
"can",
"be",
"used",
"to",
"issue",
"a",
"getcfilterheader",
"JSON",
"-",
"RPC",
"command",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/chainsvrcmds.go#L307-L313 | train |
btcsuite/btcd | btcjson/chainsvrcmds.go | NewGetNetworkHashPSCmd | func NewGetNetworkHashPSCmd(numBlocks, height *int) *GetNetworkHashPSCmd {
return &GetNetworkHashPSCmd{
Blocks: numBlocks,
Height: height,
}
} | go | func NewGetNetworkHashPSCmd(numBlocks, height *int) *GetNetworkHashPSCmd {
return &GetNetworkHashPSCmd{
Blocks: numBlocks,
Height: height,
}
} | [
"func",
"NewGetNetworkHashPSCmd",
"(",
"numBlocks",
",",
"height",
"*",
"int",
")",
"*",
"GetNetworkHashPSCmd",
"{",
"return",
"&",
"GetNetworkHashPSCmd",
"{",
"Blocks",
":",
"numBlocks",
",",
"Height",
":",
"height",
",",
"}",
"\n",
"}"
] | // NewGetNetworkHashPSCmd returns a new instance which can be used to issue a
// getnetworkhashps JSON-RPC command.
//
// The parameters which are pointers indicate they are optional. Passing nil
// for optional parameters will use the default value. | [
"NewGetNetworkHashPSCmd",
"returns",
"a",
"new",
"instance",
"which",
"can",
"be",
"used",
"to",
"issue",
"a",
"getnetworkhashps",
"JSON",
"-",
"RPC",
"command",
".",
"The",
"parameters",
"which",
"are",
"pointers",
"indicate",
"they",
"are",
"optional",
".",
"Passing",
"nil",
"for",
"optional",
"parameters",
"will",
"use",
"the",
"default",
"value",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/chainsvrcmds.go#L429-L434 | train |
btcsuite/btcd | btcjson/chainsvrcmds.go | NewGetRawTransactionCmd | func NewGetRawTransactionCmd(txHash string, verbose *int) *GetRawTransactionCmd {
return &GetRawTransactionCmd{
Txid: txHash,
Verbose: verbose,
}
} | go | func NewGetRawTransactionCmd(txHash string, verbose *int) *GetRawTransactionCmd {
return &GetRawTransactionCmd{
Txid: txHash,
Verbose: verbose,
}
} | [
"func",
"NewGetRawTransactionCmd",
"(",
"txHash",
"string",
",",
"verbose",
"*",
"int",
")",
"*",
"GetRawTransactionCmd",
"{",
"return",
"&",
"GetRawTransactionCmd",
"{",
"Txid",
":",
"txHash",
",",
"Verbose",
":",
"verbose",
",",
"}",
"\n",
"}"
] | // NewGetRawTransactionCmd returns a new instance which can be used to issue a
// getrawtransaction JSON-RPC command.
//
// The parameters which are pointers indicate they are optional. Passing nil
// for optional parameters will use the default value. | [
"NewGetRawTransactionCmd",
"returns",
"a",
"new",
"instance",
"which",
"can",
"be",
"used",
"to",
"issue",
"a",
"getrawtransaction",
"JSON",
"-",
"RPC",
"command",
".",
"The",
"parameters",
"which",
"are",
"pointers",
"indicate",
"they",
"are",
"optional",
".",
"Passing",
"nil",
"for",
"optional",
"parameters",
"will",
"use",
"the",
"default",
"value",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/chainsvrcmds.go#L475-L480 | train |
btcsuite/btcd | btcjson/chainsvrcmds.go | NewGetTxOutCmd | func NewGetTxOutCmd(txHash string, vout uint32, includeMempool *bool) *GetTxOutCmd {
return &GetTxOutCmd{
Txid: txHash,
Vout: vout,
IncludeMempool: includeMempool,
}
} | go | func NewGetTxOutCmd(txHash string, vout uint32, includeMempool *bool) *GetTxOutCmd {
return &GetTxOutCmd{
Txid: txHash,
Vout: vout,
IncludeMempool: includeMempool,
}
} | [
"func",
"NewGetTxOutCmd",
"(",
"txHash",
"string",
",",
"vout",
"uint32",
",",
"includeMempool",
"*",
"bool",
")",
"*",
"GetTxOutCmd",
"{",
"return",
"&",
"GetTxOutCmd",
"{",
"Txid",
":",
"txHash",
",",
"Vout",
":",
"vout",
",",
"IncludeMempool",
":",
"includeMempool",
",",
"}",
"\n",
"}"
] | // NewGetTxOutCmd returns a new instance which can be used to issue a gettxout
// JSON-RPC command.
//
// The parameters which are pointers indicate they are optional. Passing nil
// for optional parameters will use the default value. | [
"NewGetTxOutCmd",
"returns",
"a",
"new",
"instance",
"which",
"can",
"be",
"used",
"to",
"issue",
"a",
"gettxout",
"JSON",
"-",
"RPC",
"command",
".",
"The",
"parameters",
"which",
"are",
"pointers",
"indicate",
"they",
"are",
"optional",
".",
"Passing",
"nil",
"for",
"optional",
"parameters",
"will",
"use",
"the",
"default",
"value",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/chainsvrcmds.go#L494-L500 | train |
btcsuite/btcd | btcjson/chainsvrcmds.go | NewGetTxOutProofCmd | func NewGetTxOutProofCmd(txIDs []string, blockHash *string) *GetTxOutProofCmd {
return &GetTxOutProofCmd{
TxIDs: txIDs,
BlockHash: blockHash,
}
} | go | func NewGetTxOutProofCmd(txIDs []string, blockHash *string) *GetTxOutProofCmd {
return &GetTxOutProofCmd{
TxIDs: txIDs,
BlockHash: blockHash,
}
} | [
"func",
"NewGetTxOutProofCmd",
"(",
"txIDs",
"[",
"]",
"string",
",",
"blockHash",
"*",
"string",
")",
"*",
"GetTxOutProofCmd",
"{",
"return",
"&",
"GetTxOutProofCmd",
"{",
"TxIDs",
":",
"txIDs",
",",
"BlockHash",
":",
"blockHash",
",",
"}",
"\n",
"}"
] | // NewGetTxOutProofCmd returns a new instance which can be used to issue a
// gettxoutproof JSON-RPC command.
//
// The parameters which are pointers indicate they are optional. Passing nil
// for optional parameters will use the default value. | [
"NewGetTxOutProofCmd",
"returns",
"a",
"new",
"instance",
"which",
"can",
"be",
"used",
"to",
"issue",
"a",
"gettxoutproof",
"JSON",
"-",
"RPC",
"command",
".",
"The",
"parameters",
"which",
"are",
"pointers",
"indicate",
"they",
"are",
"optional",
".",
"Passing",
"nil",
"for",
"optional",
"parameters",
"will",
"use",
"the",
"default",
"value",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/chainsvrcmds.go#L513-L518 | train |
btcsuite/btcd | btcjson/chainsvrcmds.go | NewSearchRawTransactionsCmd | func NewSearchRawTransactionsCmd(address string, verbose, skip, count *int, vinExtra *int, reverse *bool, filterAddrs *[]string) *SearchRawTransactionsCmd {
return &SearchRawTransactionsCmd{
Address: address,
Verbose: verbose,
Skip: skip,
Count: count,
VinExtra: vinExtra,
Reverse: reverse,
FilterAddrs: filterAddrs,
}
} | go | func NewSearchRawTransactionsCmd(address string, verbose, skip, count *int, vinExtra *int, reverse *bool, filterAddrs *[]string) *SearchRawTransactionsCmd {
return &SearchRawTransactionsCmd{
Address: address,
Verbose: verbose,
Skip: skip,
Count: count,
VinExtra: vinExtra,
Reverse: reverse,
FilterAddrs: filterAddrs,
}
} | [
"func",
"NewSearchRawTransactionsCmd",
"(",
"address",
"string",
",",
"verbose",
",",
"skip",
",",
"count",
"*",
"int",
",",
"vinExtra",
"*",
"int",
",",
"reverse",
"*",
"bool",
",",
"filterAddrs",
"*",
"[",
"]",
"string",
")",
"*",
"SearchRawTransactionsCmd",
"{",
"return",
"&",
"SearchRawTransactionsCmd",
"{",
"Address",
":",
"address",
",",
"Verbose",
":",
"verbose",
",",
"Skip",
":",
"skip",
",",
"Count",
":",
"count",
",",
"VinExtra",
":",
"vinExtra",
",",
"Reverse",
":",
"reverse",
",",
"FilterAddrs",
":",
"filterAddrs",
",",
"}",
"\n",
"}"
] | // NewSearchRawTransactionsCmd returns a new instance which can be used to issue a
// sendrawtransaction JSON-RPC command.
//
// The parameters which are pointers indicate they are optional. Passing nil
// for optional parameters will use the default value. | [
"NewSearchRawTransactionsCmd",
"returns",
"a",
"new",
"instance",
"which",
"can",
"be",
"used",
"to",
"issue",
"a",
"sendrawtransaction",
"JSON",
"-",
"RPC",
"command",
".",
"The",
"parameters",
"which",
"are",
"pointers",
"indicate",
"they",
"are",
"optional",
".",
"Passing",
"nil",
"for",
"optional",
"parameters",
"will",
"use",
"the",
"default",
"value",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/chainsvrcmds.go#L625-L635 | train |
btcsuite/btcd | btcjson/chainsvrcmds.go | NewSendRawTransactionCmd | func NewSendRawTransactionCmd(hexTx string, allowHighFees *bool) *SendRawTransactionCmd {
return &SendRawTransactionCmd{
HexTx: hexTx,
AllowHighFees: allowHighFees,
}
} | go | func NewSendRawTransactionCmd(hexTx string, allowHighFees *bool) *SendRawTransactionCmd {
return &SendRawTransactionCmd{
HexTx: hexTx,
AllowHighFees: allowHighFees,
}
} | [
"func",
"NewSendRawTransactionCmd",
"(",
"hexTx",
"string",
",",
"allowHighFees",
"*",
"bool",
")",
"*",
"SendRawTransactionCmd",
"{",
"return",
"&",
"SendRawTransactionCmd",
"{",
"HexTx",
":",
"hexTx",
",",
"AllowHighFees",
":",
"allowHighFees",
",",
"}",
"\n",
"}"
] | // NewSendRawTransactionCmd returns a new instance which can be used to issue a
// sendrawtransaction JSON-RPC command.
//
// The parameters which are pointers indicate they are optional. Passing nil
// for optional parameters will use the default value. | [
"NewSendRawTransactionCmd",
"returns",
"a",
"new",
"instance",
"which",
"can",
"be",
"used",
"to",
"issue",
"a",
"sendrawtransaction",
"JSON",
"-",
"RPC",
"command",
".",
"The",
"parameters",
"which",
"are",
"pointers",
"indicate",
"they",
"are",
"optional",
".",
"Passing",
"nil",
"for",
"optional",
"parameters",
"will",
"use",
"the",
"default",
"value",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/chainsvrcmds.go#L648-L653 | train |
btcsuite/btcd | btcjson/chainsvrcmds.go | NewSetGenerateCmd | func NewSetGenerateCmd(generate bool, genProcLimit *int) *SetGenerateCmd {
return &SetGenerateCmd{
Generate: generate,
GenProcLimit: genProcLimit,
}
} | go | func NewSetGenerateCmd(generate bool, genProcLimit *int) *SetGenerateCmd {
return &SetGenerateCmd{
Generate: generate,
GenProcLimit: genProcLimit,
}
} | [
"func",
"NewSetGenerateCmd",
"(",
"generate",
"bool",
",",
"genProcLimit",
"*",
"int",
")",
"*",
"SetGenerateCmd",
"{",
"return",
"&",
"SetGenerateCmd",
"{",
"Generate",
":",
"generate",
",",
"GenProcLimit",
":",
"genProcLimit",
",",
"}",
"\n",
"}"
] | // NewSetGenerateCmd returns a new instance which can be used to issue a
// setgenerate JSON-RPC command.
//
// The parameters which are pointers indicate they are optional. Passing nil
// for optional parameters will use the default value. | [
"NewSetGenerateCmd",
"returns",
"a",
"new",
"instance",
"which",
"can",
"be",
"used",
"to",
"issue",
"a",
"setgenerate",
"JSON",
"-",
"RPC",
"command",
".",
"The",
"parameters",
"which",
"are",
"pointers",
"indicate",
"they",
"are",
"optional",
".",
"Passing",
"nil",
"for",
"optional",
"parameters",
"will",
"use",
"the",
"default",
"value",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/chainsvrcmds.go#L666-L671 | train |
btcsuite/btcd | btcjson/chainsvrcmds.go | NewSubmitBlockCmd | func NewSubmitBlockCmd(hexBlock string, options *SubmitBlockOptions) *SubmitBlockCmd {
return &SubmitBlockCmd{
HexBlock: hexBlock,
Options: options,
}
} | go | func NewSubmitBlockCmd(hexBlock string, options *SubmitBlockOptions) *SubmitBlockCmd {
return &SubmitBlockCmd{
HexBlock: hexBlock,
Options: options,
}
} | [
"func",
"NewSubmitBlockCmd",
"(",
"hexBlock",
"string",
",",
"options",
"*",
"SubmitBlockOptions",
")",
"*",
"SubmitBlockCmd",
"{",
"return",
"&",
"SubmitBlockCmd",
"{",
"HexBlock",
":",
"hexBlock",
",",
"Options",
":",
"options",
",",
"}",
"\n",
"}"
] | // NewSubmitBlockCmd returns a new instance which can be used to issue a
// submitblock JSON-RPC command.
//
// The parameters which are pointers indicate they are optional. Passing nil
// for optional parameters will use the default value. | [
"NewSubmitBlockCmd",
"returns",
"a",
"new",
"instance",
"which",
"can",
"be",
"used",
"to",
"issue",
"a",
"submitblock",
"JSON",
"-",
"RPC",
"command",
".",
"The",
"parameters",
"which",
"are",
"pointers",
"indicate",
"they",
"are",
"optional",
".",
"Passing",
"nil",
"for",
"optional",
"parameters",
"will",
"use",
"the",
"default",
"value",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/chainsvrcmds.go#L700-L705 | train |
btcsuite/btcd | btcjson/chainsvrcmds.go | NewVerifyChainCmd | func NewVerifyChainCmd(checkLevel, checkDepth *int32) *VerifyChainCmd {
return &VerifyChainCmd{
CheckLevel: checkLevel,
CheckDepth: checkDepth,
}
} | go | func NewVerifyChainCmd(checkLevel, checkDepth *int32) *VerifyChainCmd {
return &VerifyChainCmd{
CheckLevel: checkLevel,
CheckDepth: checkDepth,
}
} | [
"func",
"NewVerifyChainCmd",
"(",
"checkLevel",
",",
"checkDepth",
"*",
"int32",
")",
"*",
"VerifyChainCmd",
"{",
"return",
"&",
"VerifyChainCmd",
"{",
"CheckLevel",
":",
"checkLevel",
",",
"CheckDepth",
":",
"checkDepth",
",",
"}",
"\n",
"}"
] | // NewVerifyChainCmd returns a new instance which can be used to issue a
// verifychain JSON-RPC command.
//
// The parameters which are pointers indicate they are optional. Passing nil
// for optional parameters will use the default value. | [
"NewVerifyChainCmd",
"returns",
"a",
"new",
"instance",
"which",
"can",
"be",
"used",
"to",
"issue",
"a",
"verifychain",
"JSON",
"-",
"RPC",
"command",
".",
"The",
"parameters",
"which",
"are",
"pointers",
"indicate",
"they",
"are",
"optional",
".",
"Passing",
"nil",
"for",
"optional",
"parameters",
"will",
"use",
"the",
"default",
"value",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/chainsvrcmds.go#L739-L744 | train |
btcsuite/btcd | btcjson/chainsvrcmds.go | NewVerifyMessageCmd | func NewVerifyMessageCmd(address, signature, message string) *VerifyMessageCmd {
return &VerifyMessageCmd{
Address: address,
Signature: signature,
Message: message,
}
} | go | func NewVerifyMessageCmd(address, signature, message string) *VerifyMessageCmd {
return &VerifyMessageCmd{
Address: address,
Signature: signature,
Message: message,
}
} | [
"func",
"NewVerifyMessageCmd",
"(",
"address",
",",
"signature",
",",
"message",
"string",
")",
"*",
"VerifyMessageCmd",
"{",
"return",
"&",
"VerifyMessageCmd",
"{",
"Address",
":",
"address",
",",
"Signature",
":",
"signature",
",",
"Message",
":",
"message",
",",
"}",
"\n",
"}"
] | // NewVerifyMessageCmd returns a new instance which can be used to issue a
// verifymessage JSON-RPC command. | [
"NewVerifyMessageCmd",
"returns",
"a",
"new",
"instance",
"which",
"can",
"be",
"used",
"to",
"issue",
"a",
"verifymessage",
"JSON",
"-",
"RPC",
"command",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/chainsvrcmds.go#L755-L761 | train |
btcsuite/btcd | chaincfg/params.go | mustRegister | func mustRegister(params *Params) {
if err := Register(params); err != nil {
panic("failed to register network: " + err.Error())
}
} | go | func mustRegister(params *Params) {
if err := Register(params); err != nil {
panic("failed to register network: " + err.Error())
}
} | [
"func",
"mustRegister",
"(",
"params",
"*",
"Params",
")",
"{",
"if",
"err",
":=",
"Register",
"(",
"params",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
"+",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"}"
] | // mustRegister performs the same function as Register except it panics if there
// is an error. This should only be called from package init functions. | [
"mustRegister",
"performs",
"the",
"same",
"function",
"as",
"Register",
"except",
"it",
"panics",
"if",
"there",
"is",
"an",
"error",
".",
"This",
"should",
"only",
"be",
"called",
"from",
"package",
"init",
"functions",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/chaincfg/params.go#L632-L636 | train |
btcsuite/btcd | chaincfg/params.go | IsBech32SegwitPrefix | func IsBech32SegwitPrefix(prefix string) bool {
prefix = strings.ToLower(prefix)
_, ok := bech32SegwitPrefixes[prefix]
return ok
} | go | func IsBech32SegwitPrefix(prefix string) bool {
prefix = strings.ToLower(prefix)
_, ok := bech32SegwitPrefixes[prefix]
return ok
} | [
"func",
"IsBech32SegwitPrefix",
"(",
"prefix",
"string",
")",
"bool",
"{",
"prefix",
"=",
"strings",
".",
"ToLower",
"(",
"prefix",
")",
"\n",
"_",
",",
"ok",
":=",
"bech32SegwitPrefixes",
"[",
"prefix",
"]",
"\n",
"return",
"ok",
"\n",
"}"
] | // IsBech32SegwitPrefix returns whether the prefix is a known prefix for segwit
// addresses on any default or registered network. This is used when decoding
// an address string into a specific address type. | [
"IsBech32SegwitPrefix",
"returns",
"whether",
"the",
"prefix",
"is",
"a",
"known",
"prefix",
"for",
"segwit",
"addresses",
"on",
"any",
"default",
"or",
"registered",
"network",
".",
"This",
"is",
"used",
"when",
"decoding",
"an",
"address",
"string",
"into",
"a",
"specific",
"address",
"type",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/chaincfg/params.go#L663-L667 | train |
btcsuite/btcd | chaincfg/params.go | HDPrivateKeyToPublicKeyID | func HDPrivateKeyToPublicKeyID(id []byte) ([]byte, error) {
if len(id) != 4 {
return nil, ErrUnknownHDKeyID
}
var key [4]byte
copy(key[:], id)
pubBytes, ok := hdPrivToPubKeyIDs[key]
if !ok {
return nil, ErrUnknownHDKeyID
}
return pubBytes, nil
} | go | func HDPrivateKeyToPublicKeyID(id []byte) ([]byte, error) {
if len(id) != 4 {
return nil, ErrUnknownHDKeyID
}
var key [4]byte
copy(key[:], id)
pubBytes, ok := hdPrivToPubKeyIDs[key]
if !ok {
return nil, ErrUnknownHDKeyID
}
return pubBytes, nil
} | [
"func",
"HDPrivateKeyToPublicKeyID",
"(",
"id",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"len",
"(",
"id",
")",
"!=",
"4",
"{",
"return",
"nil",
",",
"ErrUnknownHDKeyID",
"\n",
"}",
"\n\n",
"var",
"key",
"[",
"4",
"]",
"byte",
"\n",
"copy",
"(",
"key",
"[",
":",
"]",
",",
"id",
")",
"\n",
"pubBytes",
",",
"ok",
":=",
"hdPrivToPubKeyIDs",
"[",
"key",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"ErrUnknownHDKeyID",
"\n",
"}",
"\n\n",
"return",
"pubBytes",
",",
"nil",
"\n",
"}"
] | // HDPrivateKeyToPublicKeyID accepts a private hierarchical deterministic
// extended key id and returns the associated public key id. When the provided
// id is not registered, the ErrUnknownHDKeyID error will be returned. | [
"HDPrivateKeyToPublicKeyID",
"accepts",
"a",
"private",
"hierarchical",
"deterministic",
"extended",
"key",
"id",
"and",
"returns",
"the",
"associated",
"public",
"key",
"id",
".",
"When",
"the",
"provided",
"id",
"is",
"not",
"registered",
"the",
"ErrUnknownHDKeyID",
"error",
"will",
"be",
"returned",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/chaincfg/params.go#L672-L685 | train |
btcsuite/btcd | blockchain/timesorter.go | Swap | func (s timeSorter) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
} | go | func (s timeSorter) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
} | [
"func",
"(",
"s",
"timeSorter",
")",
"Swap",
"(",
"i",
",",
"j",
"int",
")",
"{",
"s",
"[",
"i",
"]",
",",
"s",
"[",
"j",
"]",
"=",
"s",
"[",
"j",
"]",
",",
"s",
"[",
"i",
"]",
"\n",
"}"
] | // Swap swaps the timestamps at the passed indices. It is part of the
// sort.Interface implementation. | [
"Swap",
"swaps",
"the",
"timestamps",
"at",
"the",
"passed",
"indices",
".",
"It",
"is",
"part",
"of",
"the",
"sort",
".",
"Interface",
"implementation",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/timesorter.go#L19-L21 | train |
btcsuite/btcd | blockchain/timesorter.go | Less | func (s timeSorter) Less(i, j int) bool {
return s[i] < s[j]
} | go | func (s timeSorter) Less(i, j int) bool {
return s[i] < s[j]
} | [
"func",
"(",
"s",
"timeSorter",
")",
"Less",
"(",
"i",
",",
"j",
"int",
")",
"bool",
"{",
"return",
"s",
"[",
"i",
"]",
"<",
"s",
"[",
"j",
"]",
"\n",
"}"
] | // Less returns whether the timstamp with index i should sort before the
// timestamp with index j. It is part of the sort.Interface implementation. | [
"Less",
"returns",
"whether",
"the",
"timstamp",
"with",
"index",
"i",
"should",
"sort",
"before",
"the",
"timestamp",
"with",
"index",
"j",
".",
"It",
"is",
"part",
"of",
"the",
"sort",
".",
"Interface",
"implementation",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/timesorter.go#L25-L27 | train |
btcsuite/btcd | btcec/privkey.go | PrivKeyFromBytes | func PrivKeyFromBytes(curve elliptic.Curve, pk []byte) (*PrivateKey,
*PublicKey) {
x, y := curve.ScalarBaseMult(pk)
priv := &ecdsa.PrivateKey{
PublicKey: ecdsa.PublicKey{
Curve: curve,
X: x,
Y: y,
},
D: new(big.Int).SetBytes(pk),
}
return (*PrivateKey)(priv), (*PublicKey)(&priv.PublicKey)
} | go | func PrivKeyFromBytes(curve elliptic.Curve, pk []byte) (*PrivateKey,
*PublicKey) {
x, y := curve.ScalarBaseMult(pk)
priv := &ecdsa.PrivateKey{
PublicKey: ecdsa.PublicKey{
Curve: curve,
X: x,
Y: y,
},
D: new(big.Int).SetBytes(pk),
}
return (*PrivateKey)(priv), (*PublicKey)(&priv.PublicKey)
} | [
"func",
"PrivKeyFromBytes",
"(",
"curve",
"elliptic",
".",
"Curve",
",",
"pk",
"[",
"]",
"byte",
")",
"(",
"*",
"PrivateKey",
",",
"*",
"PublicKey",
")",
"{",
"x",
",",
"y",
":=",
"curve",
".",
"ScalarBaseMult",
"(",
"pk",
")",
"\n\n",
"priv",
":=",
"&",
"ecdsa",
".",
"PrivateKey",
"{",
"PublicKey",
":",
"ecdsa",
".",
"PublicKey",
"{",
"Curve",
":",
"curve",
",",
"X",
":",
"x",
",",
"Y",
":",
"y",
",",
"}",
",",
"D",
":",
"new",
"(",
"big",
".",
"Int",
")",
".",
"SetBytes",
"(",
"pk",
")",
",",
"}",
"\n\n",
"return",
"(",
"*",
"PrivateKey",
")",
"(",
"priv",
")",
",",
"(",
"*",
"PublicKey",
")",
"(",
"&",
"priv",
".",
"PublicKey",
")",
"\n",
"}"
] | // PrivKeyFromBytes returns a private and public key for `curve' based on the
// private key passed as an argument as a byte slice. | [
"PrivKeyFromBytes",
"returns",
"a",
"private",
"and",
"public",
"key",
"for",
"curve",
"based",
"on",
"the",
"private",
"key",
"passed",
"as",
"an",
"argument",
"as",
"a",
"byte",
"slice",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/privkey.go#L21-L35 | train |
btcsuite/btcd | btcec/privkey.go | NewPrivateKey | func NewPrivateKey(curve elliptic.Curve) (*PrivateKey, error) {
key, err := ecdsa.GenerateKey(curve, rand.Reader)
if err != nil {
return nil, err
}
return (*PrivateKey)(key), nil
} | go | func NewPrivateKey(curve elliptic.Curve) (*PrivateKey, error) {
key, err := ecdsa.GenerateKey(curve, rand.Reader)
if err != nil {
return nil, err
}
return (*PrivateKey)(key), nil
} | [
"func",
"NewPrivateKey",
"(",
"curve",
"elliptic",
".",
"Curve",
")",
"(",
"*",
"PrivateKey",
",",
"error",
")",
"{",
"key",
",",
"err",
":=",
"ecdsa",
".",
"GenerateKey",
"(",
"curve",
",",
"rand",
".",
"Reader",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"(",
"*",
"PrivateKey",
")",
"(",
"key",
")",
",",
"nil",
"\n",
"}"
] | // NewPrivateKey is a wrapper for ecdsa.GenerateKey that returns a PrivateKey
// instead of the normal ecdsa.PrivateKey. | [
"NewPrivateKey",
"is",
"a",
"wrapper",
"for",
"ecdsa",
".",
"GenerateKey",
"that",
"returns",
"a",
"PrivateKey",
"instead",
"of",
"the",
"normal",
"ecdsa",
".",
"PrivateKey",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/privkey.go#L39-L45 | train |
btcsuite/btcd | btcec/privkey.go | Serialize | func (p *PrivateKey) Serialize() []byte {
b := make([]byte, 0, PrivKeyBytesLen)
return paddedAppend(PrivKeyBytesLen, b, p.ToECDSA().D.Bytes())
} | go | func (p *PrivateKey) Serialize() []byte {
b := make([]byte, 0, PrivKeyBytesLen)
return paddedAppend(PrivKeyBytesLen, b, p.ToECDSA().D.Bytes())
} | [
"func",
"(",
"p",
"*",
"PrivateKey",
")",
"Serialize",
"(",
")",
"[",
"]",
"byte",
"{",
"b",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"PrivKeyBytesLen",
")",
"\n",
"return",
"paddedAppend",
"(",
"PrivKeyBytesLen",
",",
"b",
",",
"p",
".",
"ToECDSA",
"(",
")",
".",
"D",
".",
"Bytes",
"(",
")",
")",
"\n",
"}"
] | // Serialize returns the private key number d as a big-endian binary-encoded
// number, padded to a length of 32 bytes. | [
"Serialize",
"returns",
"the",
"private",
"key",
"number",
"d",
"as",
"a",
"big",
"-",
"endian",
"binary",
"-",
"encoded",
"number",
"padded",
"to",
"a",
"length",
"of",
"32",
"bytes",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/privkey.go#L70-L73 | train |
btcsuite/btcd | wire/msggetcfcheckpt.go | NewMsgGetCFCheckpt | func NewMsgGetCFCheckpt(filterType FilterType, stopHash *chainhash.Hash) *MsgGetCFCheckpt {
return &MsgGetCFCheckpt{
FilterType: filterType,
StopHash: *stopHash,
}
} | go | func NewMsgGetCFCheckpt(filterType FilterType, stopHash *chainhash.Hash) *MsgGetCFCheckpt {
return &MsgGetCFCheckpt{
FilterType: filterType,
StopHash: *stopHash,
}
} | [
"func",
"NewMsgGetCFCheckpt",
"(",
"filterType",
"FilterType",
",",
"stopHash",
"*",
"chainhash",
".",
"Hash",
")",
"*",
"MsgGetCFCheckpt",
"{",
"return",
"&",
"MsgGetCFCheckpt",
"{",
"FilterType",
":",
"filterType",
",",
"StopHash",
":",
"*",
"stopHash",
",",
"}",
"\n",
"}"
] | // NewMsgGetCFCheckpt returns a new bitcoin getcfcheckpt message that conforms
// to the Message interface using the passed parameters and defaults for the
// remaining fields. | [
"NewMsgGetCFCheckpt",
"returns",
"a",
"new",
"bitcoin",
"getcfcheckpt",
"message",
"that",
"conforms",
"to",
"the",
"Message",
"interface",
"using",
"the",
"passed",
"parameters",
"and",
"defaults",
"for",
"the",
"remaining",
"fields",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msggetcfcheckpt.go#L59-L64 | train |
btcsuite/btcd | rpcadapters.go | ToPeer | func (p *rpcPeer) ToPeer() *peer.Peer {
if p == nil {
return nil
}
return (*serverPeer)(p).Peer
} | go | func (p *rpcPeer) ToPeer() *peer.Peer {
if p == nil {
return nil
}
return (*serverPeer)(p).Peer
} | [
"func",
"(",
"p",
"*",
"rpcPeer",
")",
"ToPeer",
"(",
")",
"*",
"peer",
".",
"Peer",
"{",
"if",
"p",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"(",
"*",
"serverPeer",
")",
"(",
"p",
")",
".",
"Peer",
"\n",
"}"
] | // ToPeer returns the underlying peer instance.
//
// This function is safe for concurrent access and is part of the rpcserverPeer
// interface implementation. | [
"ToPeer",
"returns",
"the",
"underlying",
"peer",
"instance",
".",
"This",
"function",
"is",
"safe",
"for",
"concurrent",
"access",
"and",
"is",
"part",
"of",
"the",
"rpcserverPeer",
"interface",
"implementation",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcadapters.go#L30-L35 | train |
btcsuite/btcd | rpcadapters.go | Connect | func (cm *rpcConnManager) Connect(addr string, permanent bool) error {
replyChan := make(chan error)
cm.server.query <- connectNodeMsg{
addr: addr,
permanent: permanent,
reply: replyChan,
}
return <-replyChan
} | go | func (cm *rpcConnManager) Connect(addr string, permanent bool) error {
replyChan := make(chan error)
cm.server.query <- connectNodeMsg{
addr: addr,
permanent: permanent,
reply: replyChan,
}
return <-replyChan
} | [
"func",
"(",
"cm",
"*",
"rpcConnManager",
")",
"Connect",
"(",
"addr",
"string",
",",
"permanent",
"bool",
")",
"error",
"{",
"replyChan",
":=",
"make",
"(",
"chan",
"error",
")",
"\n",
"cm",
".",
"server",
".",
"query",
"<-",
"connectNodeMsg",
"{",
"addr",
":",
"addr",
",",
"permanent",
":",
"permanent",
",",
"reply",
":",
"replyChan",
",",
"}",
"\n",
"return",
"<-",
"replyChan",
"\n",
"}"
] | // Connect adds the provided address as a new outbound peer. The permanent flag
// indicates whether or not to make the peer persistent and reconnect if the
// connection is lost. Attempting to connect to an already existing peer will
// return an error.
//
// This function is safe for concurrent access and is part of the
// rpcserverConnManager interface implementation. | [
"Connect",
"adds",
"the",
"provided",
"address",
"as",
"a",
"new",
"outbound",
"peer",
".",
"The",
"permanent",
"flag",
"indicates",
"whether",
"or",
"not",
"to",
"make",
"the",
"peer",
"persistent",
"and",
"reconnect",
"if",
"the",
"connection",
"is",
"lost",
".",
"Attempting",
"to",
"connect",
"to",
"an",
"already",
"existing",
"peer",
"will",
"return",
"an",
"error",
".",
"This",
"function",
"is",
"safe",
"for",
"concurrent",
"access",
"and",
"is",
"part",
"of",
"the",
"rpcserverConnManager",
"interface",
"implementation",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcadapters.go#L80-L88 | train |
btcsuite/btcd | rpcadapters.go | RemoveByID | func (cm *rpcConnManager) RemoveByID(id int32) error {
replyChan := make(chan error)
cm.server.query <- removeNodeMsg{
cmp: func(sp *serverPeer) bool { return sp.ID() == id },
reply: replyChan,
}
return <-replyChan
} | go | func (cm *rpcConnManager) RemoveByID(id int32) error {
replyChan := make(chan error)
cm.server.query <- removeNodeMsg{
cmp: func(sp *serverPeer) bool { return sp.ID() == id },
reply: replyChan,
}
return <-replyChan
} | [
"func",
"(",
"cm",
"*",
"rpcConnManager",
")",
"RemoveByID",
"(",
"id",
"int32",
")",
"error",
"{",
"replyChan",
":=",
"make",
"(",
"chan",
"error",
")",
"\n",
"cm",
".",
"server",
".",
"query",
"<-",
"removeNodeMsg",
"{",
"cmp",
":",
"func",
"(",
"sp",
"*",
"serverPeer",
")",
"bool",
"{",
"return",
"sp",
".",
"ID",
"(",
")",
"==",
"id",
"}",
",",
"reply",
":",
"replyChan",
",",
"}",
"\n",
"return",
"<-",
"replyChan",
"\n",
"}"
] | // RemoveByID removes the peer associated with the provided id from the list of
// persistent peers. Attempting to remove an id that does not exist will return
// an error.
//
// This function is safe for concurrent access and is part of the
// rpcserverConnManager interface implementation. | [
"RemoveByID",
"removes",
"the",
"peer",
"associated",
"with",
"the",
"provided",
"id",
"from",
"the",
"list",
"of",
"persistent",
"peers",
".",
"Attempting",
"to",
"remove",
"an",
"id",
"that",
"does",
"not",
"exist",
"will",
"return",
"an",
"error",
".",
"This",
"function",
"is",
"safe",
"for",
"concurrent",
"access",
"and",
"is",
"part",
"of",
"the",
"rpcserverConnManager",
"interface",
"implementation",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcadapters.go#L96-L103 | train |
btcsuite/btcd | rpcadapters.go | RemoveByAddr | func (cm *rpcConnManager) RemoveByAddr(addr string) error {
replyChan := make(chan error)
cm.server.query <- removeNodeMsg{
cmp: func(sp *serverPeer) bool { return sp.Addr() == addr },
reply: replyChan,
}
return <-replyChan
} | go | func (cm *rpcConnManager) RemoveByAddr(addr string) error {
replyChan := make(chan error)
cm.server.query <- removeNodeMsg{
cmp: func(sp *serverPeer) bool { return sp.Addr() == addr },
reply: replyChan,
}
return <-replyChan
} | [
"func",
"(",
"cm",
"*",
"rpcConnManager",
")",
"RemoveByAddr",
"(",
"addr",
"string",
")",
"error",
"{",
"replyChan",
":=",
"make",
"(",
"chan",
"error",
")",
"\n",
"cm",
".",
"server",
".",
"query",
"<-",
"removeNodeMsg",
"{",
"cmp",
":",
"func",
"(",
"sp",
"*",
"serverPeer",
")",
"bool",
"{",
"return",
"sp",
".",
"Addr",
"(",
")",
"==",
"addr",
"}",
",",
"reply",
":",
"replyChan",
",",
"}",
"\n",
"return",
"<-",
"replyChan",
"\n",
"}"
] | // RemoveByAddr removes the peer associated with the provided address from the
// list of persistent peers. Attempting to remove an address that does not
// exist will return an error.
//
// This function is safe for concurrent access and is part of the
// rpcserverConnManager interface implementation. | [
"RemoveByAddr",
"removes",
"the",
"peer",
"associated",
"with",
"the",
"provided",
"address",
"from",
"the",
"list",
"of",
"persistent",
"peers",
".",
"Attempting",
"to",
"remove",
"an",
"address",
"that",
"does",
"not",
"exist",
"will",
"return",
"an",
"error",
".",
"This",
"function",
"is",
"safe",
"for",
"concurrent",
"access",
"and",
"is",
"part",
"of",
"the",
"rpcserverConnManager",
"interface",
"implementation",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcadapters.go#L111-L118 | train |
btcsuite/btcd | rpcadapters.go | DisconnectByID | func (cm *rpcConnManager) DisconnectByID(id int32) error {
replyChan := make(chan error)
cm.server.query <- disconnectNodeMsg{
cmp: func(sp *serverPeer) bool { return sp.ID() == id },
reply: replyChan,
}
return <-replyChan
} | go | func (cm *rpcConnManager) DisconnectByID(id int32) error {
replyChan := make(chan error)
cm.server.query <- disconnectNodeMsg{
cmp: func(sp *serverPeer) bool { return sp.ID() == id },
reply: replyChan,
}
return <-replyChan
} | [
"func",
"(",
"cm",
"*",
"rpcConnManager",
")",
"DisconnectByID",
"(",
"id",
"int32",
")",
"error",
"{",
"replyChan",
":=",
"make",
"(",
"chan",
"error",
")",
"\n",
"cm",
".",
"server",
".",
"query",
"<-",
"disconnectNodeMsg",
"{",
"cmp",
":",
"func",
"(",
"sp",
"*",
"serverPeer",
")",
"bool",
"{",
"return",
"sp",
".",
"ID",
"(",
")",
"==",
"id",
"}",
",",
"reply",
":",
"replyChan",
",",
"}",
"\n",
"return",
"<-",
"replyChan",
"\n",
"}"
] | // DisconnectByID disconnects the peer associated with the provided id. This
// applies to both inbound and outbound peers. Attempting to remove an id that
// does not exist will return an error.
//
// This function is safe for concurrent access and is part of the
// rpcserverConnManager interface implementation. | [
"DisconnectByID",
"disconnects",
"the",
"peer",
"associated",
"with",
"the",
"provided",
"id",
".",
"This",
"applies",
"to",
"both",
"inbound",
"and",
"outbound",
"peers",
".",
"Attempting",
"to",
"remove",
"an",
"id",
"that",
"does",
"not",
"exist",
"will",
"return",
"an",
"error",
".",
"This",
"function",
"is",
"safe",
"for",
"concurrent",
"access",
"and",
"is",
"part",
"of",
"the",
"rpcserverConnManager",
"interface",
"implementation",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcadapters.go#L126-L133 | train |
btcsuite/btcd | rpcadapters.go | DisconnectByAddr | func (cm *rpcConnManager) DisconnectByAddr(addr string) error {
replyChan := make(chan error)
cm.server.query <- disconnectNodeMsg{
cmp: func(sp *serverPeer) bool { return sp.Addr() == addr },
reply: replyChan,
}
return <-replyChan
} | go | func (cm *rpcConnManager) DisconnectByAddr(addr string) error {
replyChan := make(chan error)
cm.server.query <- disconnectNodeMsg{
cmp: func(sp *serverPeer) bool { return sp.Addr() == addr },
reply: replyChan,
}
return <-replyChan
} | [
"func",
"(",
"cm",
"*",
"rpcConnManager",
")",
"DisconnectByAddr",
"(",
"addr",
"string",
")",
"error",
"{",
"replyChan",
":=",
"make",
"(",
"chan",
"error",
")",
"\n",
"cm",
".",
"server",
".",
"query",
"<-",
"disconnectNodeMsg",
"{",
"cmp",
":",
"func",
"(",
"sp",
"*",
"serverPeer",
")",
"bool",
"{",
"return",
"sp",
".",
"Addr",
"(",
")",
"==",
"addr",
"}",
",",
"reply",
":",
"replyChan",
",",
"}",
"\n",
"return",
"<-",
"replyChan",
"\n",
"}"
] | // DisconnectByAddr disconnects the peer associated with the provided address.
// This applies to both inbound and outbound peers. Attempting to remove an
// address that does not exist will return an error.
//
// This function is safe for concurrent access and is part of the
// rpcserverConnManager interface implementation. | [
"DisconnectByAddr",
"disconnects",
"the",
"peer",
"associated",
"with",
"the",
"provided",
"address",
".",
"This",
"applies",
"to",
"both",
"inbound",
"and",
"outbound",
"peers",
".",
"Attempting",
"to",
"remove",
"an",
"address",
"that",
"does",
"not",
"exist",
"will",
"return",
"an",
"error",
".",
"This",
"function",
"is",
"safe",
"for",
"concurrent",
"access",
"and",
"is",
"part",
"of",
"the",
"rpcserverConnManager",
"interface",
"implementation",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcadapters.go#L141-L148 | train |
btcsuite/btcd | rpcadapters.go | ConnectedPeers | func (cm *rpcConnManager) ConnectedPeers() []rpcserverPeer {
replyChan := make(chan []*serverPeer)
cm.server.query <- getPeersMsg{reply: replyChan}
serverPeers := <-replyChan
// Convert to RPC server peers.
peers := make([]rpcserverPeer, 0, len(serverPeers))
for _, sp := range serverPeers {
peers = append(peers, (*rpcPeer)(sp))
}
return peers
} | go | func (cm *rpcConnManager) ConnectedPeers() []rpcserverPeer {
replyChan := make(chan []*serverPeer)
cm.server.query <- getPeersMsg{reply: replyChan}
serverPeers := <-replyChan
// Convert to RPC server peers.
peers := make([]rpcserverPeer, 0, len(serverPeers))
for _, sp := range serverPeers {
peers = append(peers, (*rpcPeer)(sp))
}
return peers
} | [
"func",
"(",
"cm",
"*",
"rpcConnManager",
")",
"ConnectedPeers",
"(",
")",
"[",
"]",
"rpcserverPeer",
"{",
"replyChan",
":=",
"make",
"(",
"chan",
"[",
"]",
"*",
"serverPeer",
")",
"\n",
"cm",
".",
"server",
".",
"query",
"<-",
"getPeersMsg",
"{",
"reply",
":",
"replyChan",
"}",
"\n",
"serverPeers",
":=",
"<-",
"replyChan",
"\n\n",
"// Convert to RPC server peers.",
"peers",
":=",
"make",
"(",
"[",
"]",
"rpcserverPeer",
",",
"0",
",",
"len",
"(",
"serverPeers",
")",
")",
"\n",
"for",
"_",
",",
"sp",
":=",
"range",
"serverPeers",
"{",
"peers",
"=",
"append",
"(",
"peers",
",",
"(",
"*",
"rpcPeer",
")",
"(",
"sp",
")",
")",
"\n",
"}",
"\n",
"return",
"peers",
"\n",
"}"
] | // ConnectedPeers returns an array consisting of all connected peers.
//
// This function is safe for concurrent access and is part of the
// rpcserverConnManager interface implementation. | [
"ConnectedPeers",
"returns",
"an",
"array",
"consisting",
"of",
"all",
"connected",
"peers",
".",
"This",
"function",
"is",
"safe",
"for",
"concurrent",
"access",
"and",
"is",
"part",
"of",
"the",
"rpcserverConnManager",
"interface",
"implementation",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcadapters.go#L171-L182 | train |
btcsuite/btcd | rpcadapters.go | BroadcastMessage | func (cm *rpcConnManager) BroadcastMessage(msg wire.Message) {
cm.server.BroadcastMessage(msg)
} | go | func (cm *rpcConnManager) BroadcastMessage(msg wire.Message) {
cm.server.BroadcastMessage(msg)
} | [
"func",
"(",
"cm",
"*",
"rpcConnManager",
")",
"BroadcastMessage",
"(",
"msg",
"wire",
".",
"Message",
")",
"{",
"cm",
".",
"server",
".",
"BroadcastMessage",
"(",
"msg",
")",
"\n",
"}"
] | // BroadcastMessage sends the provided message to all currently connected peers.
//
// This function is safe for concurrent access and is part of the
// rpcserverConnManager interface implementation. | [
"BroadcastMessage",
"sends",
"the",
"provided",
"message",
"to",
"all",
"currently",
"connected",
"peers",
".",
"This",
"function",
"is",
"safe",
"for",
"concurrent",
"access",
"and",
"is",
"part",
"of",
"the",
"rpcserverConnManager",
"interface",
"implementation",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcadapters.go#L206-L208 | train |
btcsuite/btcd | rpcadapters.go | AddRebroadcastInventory | func (cm *rpcConnManager) AddRebroadcastInventory(iv *wire.InvVect, data interface{}) {
cm.server.AddRebroadcastInventory(iv, data)
} | go | func (cm *rpcConnManager) AddRebroadcastInventory(iv *wire.InvVect, data interface{}) {
cm.server.AddRebroadcastInventory(iv, data)
} | [
"func",
"(",
"cm",
"*",
"rpcConnManager",
")",
"AddRebroadcastInventory",
"(",
"iv",
"*",
"wire",
".",
"InvVect",
",",
"data",
"interface",
"{",
"}",
")",
"{",
"cm",
".",
"server",
".",
"AddRebroadcastInventory",
"(",
"iv",
",",
"data",
")",
"\n",
"}"
] | // AddRebroadcastInventory adds the provided inventory to the list of
// inventories to be rebroadcast at random intervals until they show up in a
// block.
//
// This function is safe for concurrent access and is part of the
// rpcserverConnManager interface implementation. | [
"AddRebroadcastInventory",
"adds",
"the",
"provided",
"inventory",
"to",
"the",
"list",
"of",
"inventories",
"to",
"be",
"rebroadcast",
"at",
"random",
"intervals",
"until",
"they",
"show",
"up",
"in",
"a",
"block",
".",
"This",
"function",
"is",
"safe",
"for",
"concurrent",
"access",
"and",
"is",
"part",
"of",
"the",
"rpcserverConnManager",
"interface",
"implementation",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcadapters.go#L216-L218 | train |
btcsuite/btcd | rpcadapters.go | RelayTransactions | func (cm *rpcConnManager) RelayTransactions(txns []*mempool.TxDesc) {
cm.server.relayTransactions(txns)
} | go | func (cm *rpcConnManager) RelayTransactions(txns []*mempool.TxDesc) {
cm.server.relayTransactions(txns)
} | [
"func",
"(",
"cm",
"*",
"rpcConnManager",
")",
"RelayTransactions",
"(",
"txns",
"[",
"]",
"*",
"mempool",
".",
"TxDesc",
")",
"{",
"cm",
".",
"server",
".",
"relayTransactions",
"(",
"txns",
")",
"\n",
"}"
] | // RelayTransactions generates and relays inventory vectors for all of the
// passed transactions to all connected peers. | [
"RelayTransactions",
"generates",
"and",
"relays",
"inventory",
"vectors",
"for",
"all",
"of",
"the",
"passed",
"transactions",
"to",
"all",
"connected",
"peers",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcadapters.go#L222-L224 | train |
btcsuite/btcd | rpcadapters.go | SubmitBlock | func (b *rpcSyncMgr) SubmitBlock(block *btcutil.Block, flags blockchain.BehaviorFlags) (bool, error) {
return b.syncMgr.ProcessBlock(block, flags)
} | go | func (b *rpcSyncMgr) SubmitBlock(block *btcutil.Block, flags blockchain.BehaviorFlags) (bool, error) {
return b.syncMgr.ProcessBlock(block, flags)
} | [
"func",
"(",
"b",
"*",
"rpcSyncMgr",
")",
"SubmitBlock",
"(",
"block",
"*",
"btcutil",
".",
"Block",
",",
"flags",
"blockchain",
".",
"BehaviorFlags",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"b",
".",
"syncMgr",
".",
"ProcessBlock",
"(",
"block",
",",
"flags",
")",
"\n",
"}"
] | // SubmitBlock submits the provided block to the network after processing it
// locally.
//
// This function is safe for concurrent access and is part of the
// rpcserverSyncManager interface implementation. | [
"SubmitBlock",
"submits",
"the",
"provided",
"block",
"to",
"the",
"network",
"after",
"processing",
"it",
"locally",
".",
"This",
"function",
"is",
"safe",
"for",
"concurrent",
"access",
"and",
"is",
"part",
"of",
"the",
"rpcserverSyncManager",
"interface",
"implementation",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcadapters.go#L250-L252 | train |
btcsuite/btcd | rpcadapters.go | LocateHeaders | func (b *rpcSyncMgr) LocateHeaders(locators []*chainhash.Hash, hashStop *chainhash.Hash) []wire.BlockHeader {
return b.server.chain.LocateHeaders(locators, hashStop)
} | go | func (b *rpcSyncMgr) LocateHeaders(locators []*chainhash.Hash, hashStop *chainhash.Hash) []wire.BlockHeader {
return b.server.chain.LocateHeaders(locators, hashStop)
} | [
"func",
"(",
"b",
"*",
"rpcSyncMgr",
")",
"LocateHeaders",
"(",
"locators",
"[",
"]",
"*",
"chainhash",
".",
"Hash",
",",
"hashStop",
"*",
"chainhash",
".",
"Hash",
")",
"[",
"]",
"wire",
".",
"BlockHeader",
"{",
"return",
"b",
".",
"server",
".",
"chain",
".",
"LocateHeaders",
"(",
"locators",
",",
"hashStop",
")",
"\n",
"}"
] | // LocateBlocks returns the hashes of the blocks after the first known block in
// the provided locators until the provided stop hash or the current tip is
// reached, up to a max of wire.MaxBlockHeadersPerMsg hashes.
//
// This function is safe for concurrent access and is part of the
// rpcserverSyncManager interface implementation. | [
"LocateBlocks",
"returns",
"the",
"hashes",
"of",
"the",
"blocks",
"after",
"the",
"first",
"known",
"block",
"in",
"the",
"provided",
"locators",
"until",
"the",
"provided",
"stop",
"hash",
"or",
"the",
"current",
"tip",
"is",
"reached",
"up",
"to",
"a",
"max",
"of",
"wire",
".",
"MaxBlockHeadersPerMsg",
"hashes",
".",
"This",
"function",
"is",
"safe",
"for",
"concurrent",
"access",
"and",
"is",
"part",
"of",
"the",
"rpcserverSyncManager",
"interface",
"implementation",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcadapters.go#L277-L279 | train |
btcsuite/btcd | wire/msgmerkleblock.go | AddTxHash | func (msg *MsgMerkleBlock) AddTxHash(hash *chainhash.Hash) error {
if len(msg.Hashes)+1 > maxTxPerBlock {
str := fmt.Sprintf("too many tx hashes for message [max %v]",
maxTxPerBlock)
return messageError("MsgMerkleBlock.AddTxHash", str)
}
msg.Hashes = append(msg.Hashes, hash)
return nil
} | go | func (msg *MsgMerkleBlock) AddTxHash(hash *chainhash.Hash) error {
if len(msg.Hashes)+1 > maxTxPerBlock {
str := fmt.Sprintf("too many tx hashes for message [max %v]",
maxTxPerBlock)
return messageError("MsgMerkleBlock.AddTxHash", str)
}
msg.Hashes = append(msg.Hashes, hash)
return nil
} | [
"func",
"(",
"msg",
"*",
"MsgMerkleBlock",
")",
"AddTxHash",
"(",
"hash",
"*",
"chainhash",
".",
"Hash",
")",
"error",
"{",
"if",
"len",
"(",
"msg",
".",
"Hashes",
")",
"+",
"1",
">",
"maxTxPerBlock",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"maxTxPerBlock",
")",
"\n",
"return",
"messageError",
"(",
"\"",
"\"",
",",
"str",
")",
"\n",
"}",
"\n\n",
"msg",
".",
"Hashes",
"=",
"append",
"(",
"msg",
".",
"Hashes",
",",
"hash",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // AddTxHash adds a new transaction hash to the message. | [
"AddTxHash",
"adds",
"a",
"new",
"transaction",
"hash",
"to",
"the",
"message",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgmerkleblock.go#L32-L41 | train |
btcsuite/btcd | wire/msgmerkleblock.go | NewMsgMerkleBlock | func NewMsgMerkleBlock(bh *BlockHeader) *MsgMerkleBlock {
return &MsgMerkleBlock{
Header: *bh,
Transactions: 0,
Hashes: make([]*chainhash.Hash, 0),
Flags: make([]byte, 0),
}
} | go | func NewMsgMerkleBlock(bh *BlockHeader) *MsgMerkleBlock {
return &MsgMerkleBlock{
Header: *bh,
Transactions: 0,
Hashes: make([]*chainhash.Hash, 0),
Flags: make([]byte, 0),
}
} | [
"func",
"NewMsgMerkleBlock",
"(",
"bh",
"*",
"BlockHeader",
")",
"*",
"MsgMerkleBlock",
"{",
"return",
"&",
"MsgMerkleBlock",
"{",
"Header",
":",
"*",
"bh",
",",
"Transactions",
":",
"0",
",",
"Hashes",
":",
"make",
"(",
"[",
"]",
"*",
"chainhash",
".",
"Hash",
",",
"0",
")",
",",
"Flags",
":",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
")",
",",
"}",
"\n",
"}"
] | // NewMsgMerkleBlock returns a new bitcoin merkleblock message that conforms to
// the Message interface. See MsgMerkleBlock for details. | [
"NewMsgMerkleBlock",
"returns",
"a",
"new",
"bitcoin",
"merkleblock",
"message",
"that",
"conforms",
"to",
"the",
"Message",
"interface",
".",
"See",
"MsgMerkleBlock",
"for",
"details",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgmerkleblock.go#L152-L159 | train |
btcsuite/btcd | wire/invvect.go | String | func (invtype InvType) String() string {
if s, ok := ivStrings[invtype]; ok {
return s
}
return fmt.Sprintf("Unknown InvType (%d)", uint32(invtype))
} | go | func (invtype InvType) String() string {
if s, ok := ivStrings[invtype]; ok {
return s
}
return fmt.Sprintf("Unknown InvType (%d)", uint32(invtype))
} | [
"func",
"(",
"invtype",
"InvType",
")",
"String",
"(",
")",
"string",
"{",
"if",
"s",
",",
"ok",
":=",
"ivStrings",
"[",
"invtype",
"]",
";",
"ok",
"{",
"return",
"s",
"\n",
"}",
"\n\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"uint32",
"(",
"invtype",
")",
")",
"\n",
"}"
] | // String returns the InvType in human-readable form. | [
"String",
"returns",
"the",
"InvType",
"in",
"human",
"-",
"readable",
"form",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/invvect.go#L53-L59 | train |
btcsuite/btcd | wire/invvect.go | NewInvVect | func NewInvVect(typ InvType, hash *chainhash.Hash) *InvVect {
return &InvVect{
Type: typ,
Hash: *hash,
}
} | go | func NewInvVect(typ InvType, hash *chainhash.Hash) *InvVect {
return &InvVect{
Type: typ,
Hash: *hash,
}
} | [
"func",
"NewInvVect",
"(",
"typ",
"InvType",
",",
"hash",
"*",
"chainhash",
".",
"Hash",
")",
"*",
"InvVect",
"{",
"return",
"&",
"InvVect",
"{",
"Type",
":",
"typ",
",",
"Hash",
":",
"*",
"hash",
",",
"}",
"\n",
"}"
] | // NewInvVect returns a new InvVect using the provided type and hash. | [
"NewInvVect",
"returns",
"a",
"new",
"InvVect",
"using",
"the",
"provided",
"type",
"and",
"hash",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/invvect.go#L70-L75 | train |
btcsuite/btcd | wire/invvect.go | readInvVect | func readInvVect(r io.Reader, pver uint32, iv *InvVect) error {
return readElements(r, &iv.Type, &iv.Hash)
} | go | func readInvVect(r io.Reader, pver uint32, iv *InvVect) error {
return readElements(r, &iv.Type, &iv.Hash)
} | [
"func",
"readInvVect",
"(",
"r",
"io",
".",
"Reader",
",",
"pver",
"uint32",
",",
"iv",
"*",
"InvVect",
")",
"error",
"{",
"return",
"readElements",
"(",
"r",
",",
"&",
"iv",
".",
"Type",
",",
"&",
"iv",
".",
"Hash",
")",
"\n",
"}"
] | // readInvVect reads an encoded InvVect from r depending on the protocol
// version. | [
"readInvVect",
"reads",
"an",
"encoded",
"InvVect",
"from",
"r",
"depending",
"on",
"the",
"protocol",
"version",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/invvect.go#L79-L81 | train |
btcsuite/btcd | wire/invvect.go | writeInvVect | func writeInvVect(w io.Writer, pver uint32, iv *InvVect) error {
return writeElements(w, iv.Type, &iv.Hash)
} | go | func writeInvVect(w io.Writer, pver uint32, iv *InvVect) error {
return writeElements(w, iv.Type, &iv.Hash)
} | [
"func",
"writeInvVect",
"(",
"w",
"io",
".",
"Writer",
",",
"pver",
"uint32",
",",
"iv",
"*",
"InvVect",
")",
"error",
"{",
"return",
"writeElements",
"(",
"w",
",",
"iv",
".",
"Type",
",",
"&",
"iv",
".",
"Hash",
")",
"\n",
"}"
] | // writeInvVect serializes an InvVect to w depending on the protocol version. | [
"writeInvVect",
"serializes",
"an",
"InvVect",
"to",
"w",
"depending",
"on",
"the",
"protocol",
"version",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/invvect.go#L84-L86 | train |
btcsuite/btcd | btcec/btcec.go | moduloReduce | func (curve *KoblitzCurve) moduloReduce(k []byte) []byte {
// Since the order of G is curve.N, we can use a much smaller number
// by doing modulo curve.N
if len(k) > curve.byteSize {
// Reduce k by performing modulo curve.N.
tmpK := new(big.Int).SetBytes(k)
tmpK.Mod(tmpK, curve.N)
return tmpK.Bytes()
}
return k
} | go | func (curve *KoblitzCurve) moduloReduce(k []byte) []byte {
// Since the order of G is curve.N, we can use a much smaller number
// by doing modulo curve.N
if len(k) > curve.byteSize {
// Reduce k by performing modulo curve.N.
tmpK := new(big.Int).SetBytes(k)
tmpK.Mod(tmpK, curve.N)
return tmpK.Bytes()
}
return k
} | [
"func",
"(",
"curve",
"*",
"KoblitzCurve",
")",
"moduloReduce",
"(",
"k",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"// Since the order of G is curve.N, we can use a much smaller number",
"// by doing modulo curve.N",
"if",
"len",
"(",
"k",
")",
">",
"curve",
".",
"byteSize",
"{",
"// Reduce k by performing modulo curve.N.",
"tmpK",
":=",
"new",
"(",
"big",
".",
"Int",
")",
".",
"SetBytes",
"(",
"k",
")",
"\n",
"tmpK",
".",
"Mod",
"(",
"tmpK",
",",
"curve",
".",
"N",
")",
"\n",
"return",
"tmpK",
".",
"Bytes",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"k",
"\n",
"}"
] | // moduloReduce reduces k from more than 32 bytes to 32 bytes and under. This
// is done by doing a simple modulo curve.N. We can do this since G^N = 1 and
// thus any other valid point on the elliptic curve has the same order. | [
"moduloReduce",
"reduces",
"k",
"from",
"more",
"than",
"32",
"bytes",
"to",
"32",
"bytes",
"and",
"under",
".",
"This",
"is",
"done",
"by",
"doing",
"a",
"simple",
"modulo",
"curve",
".",
"N",
".",
"We",
"can",
"do",
"this",
"since",
"G^N",
"=",
"1",
"and",
"thus",
"any",
"other",
"valid",
"point",
"on",
"the",
"elliptic",
"curve",
"has",
"the",
"same",
"order",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/btcec.go#L666-L677 | train |
btcsuite/btcd | wire/netaddress.go | maxNetAddressPayload | func maxNetAddressPayload(pver uint32) uint32 {
// Services 8 bytes + ip 16 bytes + port 2 bytes.
plen := uint32(26)
// NetAddressTimeVersion added a timestamp field.
if pver >= NetAddressTimeVersion {
// Timestamp 4 bytes.
plen += 4
}
return plen
} | go | func maxNetAddressPayload(pver uint32) uint32 {
// Services 8 bytes + ip 16 bytes + port 2 bytes.
plen := uint32(26)
// NetAddressTimeVersion added a timestamp field.
if pver >= NetAddressTimeVersion {
// Timestamp 4 bytes.
plen += 4
}
return plen
} | [
"func",
"maxNetAddressPayload",
"(",
"pver",
"uint32",
")",
"uint32",
"{",
"// Services 8 bytes + ip 16 bytes + port 2 bytes.",
"plen",
":=",
"uint32",
"(",
"26",
")",
"\n\n",
"// NetAddressTimeVersion added a timestamp field.",
"if",
"pver",
">=",
"NetAddressTimeVersion",
"{",
"// Timestamp 4 bytes.",
"plen",
"+=",
"4",
"\n",
"}",
"\n\n",
"return",
"plen",
"\n",
"}"
] | // maxNetAddressPayload returns the max payload size for a bitcoin NetAddress
// based on the protocol version. | [
"maxNetAddressPayload",
"returns",
"the",
"max",
"payload",
"size",
"for",
"a",
"bitcoin",
"NetAddress",
"based",
"on",
"the",
"protocol",
"version",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/netaddress.go#L16-L27 | train |
btcsuite/btcd | wire/netaddress.go | HasService | func (na *NetAddress) HasService(service ServiceFlag) bool {
return na.Services&service == service
} | go | func (na *NetAddress) HasService(service ServiceFlag) bool {
return na.Services&service == service
} | [
"func",
"(",
"na",
"*",
"NetAddress",
")",
"HasService",
"(",
"service",
"ServiceFlag",
")",
"bool",
"{",
"return",
"na",
".",
"Services",
"&",
"service",
"==",
"service",
"\n",
"}"
] | // HasService returns whether the specified service is supported by the address. | [
"HasService",
"returns",
"whether",
"the",
"specified",
"service",
"is",
"supported",
"by",
"the",
"address",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/netaddress.go#L50-L52 | train |
btcsuite/btcd | wire/netaddress.go | NewNetAddressIPPort | func NewNetAddressIPPort(ip net.IP, port uint16, services ServiceFlag) *NetAddress {
return NewNetAddressTimestamp(time.Now(), services, ip, port)
} | go | func NewNetAddressIPPort(ip net.IP, port uint16, services ServiceFlag) *NetAddress {
return NewNetAddressTimestamp(time.Now(), services, ip, port)
} | [
"func",
"NewNetAddressIPPort",
"(",
"ip",
"net",
".",
"IP",
",",
"port",
"uint16",
",",
"services",
"ServiceFlag",
")",
"*",
"NetAddress",
"{",
"return",
"NewNetAddressTimestamp",
"(",
"time",
".",
"Now",
"(",
")",
",",
"services",
",",
"ip",
",",
"port",
")",
"\n",
"}"
] | // NewNetAddressIPPort returns a new NetAddress using the provided IP, port, and
// supported services with defaults for the remaining fields. | [
"NewNetAddressIPPort",
"returns",
"a",
"new",
"NetAddress",
"using",
"the",
"provided",
"IP",
"port",
"and",
"supported",
"services",
"with",
"defaults",
"for",
"the",
"remaining",
"fields",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/netaddress.go#L62-L64 | train |
btcsuite/btcd | wire/netaddress.go | NewNetAddressTimestamp | func NewNetAddressTimestamp(
timestamp time.Time, services ServiceFlag, ip net.IP, port uint16) *NetAddress {
// Limit the timestamp to one second precision since the protocol
// doesn't support better.
na := NetAddress{
Timestamp: time.Unix(timestamp.Unix(), 0),
Services: services,
IP: ip,
Port: port,
}
return &na
} | go | func NewNetAddressTimestamp(
timestamp time.Time, services ServiceFlag, ip net.IP, port uint16) *NetAddress {
// Limit the timestamp to one second precision since the protocol
// doesn't support better.
na := NetAddress{
Timestamp: time.Unix(timestamp.Unix(), 0),
Services: services,
IP: ip,
Port: port,
}
return &na
} | [
"func",
"NewNetAddressTimestamp",
"(",
"timestamp",
"time",
".",
"Time",
",",
"services",
"ServiceFlag",
",",
"ip",
"net",
".",
"IP",
",",
"port",
"uint16",
")",
"*",
"NetAddress",
"{",
"// Limit the timestamp to one second precision since the protocol",
"// doesn't support better.",
"na",
":=",
"NetAddress",
"{",
"Timestamp",
":",
"time",
".",
"Unix",
"(",
"timestamp",
".",
"Unix",
"(",
")",
",",
"0",
")",
",",
"Services",
":",
"services",
",",
"IP",
":",
"ip",
",",
"Port",
":",
"port",
",",
"}",
"\n",
"return",
"&",
"na",
"\n",
"}"
] | // NewNetAddressTimestamp returns a new NetAddress using the provided
// timestamp, IP, port, and supported services. The timestamp is rounded to
// single second precision. | [
"NewNetAddressTimestamp",
"returns",
"a",
"new",
"NetAddress",
"using",
"the",
"provided",
"timestamp",
"IP",
"port",
"and",
"supported",
"services",
".",
"The",
"timestamp",
"is",
"rounded",
"to",
"single",
"second",
"precision",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/netaddress.go#L69-L80 | train |
btcsuite/btcd | wire/netaddress.go | NewNetAddress | func NewNetAddress(addr *net.TCPAddr, services ServiceFlag) *NetAddress {
return NewNetAddressIPPort(addr.IP, uint16(addr.Port), services)
} | go | func NewNetAddress(addr *net.TCPAddr, services ServiceFlag) *NetAddress {
return NewNetAddressIPPort(addr.IP, uint16(addr.Port), services)
} | [
"func",
"NewNetAddress",
"(",
"addr",
"*",
"net",
".",
"TCPAddr",
",",
"services",
"ServiceFlag",
")",
"*",
"NetAddress",
"{",
"return",
"NewNetAddressIPPort",
"(",
"addr",
".",
"IP",
",",
"uint16",
"(",
"addr",
".",
"Port",
")",
",",
"services",
")",
"\n",
"}"
] | // NewNetAddress returns a new NetAddress using the provided TCP address and
// supported services with defaults for the remaining fields. | [
"NewNetAddress",
"returns",
"a",
"new",
"NetAddress",
"using",
"the",
"provided",
"TCP",
"address",
"and",
"supported",
"services",
"with",
"defaults",
"for",
"the",
"remaining",
"fields",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/netaddress.go#L84-L86 | train |
btcsuite/btcd | wire/netaddress.go | readNetAddress | func readNetAddress(r io.Reader, pver uint32, na *NetAddress, ts bool) error {
var ip [16]byte
// NOTE: The bitcoin protocol uses a uint32 for the timestamp so it will
// stop working somewhere around 2106. Also timestamp wasn't added until
// protocol version >= NetAddressTimeVersion
if ts && pver >= NetAddressTimeVersion {
err := readElement(r, (*uint32Time)(&na.Timestamp))
if err != nil {
return err
}
}
err := readElements(r, &na.Services, &ip)
if err != nil {
return err
}
// Sigh. Bitcoin protocol mixes little and big endian.
port, err := binarySerializer.Uint16(r, bigEndian)
if err != nil {
return err
}
*na = NetAddress{
Timestamp: na.Timestamp,
Services: na.Services,
IP: net.IP(ip[:]),
Port: port,
}
return nil
} | go | func readNetAddress(r io.Reader, pver uint32, na *NetAddress, ts bool) error {
var ip [16]byte
// NOTE: The bitcoin protocol uses a uint32 for the timestamp so it will
// stop working somewhere around 2106. Also timestamp wasn't added until
// protocol version >= NetAddressTimeVersion
if ts && pver >= NetAddressTimeVersion {
err := readElement(r, (*uint32Time)(&na.Timestamp))
if err != nil {
return err
}
}
err := readElements(r, &na.Services, &ip)
if err != nil {
return err
}
// Sigh. Bitcoin protocol mixes little and big endian.
port, err := binarySerializer.Uint16(r, bigEndian)
if err != nil {
return err
}
*na = NetAddress{
Timestamp: na.Timestamp,
Services: na.Services,
IP: net.IP(ip[:]),
Port: port,
}
return nil
} | [
"func",
"readNetAddress",
"(",
"r",
"io",
".",
"Reader",
",",
"pver",
"uint32",
",",
"na",
"*",
"NetAddress",
",",
"ts",
"bool",
")",
"error",
"{",
"var",
"ip",
"[",
"16",
"]",
"byte",
"\n\n",
"// NOTE: The bitcoin protocol uses a uint32 for the timestamp so it will",
"// stop working somewhere around 2106. Also timestamp wasn't added until",
"// protocol version >= NetAddressTimeVersion",
"if",
"ts",
"&&",
"pver",
">=",
"NetAddressTimeVersion",
"{",
"err",
":=",
"readElement",
"(",
"r",
",",
"(",
"*",
"uint32Time",
")",
"(",
"&",
"na",
".",
"Timestamp",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"err",
":=",
"readElements",
"(",
"r",
",",
"&",
"na",
".",
"Services",
",",
"&",
"ip",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// Sigh. Bitcoin protocol mixes little and big endian.",
"port",
",",
"err",
":=",
"binarySerializer",
".",
"Uint16",
"(",
"r",
",",
"bigEndian",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"*",
"na",
"=",
"NetAddress",
"{",
"Timestamp",
":",
"na",
".",
"Timestamp",
",",
"Services",
":",
"na",
".",
"Services",
",",
"IP",
":",
"net",
".",
"IP",
"(",
"ip",
"[",
":",
"]",
")",
",",
"Port",
":",
"port",
",",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // readNetAddress reads an encoded NetAddress from r depending on the protocol
// version and whether or not the timestamp is included per ts. Some messages
// like version do not include the timestamp. | [
"readNetAddress",
"reads",
"an",
"encoded",
"NetAddress",
"from",
"r",
"depending",
"on",
"the",
"protocol",
"version",
"and",
"whether",
"or",
"not",
"the",
"timestamp",
"is",
"included",
"per",
"ts",
".",
"Some",
"messages",
"like",
"version",
"do",
"not",
"include",
"the",
"timestamp",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/netaddress.go#L91-L121 | train |
btcsuite/btcd | wire/netaddress.go | writeNetAddress | func writeNetAddress(w io.Writer, pver uint32, na *NetAddress, ts bool) error {
// NOTE: The bitcoin protocol uses a uint32 for the timestamp so it will
// stop working somewhere around 2106. Also timestamp wasn't added until
// until protocol version >= NetAddressTimeVersion.
if ts && pver >= NetAddressTimeVersion {
err := writeElement(w, uint32(na.Timestamp.Unix()))
if err != nil {
return err
}
}
// Ensure to always write 16 bytes even if the ip is nil.
var ip [16]byte
if na.IP != nil {
copy(ip[:], na.IP.To16())
}
err := writeElements(w, na.Services, ip)
if err != nil {
return err
}
// Sigh. Bitcoin protocol mixes little and big endian.
return binary.Write(w, bigEndian, na.Port)
} | go | func writeNetAddress(w io.Writer, pver uint32, na *NetAddress, ts bool) error {
// NOTE: The bitcoin protocol uses a uint32 for the timestamp so it will
// stop working somewhere around 2106. Also timestamp wasn't added until
// until protocol version >= NetAddressTimeVersion.
if ts && pver >= NetAddressTimeVersion {
err := writeElement(w, uint32(na.Timestamp.Unix()))
if err != nil {
return err
}
}
// Ensure to always write 16 bytes even if the ip is nil.
var ip [16]byte
if na.IP != nil {
copy(ip[:], na.IP.To16())
}
err := writeElements(w, na.Services, ip)
if err != nil {
return err
}
// Sigh. Bitcoin protocol mixes little and big endian.
return binary.Write(w, bigEndian, na.Port)
} | [
"func",
"writeNetAddress",
"(",
"w",
"io",
".",
"Writer",
",",
"pver",
"uint32",
",",
"na",
"*",
"NetAddress",
",",
"ts",
"bool",
")",
"error",
"{",
"// NOTE: The bitcoin protocol uses a uint32 for the timestamp so it will",
"// stop working somewhere around 2106. Also timestamp wasn't added until",
"// until protocol version >= NetAddressTimeVersion.",
"if",
"ts",
"&&",
"pver",
">=",
"NetAddressTimeVersion",
"{",
"err",
":=",
"writeElement",
"(",
"w",
",",
"uint32",
"(",
"na",
".",
"Timestamp",
".",
"Unix",
"(",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Ensure to always write 16 bytes even if the ip is nil.",
"var",
"ip",
"[",
"16",
"]",
"byte",
"\n",
"if",
"na",
".",
"IP",
"!=",
"nil",
"{",
"copy",
"(",
"ip",
"[",
":",
"]",
",",
"na",
".",
"IP",
".",
"To16",
"(",
")",
")",
"\n",
"}",
"\n",
"err",
":=",
"writeElements",
"(",
"w",
",",
"na",
".",
"Services",
",",
"ip",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Sigh. Bitcoin protocol mixes little and big endian.",
"return",
"binary",
".",
"Write",
"(",
"w",
",",
"bigEndian",
",",
"na",
".",
"Port",
")",
"\n",
"}"
] | // writeNetAddress serializes a NetAddress to w depending on the protocol
// version and whether or not the timestamp is included per ts. Some messages
// like version do not include the timestamp. | [
"writeNetAddress",
"serializes",
"a",
"NetAddress",
"to",
"w",
"depending",
"on",
"the",
"protocol",
"version",
"and",
"whether",
"or",
"not",
"the",
"timestamp",
"is",
"included",
"per",
"ts",
".",
"Some",
"messages",
"like",
"version",
"do",
"not",
"include",
"the",
"timestamp",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/netaddress.go#L126-L149 | train |
btcsuite/btcd | database/driver.go | RegisterDriver | func RegisterDriver(driver Driver) error {
if _, exists := drivers[driver.DbType]; exists {
str := fmt.Sprintf("driver %q is already registered",
driver.DbType)
return makeError(ErrDbTypeRegistered, str, nil)
}
drivers[driver.DbType] = &driver
return nil
} | go | func RegisterDriver(driver Driver) error {
if _, exists := drivers[driver.DbType]; exists {
str := fmt.Sprintf("driver %q is already registered",
driver.DbType)
return makeError(ErrDbTypeRegistered, str, nil)
}
drivers[driver.DbType] = &driver
return nil
} | [
"func",
"RegisterDriver",
"(",
"driver",
"Driver",
")",
"error",
"{",
"if",
"_",
",",
"exists",
":=",
"drivers",
"[",
"driver",
".",
"DbType",
"]",
";",
"exists",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"driver",
".",
"DbType",
")",
"\n",
"return",
"makeError",
"(",
"ErrDbTypeRegistered",
",",
"str",
",",
"nil",
")",
"\n",
"}",
"\n\n",
"drivers",
"[",
"driver",
".",
"DbType",
"]",
"=",
"&",
"driver",
"\n",
"return",
"nil",
"\n",
"}"
] | // RegisterDriver adds a backend database driver to available interfaces.
// ErrDbTypeRegistered will be returned if the database type for the driver has
// already been registered. | [
"RegisterDriver",
"adds",
"a",
"backend",
"database",
"driver",
"to",
"available",
"interfaces",
".",
"ErrDbTypeRegistered",
"will",
"be",
"returned",
"if",
"the",
"database",
"type",
"for",
"the",
"driver",
"has",
"already",
"been",
"registered",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/driver.go#L40-L49 | train |
btcsuite/btcd | database/driver.go | SupportedDrivers | func SupportedDrivers() []string {
supportedDBs := make([]string, 0, len(drivers))
for _, drv := range drivers {
supportedDBs = append(supportedDBs, drv.DbType)
}
return supportedDBs
} | go | func SupportedDrivers() []string {
supportedDBs := make([]string, 0, len(drivers))
for _, drv := range drivers {
supportedDBs = append(supportedDBs, drv.DbType)
}
return supportedDBs
} | [
"func",
"SupportedDrivers",
"(",
")",
"[",
"]",
"string",
"{",
"supportedDBs",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"drivers",
")",
")",
"\n",
"for",
"_",
",",
"drv",
":=",
"range",
"drivers",
"{",
"supportedDBs",
"=",
"append",
"(",
"supportedDBs",
",",
"drv",
".",
"DbType",
")",
"\n",
"}",
"\n",
"return",
"supportedDBs",
"\n",
"}"
] | // SupportedDrivers returns a slice of strings that represent the database
// drivers that have been registered and are therefore supported. | [
"SupportedDrivers",
"returns",
"a",
"slice",
"of",
"strings",
"that",
"represent",
"the",
"database",
"drivers",
"that",
"have",
"been",
"registered",
"and",
"are",
"therefore",
"supported",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/driver.go#L53-L59 | train |
btcsuite/btcd | database/driver.go | Create | func Create(dbType string, args ...interface{}) (DB, error) {
drv, exists := drivers[dbType]
if !exists {
str := fmt.Sprintf("driver %q is not registered", dbType)
return nil, makeError(ErrDbUnknownType, str, nil)
}
return drv.Create(args...)
} | go | func Create(dbType string, args ...interface{}) (DB, error) {
drv, exists := drivers[dbType]
if !exists {
str := fmt.Sprintf("driver %q is not registered", dbType)
return nil, makeError(ErrDbUnknownType, str, nil)
}
return drv.Create(args...)
} | [
"func",
"Create",
"(",
"dbType",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"(",
"DB",
",",
"error",
")",
"{",
"drv",
",",
"exists",
":=",
"drivers",
"[",
"dbType",
"]",
"\n",
"if",
"!",
"exists",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"dbType",
")",
"\n",
"return",
"nil",
",",
"makeError",
"(",
"ErrDbUnknownType",
",",
"str",
",",
"nil",
")",
"\n",
"}",
"\n\n",
"return",
"drv",
".",
"Create",
"(",
"args",
"...",
")",
"\n",
"}"
] | // Create initializes and opens a database for the specified type. The
// arguments are specific to the database type driver. See the documentation
// for the database driver for further details.
//
// ErrDbUnknownType will be returned if the the database type is not registered. | [
"Create",
"initializes",
"and",
"opens",
"a",
"database",
"for",
"the",
"specified",
"type",
".",
"The",
"arguments",
"are",
"specific",
"to",
"the",
"database",
"type",
"driver",
".",
"See",
"the",
"documentation",
"for",
"the",
"database",
"driver",
"for",
"further",
"details",
".",
"ErrDbUnknownType",
"will",
"be",
"returned",
"if",
"the",
"the",
"database",
"type",
"is",
"not",
"registered",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/driver.go#L66-L74 | train |
btcsuite/btcd | connmgr/connmanager.go | updateState | func (c *ConnReq) updateState(state ConnState) {
c.stateMtx.Lock()
c.state = state
c.stateMtx.Unlock()
} | go | func (c *ConnReq) updateState(state ConnState) {
c.stateMtx.Lock()
c.state = state
c.stateMtx.Unlock()
} | [
"func",
"(",
"c",
"*",
"ConnReq",
")",
"updateState",
"(",
"state",
"ConnState",
")",
"{",
"c",
".",
"stateMtx",
".",
"Lock",
"(",
")",
"\n",
"c",
".",
"state",
"=",
"state",
"\n",
"c",
".",
"stateMtx",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // updateState updates the state of the connection request. | [
"updateState",
"updates",
"the",
"state",
"of",
"the",
"connection",
"request",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/connmgr/connmanager.go#L71-L75 | train |
btcsuite/btcd | connmgr/connmanager.go | State | func (c *ConnReq) State() ConnState {
c.stateMtx.RLock()
state := c.state
c.stateMtx.RUnlock()
return state
} | go | func (c *ConnReq) State() ConnState {
c.stateMtx.RLock()
state := c.state
c.stateMtx.RUnlock()
return state
} | [
"func",
"(",
"c",
"*",
"ConnReq",
")",
"State",
"(",
")",
"ConnState",
"{",
"c",
".",
"stateMtx",
".",
"RLock",
"(",
")",
"\n",
"state",
":=",
"c",
".",
"state",
"\n",
"c",
".",
"stateMtx",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"state",
"\n",
"}"
] | // State is the connection state of the requested connection. | [
"State",
"is",
"the",
"connection",
"state",
"of",
"the",
"requested",
"connection",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/connmgr/connmanager.go#L83-L88 | train |
btcsuite/btcd | connmgr/connmanager.go | String | func (c *ConnReq) String() string {
if c.Addr == nil || c.Addr.String() == "" {
return fmt.Sprintf("reqid %d", atomic.LoadUint64(&c.id))
}
return fmt.Sprintf("%s (reqid %d)", c.Addr, atomic.LoadUint64(&c.id))
} | go | func (c *ConnReq) String() string {
if c.Addr == nil || c.Addr.String() == "" {
return fmt.Sprintf("reqid %d", atomic.LoadUint64(&c.id))
}
return fmt.Sprintf("%s (reqid %d)", c.Addr, atomic.LoadUint64(&c.id))
} | [
"func",
"(",
"c",
"*",
"ConnReq",
")",
"String",
"(",
")",
"string",
"{",
"if",
"c",
".",
"Addr",
"==",
"nil",
"||",
"c",
".",
"Addr",
".",
"String",
"(",
")",
"==",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"atomic",
".",
"LoadUint64",
"(",
"&",
"c",
".",
"id",
")",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"c",
".",
"Addr",
",",
"atomic",
".",
"LoadUint64",
"(",
"&",
"c",
".",
"id",
")",
")",
"\n",
"}"
] | // String returns a human-readable string for the connection request. | [
"String",
"returns",
"a",
"human",
"-",
"readable",
"string",
"for",
"the",
"connection",
"request",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/connmgr/connmanager.go#L91-L96 | train |
btcsuite/btcd | connmgr/connmanager.go | handleFailedConn | func (cm *ConnManager) handleFailedConn(c *ConnReq) {
if atomic.LoadInt32(&cm.stop) != 0 {
return
}
if c.Permanent {
c.retryCount++
d := time.Duration(c.retryCount) * cm.cfg.RetryDuration
if d > maxRetryDuration {
d = maxRetryDuration
}
log.Debugf("Retrying connection to %v in %v", c, d)
time.AfterFunc(d, func() {
cm.Connect(c)
})
} else if cm.cfg.GetNewAddress != nil {
cm.failedAttempts++
if cm.failedAttempts >= maxFailedAttempts {
log.Debugf("Max failed connection attempts reached: [%d] "+
"-- retrying connection in: %v", maxFailedAttempts,
cm.cfg.RetryDuration)
time.AfterFunc(cm.cfg.RetryDuration, func() {
cm.NewConnReq()
})
} else {
go cm.NewConnReq()
}
}
} | go | func (cm *ConnManager) handleFailedConn(c *ConnReq) {
if atomic.LoadInt32(&cm.stop) != 0 {
return
}
if c.Permanent {
c.retryCount++
d := time.Duration(c.retryCount) * cm.cfg.RetryDuration
if d > maxRetryDuration {
d = maxRetryDuration
}
log.Debugf("Retrying connection to %v in %v", c, d)
time.AfterFunc(d, func() {
cm.Connect(c)
})
} else if cm.cfg.GetNewAddress != nil {
cm.failedAttempts++
if cm.failedAttempts >= maxFailedAttempts {
log.Debugf("Max failed connection attempts reached: [%d] "+
"-- retrying connection in: %v", maxFailedAttempts,
cm.cfg.RetryDuration)
time.AfterFunc(cm.cfg.RetryDuration, func() {
cm.NewConnReq()
})
} else {
go cm.NewConnReq()
}
}
} | [
"func",
"(",
"cm",
"*",
"ConnManager",
")",
"handleFailedConn",
"(",
"c",
"*",
"ConnReq",
")",
"{",
"if",
"atomic",
".",
"LoadInt32",
"(",
"&",
"cm",
".",
"stop",
")",
"!=",
"0",
"{",
"return",
"\n",
"}",
"\n",
"if",
"c",
".",
"Permanent",
"{",
"c",
".",
"retryCount",
"++",
"\n",
"d",
":=",
"time",
".",
"Duration",
"(",
"c",
".",
"retryCount",
")",
"*",
"cm",
".",
"cfg",
".",
"RetryDuration",
"\n",
"if",
"d",
">",
"maxRetryDuration",
"{",
"d",
"=",
"maxRetryDuration",
"\n",
"}",
"\n",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"c",
",",
"d",
")",
"\n",
"time",
".",
"AfterFunc",
"(",
"d",
",",
"func",
"(",
")",
"{",
"cm",
".",
"Connect",
"(",
"c",
")",
"\n",
"}",
")",
"\n",
"}",
"else",
"if",
"cm",
".",
"cfg",
".",
"GetNewAddress",
"!=",
"nil",
"{",
"cm",
".",
"failedAttempts",
"++",
"\n",
"if",
"cm",
".",
"failedAttempts",
">=",
"maxFailedAttempts",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"maxFailedAttempts",
",",
"cm",
".",
"cfg",
".",
"RetryDuration",
")",
"\n",
"time",
".",
"AfterFunc",
"(",
"cm",
".",
"cfg",
".",
"RetryDuration",
",",
"func",
"(",
")",
"{",
"cm",
".",
"NewConnReq",
"(",
")",
"\n",
"}",
")",
"\n",
"}",
"else",
"{",
"go",
"cm",
".",
"NewConnReq",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // handleFailedConn handles a connection failed due to a disconnect or any
// other failure. If permanent, it retries the connection after the configured
// retry duration. Otherwise, if required, it makes a new connection request.
// After maxFailedConnectionAttempts new connections will be retried after the
// configured retry duration. | [
"handleFailedConn",
"handles",
"a",
"connection",
"failed",
"due",
"to",
"a",
"disconnect",
"or",
"any",
"other",
"failure",
".",
"If",
"permanent",
"it",
"retries",
"the",
"connection",
"after",
"the",
"configured",
"retry",
"duration",
".",
"Otherwise",
"if",
"required",
"it",
"makes",
"a",
"new",
"connection",
"request",
".",
"After",
"maxFailedConnectionAttempts",
"new",
"connections",
"will",
"be",
"retried",
"after",
"the",
"configured",
"retry",
"duration",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/connmgr/connmanager.go#L193-L220 | train |
btcsuite/btcd | connmgr/connmanager.go | NewConnReq | func (cm *ConnManager) NewConnReq() {
if atomic.LoadInt32(&cm.stop) != 0 {
return
}
if cm.cfg.GetNewAddress == nil {
return
}
c := &ConnReq{}
atomic.StoreUint64(&c.id, atomic.AddUint64(&cm.connReqCount, 1))
// Submit a request of a pending connection attempt to the connection
// manager. By registering the id before the connection is even
// established, we'll be able to later cancel the connection via the
// Remove method.
done := make(chan struct{})
select {
case cm.requests <- registerPending{c, done}:
case <-cm.quit:
return
}
// Wait for the registration to successfully add the pending conn req to
// the conn manager's internal state.
select {
case <-done:
case <-cm.quit:
return
}
addr, err := cm.cfg.GetNewAddress()
if err != nil {
select {
case cm.requests <- handleFailed{c, err}:
case <-cm.quit:
}
return
}
c.Addr = addr
cm.Connect(c)
} | go | func (cm *ConnManager) NewConnReq() {
if atomic.LoadInt32(&cm.stop) != 0 {
return
}
if cm.cfg.GetNewAddress == nil {
return
}
c := &ConnReq{}
atomic.StoreUint64(&c.id, atomic.AddUint64(&cm.connReqCount, 1))
// Submit a request of a pending connection attempt to the connection
// manager. By registering the id before the connection is even
// established, we'll be able to later cancel the connection via the
// Remove method.
done := make(chan struct{})
select {
case cm.requests <- registerPending{c, done}:
case <-cm.quit:
return
}
// Wait for the registration to successfully add the pending conn req to
// the conn manager's internal state.
select {
case <-done:
case <-cm.quit:
return
}
addr, err := cm.cfg.GetNewAddress()
if err != nil {
select {
case cm.requests <- handleFailed{c, err}:
case <-cm.quit:
}
return
}
c.Addr = addr
cm.Connect(c)
} | [
"func",
"(",
"cm",
"*",
"ConnManager",
")",
"NewConnReq",
"(",
")",
"{",
"if",
"atomic",
".",
"LoadInt32",
"(",
"&",
"cm",
".",
"stop",
")",
"!=",
"0",
"{",
"return",
"\n",
"}",
"\n",
"if",
"cm",
".",
"cfg",
".",
"GetNewAddress",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"c",
":=",
"&",
"ConnReq",
"{",
"}",
"\n",
"atomic",
".",
"StoreUint64",
"(",
"&",
"c",
".",
"id",
",",
"atomic",
".",
"AddUint64",
"(",
"&",
"cm",
".",
"connReqCount",
",",
"1",
")",
")",
"\n\n",
"// Submit a request of a pending connection attempt to the connection",
"// manager. By registering the id before the connection is even",
"// established, we'll be able to later cancel the connection via the",
"// Remove method.",
"done",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"select",
"{",
"case",
"cm",
".",
"requests",
"<-",
"registerPending",
"{",
"c",
",",
"done",
"}",
":",
"case",
"<-",
"cm",
".",
"quit",
":",
"return",
"\n",
"}",
"\n\n",
"// Wait for the registration to successfully add the pending conn req to",
"// the conn manager's internal state.",
"select",
"{",
"case",
"<-",
"done",
":",
"case",
"<-",
"cm",
".",
"quit",
":",
"return",
"\n",
"}",
"\n\n",
"addr",
",",
"err",
":=",
"cm",
".",
"cfg",
".",
"GetNewAddress",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"select",
"{",
"case",
"cm",
".",
"requests",
"<-",
"handleFailed",
"{",
"c",
",",
"err",
"}",
":",
"case",
"<-",
"cm",
".",
"quit",
":",
"}",
"\n",
"return",
"\n",
"}",
"\n\n",
"c",
".",
"Addr",
"=",
"addr",
"\n\n",
"cm",
".",
"Connect",
"(",
"c",
")",
"\n",
"}"
] | // NewConnReq creates a new connection request and connects to the
// corresponding address. | [
"NewConnReq",
"creates",
"a",
"new",
"connection",
"request",
"and",
"connects",
"to",
"the",
"corresponding",
"address",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/connmgr/connmanager.go#L361-L403 | train |
btcsuite/btcd | connmgr/connmanager.go | Connect | func (cm *ConnManager) Connect(c *ConnReq) {
if atomic.LoadInt32(&cm.stop) != 0 {
return
}
// During the time we wait for retry there is a chance that
// this connection was already cancelled
if c.State() == ConnCanceled {
log.Debugf("Ignoring connect for canceled connreq=%v", c)
return
}
if atomic.LoadUint64(&c.id) == 0 {
atomic.StoreUint64(&c.id, atomic.AddUint64(&cm.connReqCount, 1))
// Submit a request of a pending connection attempt to the
// connection manager. By registering the id before the
// connection is even established, we'll be able to later
// cancel the connection via the Remove method.
done := make(chan struct{})
select {
case cm.requests <- registerPending{c, done}:
case <-cm.quit:
return
}
// Wait for the registration to successfully add the pending
// conn req to the conn manager's internal state.
select {
case <-done:
case <-cm.quit:
return
}
}
log.Debugf("Attempting to connect to %v", c)
conn, err := cm.cfg.Dial(c.Addr)
if err != nil {
select {
case cm.requests <- handleFailed{c, err}:
case <-cm.quit:
}
return
}
select {
case cm.requests <- handleConnected{c, conn}:
case <-cm.quit:
}
} | go | func (cm *ConnManager) Connect(c *ConnReq) {
if atomic.LoadInt32(&cm.stop) != 0 {
return
}
// During the time we wait for retry there is a chance that
// this connection was already cancelled
if c.State() == ConnCanceled {
log.Debugf("Ignoring connect for canceled connreq=%v", c)
return
}
if atomic.LoadUint64(&c.id) == 0 {
atomic.StoreUint64(&c.id, atomic.AddUint64(&cm.connReqCount, 1))
// Submit a request of a pending connection attempt to the
// connection manager. By registering the id before the
// connection is even established, we'll be able to later
// cancel the connection via the Remove method.
done := make(chan struct{})
select {
case cm.requests <- registerPending{c, done}:
case <-cm.quit:
return
}
// Wait for the registration to successfully add the pending
// conn req to the conn manager's internal state.
select {
case <-done:
case <-cm.quit:
return
}
}
log.Debugf("Attempting to connect to %v", c)
conn, err := cm.cfg.Dial(c.Addr)
if err != nil {
select {
case cm.requests <- handleFailed{c, err}:
case <-cm.quit:
}
return
}
select {
case cm.requests <- handleConnected{c, conn}:
case <-cm.quit:
}
} | [
"func",
"(",
"cm",
"*",
"ConnManager",
")",
"Connect",
"(",
"c",
"*",
"ConnReq",
")",
"{",
"if",
"atomic",
".",
"LoadInt32",
"(",
"&",
"cm",
".",
"stop",
")",
"!=",
"0",
"{",
"return",
"\n",
"}",
"\n\n",
"// During the time we wait for retry there is a chance that",
"// this connection was already cancelled",
"if",
"c",
".",
"State",
"(",
")",
"==",
"ConnCanceled",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"c",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"atomic",
".",
"LoadUint64",
"(",
"&",
"c",
".",
"id",
")",
"==",
"0",
"{",
"atomic",
".",
"StoreUint64",
"(",
"&",
"c",
".",
"id",
",",
"atomic",
".",
"AddUint64",
"(",
"&",
"cm",
".",
"connReqCount",
",",
"1",
")",
")",
"\n\n",
"// Submit a request of a pending connection attempt to the",
"// connection manager. By registering the id before the",
"// connection is even established, we'll be able to later",
"// cancel the connection via the Remove method.",
"done",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"select",
"{",
"case",
"cm",
".",
"requests",
"<-",
"registerPending",
"{",
"c",
",",
"done",
"}",
":",
"case",
"<-",
"cm",
".",
"quit",
":",
"return",
"\n",
"}",
"\n\n",
"// Wait for the registration to successfully add the pending",
"// conn req to the conn manager's internal state.",
"select",
"{",
"case",
"<-",
"done",
":",
"case",
"<-",
"cm",
".",
"quit",
":",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"c",
")",
"\n\n",
"conn",
",",
"err",
":=",
"cm",
".",
"cfg",
".",
"Dial",
"(",
"c",
".",
"Addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"select",
"{",
"case",
"cm",
".",
"requests",
"<-",
"handleFailed",
"{",
"c",
",",
"err",
"}",
":",
"case",
"<-",
"cm",
".",
"quit",
":",
"}",
"\n",
"return",
"\n",
"}",
"\n\n",
"select",
"{",
"case",
"cm",
".",
"requests",
"<-",
"handleConnected",
"{",
"c",
",",
"conn",
"}",
":",
"case",
"<-",
"cm",
".",
"quit",
":",
"}",
"\n",
"}"
] | // Connect assigns an id and dials a connection to the address of the
// connection request. | [
"Connect",
"assigns",
"an",
"id",
"and",
"dials",
"a",
"connection",
"to",
"the",
"address",
"of",
"the",
"connection",
"request",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/connmgr/connmanager.go#L407-L457 | train |
btcsuite/btcd | connmgr/connmanager.go | Disconnect | func (cm *ConnManager) Disconnect(id uint64) {
if atomic.LoadInt32(&cm.stop) != 0 {
return
}
select {
case cm.requests <- handleDisconnected{id, true}:
case <-cm.quit:
}
} | go | func (cm *ConnManager) Disconnect(id uint64) {
if atomic.LoadInt32(&cm.stop) != 0 {
return
}
select {
case cm.requests <- handleDisconnected{id, true}:
case <-cm.quit:
}
} | [
"func",
"(",
"cm",
"*",
"ConnManager",
")",
"Disconnect",
"(",
"id",
"uint64",
")",
"{",
"if",
"atomic",
".",
"LoadInt32",
"(",
"&",
"cm",
".",
"stop",
")",
"!=",
"0",
"{",
"return",
"\n",
"}",
"\n\n",
"select",
"{",
"case",
"cm",
".",
"requests",
"<-",
"handleDisconnected",
"{",
"id",
",",
"true",
"}",
":",
"case",
"<-",
"cm",
".",
"quit",
":",
"}",
"\n",
"}"
] | // Disconnect disconnects the connection corresponding to the given connection
// id. If permanent, the connection will be retried with an increasing backoff
// duration. | [
"Disconnect",
"disconnects",
"the",
"connection",
"corresponding",
"to",
"the",
"given",
"connection",
"id",
".",
"If",
"permanent",
"the",
"connection",
"will",
"be",
"retried",
"with",
"an",
"increasing",
"backoff",
"duration",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/connmgr/connmanager.go#L462-L471 | train |
btcsuite/btcd | connmgr/connmanager.go | listenHandler | func (cm *ConnManager) listenHandler(listener net.Listener) {
log.Infof("Server listening on %s", listener.Addr())
for atomic.LoadInt32(&cm.stop) == 0 {
conn, err := listener.Accept()
if err != nil {
// Only log the error if not forcibly shutting down.
if atomic.LoadInt32(&cm.stop) == 0 {
log.Errorf("Can't accept connection: %v", err)
}
continue
}
go cm.cfg.OnAccept(conn)
}
cm.wg.Done()
log.Tracef("Listener handler done for %s", listener.Addr())
} | go | func (cm *ConnManager) listenHandler(listener net.Listener) {
log.Infof("Server listening on %s", listener.Addr())
for atomic.LoadInt32(&cm.stop) == 0 {
conn, err := listener.Accept()
if err != nil {
// Only log the error if not forcibly shutting down.
if atomic.LoadInt32(&cm.stop) == 0 {
log.Errorf("Can't accept connection: %v", err)
}
continue
}
go cm.cfg.OnAccept(conn)
}
cm.wg.Done()
log.Tracef("Listener handler done for %s", listener.Addr())
} | [
"func",
"(",
"cm",
"*",
"ConnManager",
")",
"listenHandler",
"(",
"listener",
"net",
".",
"Listener",
")",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"listener",
".",
"Addr",
"(",
")",
")",
"\n",
"for",
"atomic",
".",
"LoadInt32",
"(",
"&",
"cm",
".",
"stop",
")",
"==",
"0",
"{",
"conn",
",",
"err",
":=",
"listener",
".",
"Accept",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Only log the error if not forcibly shutting down.",
"if",
"atomic",
".",
"LoadInt32",
"(",
"&",
"cm",
".",
"stop",
")",
"==",
"0",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"continue",
"\n",
"}",
"\n",
"go",
"cm",
".",
"cfg",
".",
"OnAccept",
"(",
"conn",
")",
"\n",
"}",
"\n\n",
"cm",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"log",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"listener",
".",
"Addr",
"(",
")",
")",
"\n",
"}"
] | // listenHandler accepts incoming connections on a given listener. It must be
// run as a goroutine. | [
"listenHandler",
"accepts",
"incoming",
"connections",
"on",
"a",
"given",
"listener",
".",
"It",
"must",
"be",
"run",
"as",
"a",
"goroutine",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/connmgr/connmanager.go#L491-L507 | train |
btcsuite/btcd | connmgr/connmanager.go | Start | func (cm *ConnManager) Start() {
// Already started?
if atomic.AddInt32(&cm.start, 1) != 1 {
return
}
log.Trace("Connection manager started")
cm.wg.Add(1)
go cm.connHandler()
// Start all the listeners so long as the caller requested them and
// provided a callback to be invoked when connections are accepted.
if cm.cfg.OnAccept != nil {
for _, listner := range cm.cfg.Listeners {
cm.wg.Add(1)
go cm.listenHandler(listner)
}
}
for i := atomic.LoadUint64(&cm.connReqCount); i < uint64(cm.cfg.TargetOutbound); i++ {
go cm.NewConnReq()
}
} | go | func (cm *ConnManager) Start() {
// Already started?
if atomic.AddInt32(&cm.start, 1) != 1 {
return
}
log.Trace("Connection manager started")
cm.wg.Add(1)
go cm.connHandler()
// Start all the listeners so long as the caller requested them and
// provided a callback to be invoked when connections are accepted.
if cm.cfg.OnAccept != nil {
for _, listner := range cm.cfg.Listeners {
cm.wg.Add(1)
go cm.listenHandler(listner)
}
}
for i := atomic.LoadUint64(&cm.connReqCount); i < uint64(cm.cfg.TargetOutbound); i++ {
go cm.NewConnReq()
}
} | [
"func",
"(",
"cm",
"*",
"ConnManager",
")",
"Start",
"(",
")",
"{",
"// Already started?",
"if",
"atomic",
".",
"AddInt32",
"(",
"&",
"cm",
".",
"start",
",",
"1",
")",
"!=",
"1",
"{",
"return",
"\n",
"}",
"\n\n",
"log",
".",
"Trace",
"(",
"\"",
"\"",
")",
"\n",
"cm",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"cm",
".",
"connHandler",
"(",
")",
"\n\n",
"// Start all the listeners so long as the caller requested them and",
"// provided a callback to be invoked when connections are accepted.",
"if",
"cm",
".",
"cfg",
".",
"OnAccept",
"!=",
"nil",
"{",
"for",
"_",
",",
"listner",
":=",
"range",
"cm",
".",
"cfg",
".",
"Listeners",
"{",
"cm",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"cm",
".",
"listenHandler",
"(",
"listner",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"for",
"i",
":=",
"atomic",
".",
"LoadUint64",
"(",
"&",
"cm",
".",
"connReqCount",
")",
";",
"i",
"<",
"uint64",
"(",
"cm",
".",
"cfg",
".",
"TargetOutbound",
")",
";",
"i",
"++",
"{",
"go",
"cm",
".",
"NewConnReq",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // Start launches the connection manager and begins connecting to the network. | [
"Start",
"launches",
"the",
"connection",
"manager",
"and",
"begins",
"connecting",
"to",
"the",
"network",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/connmgr/connmanager.go#L510-L532 | train |
btcsuite/btcd | connmgr/connmanager.go | Stop | func (cm *ConnManager) Stop() {
if atomic.AddInt32(&cm.stop, 1) != 1 {
log.Warnf("Connection manager already stopped")
return
}
// Stop all the listeners. There will not be any listeners if
// listening is disabled.
for _, listener := range cm.cfg.Listeners {
// Ignore the error since this is shutdown and there is no way
// to recover anyways.
_ = listener.Close()
}
close(cm.quit)
log.Trace("Connection manager stopped")
} | go | func (cm *ConnManager) Stop() {
if atomic.AddInt32(&cm.stop, 1) != 1 {
log.Warnf("Connection manager already stopped")
return
}
// Stop all the listeners. There will not be any listeners if
// listening is disabled.
for _, listener := range cm.cfg.Listeners {
// Ignore the error since this is shutdown and there is no way
// to recover anyways.
_ = listener.Close()
}
close(cm.quit)
log.Trace("Connection manager stopped")
} | [
"func",
"(",
"cm",
"*",
"ConnManager",
")",
"Stop",
"(",
")",
"{",
"if",
"atomic",
".",
"AddInt32",
"(",
"&",
"cm",
".",
"stop",
",",
"1",
")",
"!=",
"1",
"{",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Stop all the listeners. There will not be any listeners if",
"// listening is disabled.",
"for",
"_",
",",
"listener",
":=",
"range",
"cm",
".",
"cfg",
".",
"Listeners",
"{",
"// Ignore the error since this is shutdown and there is no way",
"// to recover anyways.",
"_",
"=",
"listener",
".",
"Close",
"(",
")",
"\n",
"}",
"\n\n",
"close",
"(",
"cm",
".",
"quit",
")",
"\n",
"log",
".",
"Trace",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // Stop gracefully shuts down the connection manager. | [
"Stop",
"gracefully",
"shuts",
"down",
"the",
"connection",
"manager",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/connmgr/connmanager.go#L540-L556 | train |
btcsuite/btcd | connmgr/connmanager.go | New | func New(cfg *Config) (*ConnManager, error) {
if cfg.Dial == nil {
return nil, ErrDialNil
}
// Default to sane values
if cfg.RetryDuration <= 0 {
cfg.RetryDuration = defaultRetryDuration
}
if cfg.TargetOutbound == 0 {
cfg.TargetOutbound = defaultTargetOutbound
}
cm := ConnManager{
cfg: *cfg, // Copy so caller can't mutate
requests: make(chan interface{}),
quit: make(chan struct{}),
}
return &cm, nil
} | go | func New(cfg *Config) (*ConnManager, error) {
if cfg.Dial == nil {
return nil, ErrDialNil
}
// Default to sane values
if cfg.RetryDuration <= 0 {
cfg.RetryDuration = defaultRetryDuration
}
if cfg.TargetOutbound == 0 {
cfg.TargetOutbound = defaultTargetOutbound
}
cm := ConnManager{
cfg: *cfg, // Copy so caller can't mutate
requests: make(chan interface{}),
quit: make(chan struct{}),
}
return &cm, nil
} | [
"func",
"New",
"(",
"cfg",
"*",
"Config",
")",
"(",
"*",
"ConnManager",
",",
"error",
")",
"{",
"if",
"cfg",
".",
"Dial",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrDialNil",
"\n",
"}",
"\n",
"// Default to sane values",
"if",
"cfg",
".",
"RetryDuration",
"<=",
"0",
"{",
"cfg",
".",
"RetryDuration",
"=",
"defaultRetryDuration",
"\n",
"}",
"\n",
"if",
"cfg",
".",
"TargetOutbound",
"==",
"0",
"{",
"cfg",
".",
"TargetOutbound",
"=",
"defaultTargetOutbound",
"\n",
"}",
"\n",
"cm",
":=",
"ConnManager",
"{",
"cfg",
":",
"*",
"cfg",
",",
"// Copy so caller can't mutate",
"requests",
":",
"make",
"(",
"chan",
"interface",
"{",
"}",
")",
",",
"quit",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"}",
"\n",
"return",
"&",
"cm",
",",
"nil",
"\n",
"}"
] | // New returns a new connection manager.
// Use Start to start connecting to the network. | [
"New",
"returns",
"a",
"new",
"connection",
"manager",
".",
"Use",
"Start",
"to",
"start",
"connecting",
"to",
"the",
"network",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/connmgr/connmanager.go#L560-L577 | train |
btcsuite/btcd | wire/msgblock.go | AddTransaction | func (msg *MsgBlock) AddTransaction(tx *MsgTx) error {
msg.Transactions = append(msg.Transactions, tx)
return nil
} | go | func (msg *MsgBlock) AddTransaction(tx *MsgTx) error {
msg.Transactions = append(msg.Transactions, tx)
return nil
} | [
"func",
"(",
"msg",
"*",
"MsgBlock",
")",
"AddTransaction",
"(",
"tx",
"*",
"MsgTx",
")",
"error",
"{",
"msg",
".",
"Transactions",
"=",
"append",
"(",
"msg",
".",
"Transactions",
",",
"tx",
")",
"\n",
"return",
"nil",
"\n\n",
"}"
] | // AddTransaction adds a transaction to the message. | [
"AddTransaction",
"adds",
"a",
"transaction",
"to",
"the",
"message",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgblock.go#L49-L53 | train |
btcsuite/btcd | wire/msgblock.go | BtcDecode | func (msg *MsgBlock) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error {
err := readBlockHeader(r, pver, &msg.Header)
if err != nil {
return err
}
txCount, err := ReadVarInt(r, pver)
if err != nil {
return err
}
// Prevent more transactions than could possibly fit into a block.
// It would be possible to cause memory exhaustion and panics without
// a sane upper bound on this count.
if txCount > maxTxPerBlock {
str := fmt.Sprintf("too many transactions to fit into a block "+
"[count %d, max %d]", txCount, maxTxPerBlock)
return messageError("MsgBlock.BtcDecode", str)
}
msg.Transactions = make([]*MsgTx, 0, txCount)
for i := uint64(0); i < txCount; i++ {
tx := MsgTx{}
err := tx.BtcDecode(r, pver, enc)
if err != nil {
return err
}
msg.Transactions = append(msg.Transactions, &tx)
}
return nil
} | go | func (msg *MsgBlock) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error {
err := readBlockHeader(r, pver, &msg.Header)
if err != nil {
return err
}
txCount, err := ReadVarInt(r, pver)
if err != nil {
return err
}
// Prevent more transactions than could possibly fit into a block.
// It would be possible to cause memory exhaustion and panics without
// a sane upper bound on this count.
if txCount > maxTxPerBlock {
str := fmt.Sprintf("too many transactions to fit into a block "+
"[count %d, max %d]", txCount, maxTxPerBlock)
return messageError("MsgBlock.BtcDecode", str)
}
msg.Transactions = make([]*MsgTx, 0, txCount)
for i := uint64(0); i < txCount; i++ {
tx := MsgTx{}
err := tx.BtcDecode(r, pver, enc)
if err != nil {
return err
}
msg.Transactions = append(msg.Transactions, &tx)
}
return nil
} | [
"func",
"(",
"msg",
"*",
"MsgBlock",
")",
"BtcDecode",
"(",
"r",
"io",
".",
"Reader",
",",
"pver",
"uint32",
",",
"enc",
"MessageEncoding",
")",
"error",
"{",
"err",
":=",
"readBlockHeader",
"(",
"r",
",",
"pver",
",",
"&",
"msg",
".",
"Header",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"txCount",
",",
"err",
":=",
"ReadVarInt",
"(",
"r",
",",
"pver",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Prevent more transactions than could possibly fit into a block.",
"// It would be possible to cause memory exhaustion and panics without",
"// a sane upper bound on this count.",
"if",
"txCount",
">",
"maxTxPerBlock",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"txCount",
",",
"maxTxPerBlock",
")",
"\n",
"return",
"messageError",
"(",
"\"",
"\"",
",",
"str",
")",
"\n",
"}",
"\n\n",
"msg",
".",
"Transactions",
"=",
"make",
"(",
"[",
"]",
"*",
"MsgTx",
",",
"0",
",",
"txCount",
")",
"\n",
"for",
"i",
":=",
"uint64",
"(",
"0",
")",
";",
"i",
"<",
"txCount",
";",
"i",
"++",
"{",
"tx",
":=",
"MsgTx",
"{",
"}",
"\n",
"err",
":=",
"tx",
".",
"BtcDecode",
"(",
"r",
",",
"pver",
",",
"enc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"msg",
".",
"Transactions",
"=",
"append",
"(",
"msg",
".",
"Transactions",
",",
"&",
"tx",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
// This is part of the Message interface implementation.
// See Deserialize for decoding blocks stored to disk, such as in a database, as
// opposed to decoding blocks from the wire. | [
"BtcDecode",
"decodes",
"r",
"using",
"the",
"bitcoin",
"protocol",
"encoding",
"into",
"the",
"receiver",
".",
"This",
"is",
"part",
"of",
"the",
"Message",
"interface",
"implementation",
".",
"See",
"Deserialize",
"for",
"decoding",
"blocks",
"stored",
"to",
"disk",
"such",
"as",
"in",
"a",
"database",
"as",
"opposed",
"to",
"decoding",
"blocks",
"from",
"the",
"wire",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgblock.go#L64-L95 | train |
btcsuite/btcd | wire/msgblock.go | DeserializeTxLoc | func (msg *MsgBlock) DeserializeTxLoc(r *bytes.Buffer) ([]TxLoc, error) {
fullLen := r.Len()
// At the current time, there is no difference between the wire encoding
// at protocol version 0 and the stable long-term storage format. As
// a result, make use of existing wire protocol functions.
err := readBlockHeader(r, 0, &msg.Header)
if err != nil {
return nil, err
}
txCount, err := ReadVarInt(r, 0)
if err != nil {
return nil, err
}
// Prevent more transactions than could possibly fit into a block.
// It would be possible to cause memory exhaustion and panics without
// a sane upper bound on this count.
if txCount > maxTxPerBlock {
str := fmt.Sprintf("too many transactions to fit into a block "+
"[count %d, max %d]", txCount, maxTxPerBlock)
return nil, messageError("MsgBlock.DeserializeTxLoc", str)
}
// Deserialize each transaction while keeping track of its location
// within the byte stream.
msg.Transactions = make([]*MsgTx, 0, txCount)
txLocs := make([]TxLoc, txCount)
for i := uint64(0); i < txCount; i++ {
txLocs[i].TxStart = fullLen - r.Len()
tx := MsgTx{}
err := tx.Deserialize(r)
if err != nil {
return nil, err
}
msg.Transactions = append(msg.Transactions, &tx)
txLocs[i].TxLen = (fullLen - r.Len()) - txLocs[i].TxStart
}
return txLocs, nil
} | go | func (msg *MsgBlock) DeserializeTxLoc(r *bytes.Buffer) ([]TxLoc, error) {
fullLen := r.Len()
// At the current time, there is no difference between the wire encoding
// at protocol version 0 and the stable long-term storage format. As
// a result, make use of existing wire protocol functions.
err := readBlockHeader(r, 0, &msg.Header)
if err != nil {
return nil, err
}
txCount, err := ReadVarInt(r, 0)
if err != nil {
return nil, err
}
// Prevent more transactions than could possibly fit into a block.
// It would be possible to cause memory exhaustion and panics without
// a sane upper bound on this count.
if txCount > maxTxPerBlock {
str := fmt.Sprintf("too many transactions to fit into a block "+
"[count %d, max %d]", txCount, maxTxPerBlock)
return nil, messageError("MsgBlock.DeserializeTxLoc", str)
}
// Deserialize each transaction while keeping track of its location
// within the byte stream.
msg.Transactions = make([]*MsgTx, 0, txCount)
txLocs := make([]TxLoc, txCount)
for i := uint64(0); i < txCount; i++ {
txLocs[i].TxStart = fullLen - r.Len()
tx := MsgTx{}
err := tx.Deserialize(r)
if err != nil {
return nil, err
}
msg.Transactions = append(msg.Transactions, &tx)
txLocs[i].TxLen = (fullLen - r.Len()) - txLocs[i].TxStart
}
return txLocs, nil
} | [
"func",
"(",
"msg",
"*",
"MsgBlock",
")",
"DeserializeTxLoc",
"(",
"r",
"*",
"bytes",
".",
"Buffer",
")",
"(",
"[",
"]",
"TxLoc",
",",
"error",
")",
"{",
"fullLen",
":=",
"r",
".",
"Len",
"(",
")",
"\n\n",
"// At the current time, there is no difference between the wire encoding",
"// at protocol version 0 and the stable long-term storage format. As",
"// a result, make use of existing wire protocol functions.",
"err",
":=",
"readBlockHeader",
"(",
"r",
",",
"0",
",",
"&",
"msg",
".",
"Header",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"txCount",
",",
"err",
":=",
"ReadVarInt",
"(",
"r",
",",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Prevent more transactions than could possibly fit into a block.",
"// It would be possible to cause memory exhaustion and panics without",
"// a sane upper bound on this count.",
"if",
"txCount",
">",
"maxTxPerBlock",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"txCount",
",",
"maxTxPerBlock",
")",
"\n",
"return",
"nil",
",",
"messageError",
"(",
"\"",
"\"",
",",
"str",
")",
"\n",
"}",
"\n\n",
"// Deserialize each transaction while keeping track of its location",
"// within the byte stream.",
"msg",
".",
"Transactions",
"=",
"make",
"(",
"[",
"]",
"*",
"MsgTx",
",",
"0",
",",
"txCount",
")",
"\n",
"txLocs",
":=",
"make",
"(",
"[",
"]",
"TxLoc",
",",
"txCount",
")",
"\n",
"for",
"i",
":=",
"uint64",
"(",
"0",
")",
";",
"i",
"<",
"txCount",
";",
"i",
"++",
"{",
"txLocs",
"[",
"i",
"]",
".",
"TxStart",
"=",
"fullLen",
"-",
"r",
".",
"Len",
"(",
")",
"\n",
"tx",
":=",
"MsgTx",
"{",
"}",
"\n",
"err",
":=",
"tx",
".",
"Deserialize",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"msg",
".",
"Transactions",
"=",
"append",
"(",
"msg",
".",
"Transactions",
",",
"&",
"tx",
")",
"\n",
"txLocs",
"[",
"i",
"]",
".",
"TxLen",
"=",
"(",
"fullLen",
"-",
"r",
".",
"Len",
"(",
")",
")",
"-",
"txLocs",
"[",
"i",
"]",
".",
"TxStart",
"\n",
"}",
"\n\n",
"return",
"txLocs",
",",
"nil",
"\n",
"}"
] | // DeserializeTxLoc decodes r in the same manner Deserialize does, but it takes
// a byte buffer instead of a generic reader and returns a slice containing the
// start and length of each transaction within the raw data that is being
// deserialized. | [
"DeserializeTxLoc",
"decodes",
"r",
"in",
"the",
"same",
"manner",
"Deserialize",
"does",
"but",
"it",
"takes",
"a",
"byte",
"buffer",
"instead",
"of",
"a",
"generic",
"reader",
"and",
"returns",
"a",
"slice",
"containing",
"the",
"start",
"and",
"length",
"of",
"each",
"transaction",
"within",
"the",
"raw",
"data",
"that",
"is",
"being",
"deserialized",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgblock.go#L129-L170 | train |
btcsuite/btcd | wire/msgblock.go | BtcEncode | func (msg *MsgBlock) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {
err := writeBlockHeader(w, pver, &msg.Header)
if err != nil {
return err
}
err = WriteVarInt(w, pver, uint64(len(msg.Transactions)))
if err != nil {
return err
}
for _, tx := range msg.Transactions {
err = tx.BtcEncode(w, pver, enc)
if err != nil {
return err
}
}
return nil
} | go | func (msg *MsgBlock) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {
err := writeBlockHeader(w, pver, &msg.Header)
if err != nil {
return err
}
err = WriteVarInt(w, pver, uint64(len(msg.Transactions)))
if err != nil {
return err
}
for _, tx := range msg.Transactions {
err = tx.BtcEncode(w, pver, enc)
if err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"msg",
"*",
"MsgBlock",
")",
"BtcEncode",
"(",
"w",
"io",
".",
"Writer",
",",
"pver",
"uint32",
",",
"enc",
"MessageEncoding",
")",
"error",
"{",
"err",
":=",
"writeBlockHeader",
"(",
"w",
",",
"pver",
",",
"&",
"msg",
".",
"Header",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"err",
"=",
"WriteVarInt",
"(",
"w",
",",
"pver",
",",
"uint64",
"(",
"len",
"(",
"msg",
".",
"Transactions",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"tx",
":=",
"range",
"msg",
".",
"Transactions",
"{",
"err",
"=",
"tx",
".",
"BtcEncode",
"(",
"w",
",",
"pver",
",",
"enc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
// This is part of the Message interface implementation.
// See Serialize for encoding blocks to be stored to disk, such as in a
// database, as opposed to encoding blocks for the wire. | [
"BtcEncode",
"encodes",
"the",
"receiver",
"to",
"w",
"using",
"the",
"bitcoin",
"protocol",
"encoding",
".",
"This",
"is",
"part",
"of",
"the",
"Message",
"interface",
"implementation",
".",
"See",
"Serialize",
"for",
"encoding",
"blocks",
"to",
"be",
"stored",
"to",
"disk",
"such",
"as",
"in",
"a",
"database",
"as",
"opposed",
"to",
"encoding",
"blocks",
"for",
"the",
"wire",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgblock.go#L176-L195 | train |
btcsuite/btcd | wire/msgblock.go | SerializeSize | func (msg *MsgBlock) SerializeSize() int {
// Block header bytes + Serialized varint size for the number of
// transactions.
n := blockHeaderLen + VarIntSerializeSize(uint64(len(msg.Transactions)))
for _, tx := range msg.Transactions {
n += tx.SerializeSize()
}
return n
} | go | func (msg *MsgBlock) SerializeSize() int {
// Block header bytes + Serialized varint size for the number of
// transactions.
n := blockHeaderLen + VarIntSerializeSize(uint64(len(msg.Transactions)))
for _, tx := range msg.Transactions {
n += tx.SerializeSize()
}
return n
} | [
"func",
"(",
"msg",
"*",
"MsgBlock",
")",
"SerializeSize",
"(",
")",
"int",
"{",
"// Block header bytes + Serialized varint size for the number of",
"// transactions.",
"n",
":=",
"blockHeaderLen",
"+",
"VarIntSerializeSize",
"(",
"uint64",
"(",
"len",
"(",
"msg",
".",
"Transactions",
")",
")",
")",
"\n\n",
"for",
"_",
",",
"tx",
":=",
"range",
"msg",
".",
"Transactions",
"{",
"n",
"+=",
"tx",
".",
"SerializeSize",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"n",
"\n",
"}"
] | // SerializeSize returns the number of bytes it would take to serialize the
// block, factoring in any witness data within transaction. | [
"SerializeSize",
"returns",
"the",
"number",
"of",
"bytes",
"it",
"would",
"take",
"to",
"serialize",
"the",
"block",
"factoring",
"in",
"any",
"witness",
"data",
"within",
"transaction",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgblock.go#L228-L238 | train |
btcsuite/btcd | wire/msgblock.go | TxHashes | func (msg *MsgBlock) TxHashes() ([]chainhash.Hash, error) {
hashList := make([]chainhash.Hash, 0, len(msg.Transactions))
for _, tx := range msg.Transactions {
hashList = append(hashList, tx.TxHash())
}
return hashList, nil
} | go | func (msg *MsgBlock) TxHashes() ([]chainhash.Hash, error) {
hashList := make([]chainhash.Hash, 0, len(msg.Transactions))
for _, tx := range msg.Transactions {
hashList = append(hashList, tx.TxHash())
}
return hashList, nil
} | [
"func",
"(",
"msg",
"*",
"MsgBlock",
")",
"TxHashes",
"(",
")",
"(",
"[",
"]",
"chainhash",
".",
"Hash",
",",
"error",
")",
"{",
"hashList",
":=",
"make",
"(",
"[",
"]",
"chainhash",
".",
"Hash",
",",
"0",
",",
"len",
"(",
"msg",
".",
"Transactions",
")",
")",
"\n",
"for",
"_",
",",
"tx",
":=",
"range",
"msg",
".",
"Transactions",
"{",
"hashList",
"=",
"append",
"(",
"hashList",
",",
"tx",
".",
"TxHash",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"hashList",
",",
"nil",
"\n",
"}"
] | // TxHashes returns a slice of hashes of all of transactions in this block. | [
"TxHashes",
"returns",
"a",
"slice",
"of",
"hashes",
"of",
"all",
"of",
"transactions",
"in",
"this",
"block",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgblock.go#L275-L281 | train |
btcsuite/btcd | wire/msgblock.go | NewMsgBlock | func NewMsgBlock(blockHeader *BlockHeader) *MsgBlock {
return &MsgBlock{
Header: *blockHeader,
Transactions: make([]*MsgTx, 0, defaultTransactionAlloc),
}
} | go | func NewMsgBlock(blockHeader *BlockHeader) *MsgBlock {
return &MsgBlock{
Header: *blockHeader,
Transactions: make([]*MsgTx, 0, defaultTransactionAlloc),
}
} | [
"func",
"NewMsgBlock",
"(",
"blockHeader",
"*",
"BlockHeader",
")",
"*",
"MsgBlock",
"{",
"return",
"&",
"MsgBlock",
"{",
"Header",
":",
"*",
"blockHeader",
",",
"Transactions",
":",
"make",
"(",
"[",
"]",
"*",
"MsgTx",
",",
"0",
",",
"defaultTransactionAlloc",
")",
",",
"}",
"\n",
"}"
] | // NewMsgBlock returns a new bitcoin block message that conforms to the
// Message interface. See MsgBlock for details. | [
"NewMsgBlock",
"returns",
"a",
"new",
"bitcoin",
"block",
"message",
"that",
"conforms",
"to",
"the",
"Message",
"interface",
".",
"See",
"MsgBlock",
"for",
"details",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgblock.go#L285-L290 | train |
btcsuite/btcd | blockchain/indexers/addrindex.go | serializeAddrIndexEntry | func serializeAddrIndexEntry(blockID uint32, txLoc wire.TxLoc) []byte {
// Serialize the entry.
serialized := make([]byte, 12)
byteOrder.PutUint32(serialized, blockID)
byteOrder.PutUint32(serialized[4:], uint32(txLoc.TxStart))
byteOrder.PutUint32(serialized[8:], uint32(txLoc.TxLen))
return serialized
} | go | func serializeAddrIndexEntry(blockID uint32, txLoc wire.TxLoc) []byte {
// Serialize the entry.
serialized := make([]byte, 12)
byteOrder.PutUint32(serialized, blockID)
byteOrder.PutUint32(serialized[4:], uint32(txLoc.TxStart))
byteOrder.PutUint32(serialized[8:], uint32(txLoc.TxLen))
return serialized
} | [
"func",
"serializeAddrIndexEntry",
"(",
"blockID",
"uint32",
",",
"txLoc",
"wire",
".",
"TxLoc",
")",
"[",
"]",
"byte",
"{",
"// Serialize the entry.",
"serialized",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"12",
")",
"\n",
"byteOrder",
".",
"PutUint32",
"(",
"serialized",
",",
"blockID",
")",
"\n",
"byteOrder",
".",
"PutUint32",
"(",
"serialized",
"[",
"4",
":",
"]",
",",
"uint32",
"(",
"txLoc",
".",
"TxStart",
")",
")",
"\n",
"byteOrder",
".",
"PutUint32",
"(",
"serialized",
"[",
"8",
":",
"]",
",",
"uint32",
"(",
"txLoc",
".",
"TxLen",
")",
")",
"\n",
"return",
"serialized",
"\n",
"}"
] | // serializeAddrIndexEntry serializes the provided block id and transaction
// location according to the format described in detail above. | [
"serializeAddrIndexEntry",
"serializes",
"the",
"provided",
"block",
"id",
"and",
"transaction",
"location",
"according",
"to",
"the",
"format",
"described",
"in",
"detail",
"above",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/addrindex.go#L145-L152 | train |
btcsuite/btcd | blockchain/indexers/addrindex.go | deserializeAddrIndexEntry | func deserializeAddrIndexEntry(serialized []byte, region *database.BlockRegion, fetchBlockHash fetchBlockHashFunc) error {
// Ensure there are enough bytes to decode.
if len(serialized) < txEntrySize {
return errDeserialize("unexpected end of data")
}
hash, err := fetchBlockHash(serialized[0:4])
if err != nil {
return err
}
region.Hash = hash
region.Offset = byteOrder.Uint32(serialized[4:8])
region.Len = byteOrder.Uint32(serialized[8:12])
return nil
} | go | func deserializeAddrIndexEntry(serialized []byte, region *database.BlockRegion, fetchBlockHash fetchBlockHashFunc) error {
// Ensure there are enough bytes to decode.
if len(serialized) < txEntrySize {
return errDeserialize("unexpected end of data")
}
hash, err := fetchBlockHash(serialized[0:4])
if err != nil {
return err
}
region.Hash = hash
region.Offset = byteOrder.Uint32(serialized[4:8])
region.Len = byteOrder.Uint32(serialized[8:12])
return nil
} | [
"func",
"deserializeAddrIndexEntry",
"(",
"serialized",
"[",
"]",
"byte",
",",
"region",
"*",
"database",
".",
"BlockRegion",
",",
"fetchBlockHash",
"fetchBlockHashFunc",
")",
"error",
"{",
"// Ensure there are enough bytes to decode.",
"if",
"len",
"(",
"serialized",
")",
"<",
"txEntrySize",
"{",
"return",
"errDeserialize",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"hash",
",",
"err",
":=",
"fetchBlockHash",
"(",
"serialized",
"[",
"0",
":",
"4",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"region",
".",
"Hash",
"=",
"hash",
"\n",
"region",
".",
"Offset",
"=",
"byteOrder",
".",
"Uint32",
"(",
"serialized",
"[",
"4",
":",
"8",
"]",
")",
"\n",
"region",
".",
"Len",
"=",
"byteOrder",
".",
"Uint32",
"(",
"serialized",
"[",
"8",
":",
"12",
"]",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // deserializeAddrIndexEntry decodes the passed serialized byte slice into the
// provided region struct according to the format described in detail above and
// uses the passed block hash fetching function in order to conver the block ID
// to the associated block hash. | [
"deserializeAddrIndexEntry",
"decodes",
"the",
"passed",
"serialized",
"byte",
"slice",
"into",
"the",
"provided",
"region",
"struct",
"according",
"to",
"the",
"format",
"described",
"in",
"detail",
"above",
"and",
"uses",
"the",
"passed",
"block",
"hash",
"fetching",
"function",
"in",
"order",
"to",
"conver",
"the",
"block",
"ID",
"to",
"the",
"associated",
"block",
"hash",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/addrindex.go#L158-L172 | train |
btcsuite/btcd | blockchain/indexers/addrindex.go | keyForLevel | func keyForLevel(addrKey [addrKeySize]byte, level uint8) [levelKeySize]byte {
var key [levelKeySize]byte
copy(key[:], addrKey[:])
key[levelOffset] = level
return key
} | go | func keyForLevel(addrKey [addrKeySize]byte, level uint8) [levelKeySize]byte {
var key [levelKeySize]byte
copy(key[:], addrKey[:])
key[levelOffset] = level
return key
} | [
"func",
"keyForLevel",
"(",
"addrKey",
"[",
"addrKeySize",
"]",
"byte",
",",
"level",
"uint8",
")",
"[",
"levelKeySize",
"]",
"byte",
"{",
"var",
"key",
"[",
"levelKeySize",
"]",
"byte",
"\n",
"copy",
"(",
"key",
"[",
":",
"]",
",",
"addrKey",
"[",
":",
"]",
")",
"\n",
"key",
"[",
"levelOffset",
"]",
"=",
"level",
"\n",
"return",
"key",
"\n",
"}"
] | // keyForLevel returns the key for a specific address and level in the address
// index entry. | [
"keyForLevel",
"returns",
"the",
"key",
"for",
"a",
"specific",
"address",
"and",
"level",
"in",
"the",
"address",
"index",
"entry",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/addrindex.go#L176-L181 | train |
btcsuite/btcd | blockchain/indexers/addrindex.go | dbPutAddrIndexEntry | func dbPutAddrIndexEntry(bucket internalBucket, addrKey [addrKeySize]byte, blockID uint32, txLoc wire.TxLoc) error {
// Start with level 0 and its initial max number of entries.
curLevel := uint8(0)
maxLevelBytes := level0MaxEntries * txEntrySize
// Simply append the new entry to level 0 and return now when it will
// fit. This is the most common path.
newData := serializeAddrIndexEntry(blockID, txLoc)
level0Key := keyForLevel(addrKey, 0)
level0Data := bucket.Get(level0Key[:])
if len(level0Data)+len(newData) <= maxLevelBytes {
mergedData := newData
if len(level0Data) > 0 {
mergedData = make([]byte, len(level0Data)+len(newData))
copy(mergedData, level0Data)
copy(mergedData[len(level0Data):], newData)
}
return bucket.Put(level0Key[:], mergedData)
}
// At this point, level 0 is full, so merge each level into higher
// levels as many times as needed to free up level 0.
prevLevelData := level0Data
for {
// Each new level holds twice as much as the previous one.
curLevel++
maxLevelBytes *= 2
// Move to the next level as long as the current level is full.
curLevelKey := keyForLevel(addrKey, curLevel)
curLevelData := bucket.Get(curLevelKey[:])
if len(curLevelData) == maxLevelBytes {
prevLevelData = curLevelData
continue
}
// The current level has room for the data in the previous one,
// so merge the data from previous level into it.
mergedData := prevLevelData
if len(curLevelData) > 0 {
mergedData = make([]byte, len(curLevelData)+
len(prevLevelData))
copy(mergedData, curLevelData)
copy(mergedData[len(curLevelData):], prevLevelData)
}
err := bucket.Put(curLevelKey[:], mergedData)
if err != nil {
return err
}
// Move all of the levels before the previous one up a level.
for mergeLevel := curLevel - 1; mergeLevel > 0; mergeLevel-- {
mergeLevelKey := keyForLevel(addrKey, mergeLevel)
prevLevelKey := keyForLevel(addrKey, mergeLevel-1)
prevData := bucket.Get(prevLevelKey[:])
err := bucket.Put(mergeLevelKey[:], prevData)
if err != nil {
return err
}
}
break
}
// Finally, insert the new entry into level 0 now that it is empty.
return bucket.Put(level0Key[:], newData)
} | go | func dbPutAddrIndexEntry(bucket internalBucket, addrKey [addrKeySize]byte, blockID uint32, txLoc wire.TxLoc) error {
// Start with level 0 and its initial max number of entries.
curLevel := uint8(0)
maxLevelBytes := level0MaxEntries * txEntrySize
// Simply append the new entry to level 0 and return now when it will
// fit. This is the most common path.
newData := serializeAddrIndexEntry(blockID, txLoc)
level0Key := keyForLevel(addrKey, 0)
level0Data := bucket.Get(level0Key[:])
if len(level0Data)+len(newData) <= maxLevelBytes {
mergedData := newData
if len(level0Data) > 0 {
mergedData = make([]byte, len(level0Data)+len(newData))
copy(mergedData, level0Data)
copy(mergedData[len(level0Data):], newData)
}
return bucket.Put(level0Key[:], mergedData)
}
// At this point, level 0 is full, so merge each level into higher
// levels as many times as needed to free up level 0.
prevLevelData := level0Data
for {
// Each new level holds twice as much as the previous one.
curLevel++
maxLevelBytes *= 2
// Move to the next level as long as the current level is full.
curLevelKey := keyForLevel(addrKey, curLevel)
curLevelData := bucket.Get(curLevelKey[:])
if len(curLevelData) == maxLevelBytes {
prevLevelData = curLevelData
continue
}
// The current level has room for the data in the previous one,
// so merge the data from previous level into it.
mergedData := prevLevelData
if len(curLevelData) > 0 {
mergedData = make([]byte, len(curLevelData)+
len(prevLevelData))
copy(mergedData, curLevelData)
copy(mergedData[len(curLevelData):], prevLevelData)
}
err := bucket.Put(curLevelKey[:], mergedData)
if err != nil {
return err
}
// Move all of the levels before the previous one up a level.
for mergeLevel := curLevel - 1; mergeLevel > 0; mergeLevel-- {
mergeLevelKey := keyForLevel(addrKey, mergeLevel)
prevLevelKey := keyForLevel(addrKey, mergeLevel-1)
prevData := bucket.Get(prevLevelKey[:])
err := bucket.Put(mergeLevelKey[:], prevData)
if err != nil {
return err
}
}
break
}
// Finally, insert the new entry into level 0 now that it is empty.
return bucket.Put(level0Key[:], newData)
} | [
"func",
"dbPutAddrIndexEntry",
"(",
"bucket",
"internalBucket",
",",
"addrKey",
"[",
"addrKeySize",
"]",
"byte",
",",
"blockID",
"uint32",
",",
"txLoc",
"wire",
".",
"TxLoc",
")",
"error",
"{",
"// Start with level 0 and its initial max number of entries.",
"curLevel",
":=",
"uint8",
"(",
"0",
")",
"\n",
"maxLevelBytes",
":=",
"level0MaxEntries",
"*",
"txEntrySize",
"\n\n",
"// Simply append the new entry to level 0 and return now when it will",
"// fit. This is the most common path.",
"newData",
":=",
"serializeAddrIndexEntry",
"(",
"blockID",
",",
"txLoc",
")",
"\n",
"level0Key",
":=",
"keyForLevel",
"(",
"addrKey",
",",
"0",
")",
"\n",
"level0Data",
":=",
"bucket",
".",
"Get",
"(",
"level0Key",
"[",
":",
"]",
")",
"\n",
"if",
"len",
"(",
"level0Data",
")",
"+",
"len",
"(",
"newData",
")",
"<=",
"maxLevelBytes",
"{",
"mergedData",
":=",
"newData",
"\n",
"if",
"len",
"(",
"level0Data",
")",
">",
"0",
"{",
"mergedData",
"=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"level0Data",
")",
"+",
"len",
"(",
"newData",
")",
")",
"\n",
"copy",
"(",
"mergedData",
",",
"level0Data",
")",
"\n",
"copy",
"(",
"mergedData",
"[",
"len",
"(",
"level0Data",
")",
":",
"]",
",",
"newData",
")",
"\n",
"}",
"\n",
"return",
"bucket",
".",
"Put",
"(",
"level0Key",
"[",
":",
"]",
",",
"mergedData",
")",
"\n",
"}",
"\n\n",
"// At this point, level 0 is full, so merge each level into higher",
"// levels as many times as needed to free up level 0.",
"prevLevelData",
":=",
"level0Data",
"\n",
"for",
"{",
"// Each new level holds twice as much as the previous one.",
"curLevel",
"++",
"\n",
"maxLevelBytes",
"*=",
"2",
"\n\n",
"// Move to the next level as long as the current level is full.",
"curLevelKey",
":=",
"keyForLevel",
"(",
"addrKey",
",",
"curLevel",
")",
"\n",
"curLevelData",
":=",
"bucket",
".",
"Get",
"(",
"curLevelKey",
"[",
":",
"]",
")",
"\n",
"if",
"len",
"(",
"curLevelData",
")",
"==",
"maxLevelBytes",
"{",
"prevLevelData",
"=",
"curLevelData",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// The current level has room for the data in the previous one,",
"// so merge the data from previous level into it.",
"mergedData",
":=",
"prevLevelData",
"\n",
"if",
"len",
"(",
"curLevelData",
")",
">",
"0",
"{",
"mergedData",
"=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"curLevelData",
")",
"+",
"len",
"(",
"prevLevelData",
")",
")",
"\n",
"copy",
"(",
"mergedData",
",",
"curLevelData",
")",
"\n",
"copy",
"(",
"mergedData",
"[",
"len",
"(",
"curLevelData",
")",
":",
"]",
",",
"prevLevelData",
")",
"\n",
"}",
"\n",
"err",
":=",
"bucket",
".",
"Put",
"(",
"curLevelKey",
"[",
":",
"]",
",",
"mergedData",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Move all of the levels before the previous one up a level.",
"for",
"mergeLevel",
":=",
"curLevel",
"-",
"1",
";",
"mergeLevel",
">",
"0",
";",
"mergeLevel",
"--",
"{",
"mergeLevelKey",
":=",
"keyForLevel",
"(",
"addrKey",
",",
"mergeLevel",
")",
"\n",
"prevLevelKey",
":=",
"keyForLevel",
"(",
"addrKey",
",",
"mergeLevel",
"-",
"1",
")",
"\n",
"prevData",
":=",
"bucket",
".",
"Get",
"(",
"prevLevelKey",
"[",
":",
"]",
")",
"\n",
"err",
":=",
"bucket",
".",
"Put",
"(",
"mergeLevelKey",
"[",
":",
"]",
",",
"prevData",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"break",
"\n",
"}",
"\n\n",
"// Finally, insert the new entry into level 0 now that it is empty.",
"return",
"bucket",
".",
"Put",
"(",
"level0Key",
"[",
":",
"]",
",",
"newData",
")",
"\n",
"}"
] | // dbPutAddrIndexEntry updates the address index to include the provided entry
// according to the level-based scheme described in detail above. | [
"dbPutAddrIndexEntry",
"updates",
"the",
"address",
"index",
"to",
"include",
"the",
"provided",
"entry",
"according",
"to",
"the",
"level",
"-",
"based",
"scheme",
"described",
"in",
"detail",
"above",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/addrindex.go#L185-L250 | train |
btcsuite/btcd | blockchain/indexers/addrindex.go | dbFetchAddrIndexEntries | func dbFetchAddrIndexEntries(bucket internalBucket, addrKey [addrKeySize]byte, numToSkip, numRequested uint32, reverse bool, fetchBlockHash fetchBlockHashFunc) ([]database.BlockRegion, uint32, error) {
// When the reverse flag is not set, all levels need to be fetched
// because numToSkip and numRequested are counted from the oldest
// transactions (highest level) and thus the total count is needed.
// However, when the reverse flag is set, only enough records to satisfy
// the requested amount are needed.
var level uint8
var serialized []byte
for !reverse || len(serialized) < int(numToSkip+numRequested)*txEntrySize {
curLevelKey := keyForLevel(addrKey, level)
levelData := bucket.Get(curLevelKey[:])
if levelData == nil {
// Stop when there are no more levels.
break
}
// Higher levels contain older transactions, so prepend them.
prepended := make([]byte, len(serialized)+len(levelData))
copy(prepended, levelData)
copy(prepended[len(levelData):], serialized)
serialized = prepended
level++
}
// When the requested number of entries to skip is larger than the
// number available, skip them all and return now with the actual number
// skipped.
numEntries := uint32(len(serialized) / txEntrySize)
if numToSkip >= numEntries {
return nil, numEntries, nil
}
// Nothing more to do when there are no requested entries.
if numRequested == 0 {
return nil, numToSkip, nil
}
// Limit the number to load based on the number of available entries,
// the number to skip, and the number requested.
numToLoad := numEntries - numToSkip
if numToLoad > numRequested {
numToLoad = numRequested
}
// Start the offset after all skipped entries and load the calculated
// number.
results := make([]database.BlockRegion, numToLoad)
for i := uint32(0); i < numToLoad; i++ {
// Calculate the read offset according to the reverse flag.
var offset uint32
if reverse {
offset = (numEntries - numToSkip - i - 1) * txEntrySize
} else {
offset = (numToSkip + i) * txEntrySize
}
// Deserialize and populate the result.
err := deserializeAddrIndexEntry(serialized[offset:],
&results[i], fetchBlockHash)
if err != nil {
// Ensure any deserialization errors are returned as
// database corruption errors.
if isDeserializeErr(err) {
err = database.Error{
ErrorCode: database.ErrCorruption,
Description: fmt.Sprintf("failed to "+
"deserialized address index "+
"for key %x: %v", addrKey, err),
}
}
return nil, 0, err
}
}
return results, numToSkip, nil
} | go | func dbFetchAddrIndexEntries(bucket internalBucket, addrKey [addrKeySize]byte, numToSkip, numRequested uint32, reverse bool, fetchBlockHash fetchBlockHashFunc) ([]database.BlockRegion, uint32, error) {
// When the reverse flag is not set, all levels need to be fetched
// because numToSkip and numRequested are counted from the oldest
// transactions (highest level) and thus the total count is needed.
// However, when the reverse flag is set, only enough records to satisfy
// the requested amount are needed.
var level uint8
var serialized []byte
for !reverse || len(serialized) < int(numToSkip+numRequested)*txEntrySize {
curLevelKey := keyForLevel(addrKey, level)
levelData := bucket.Get(curLevelKey[:])
if levelData == nil {
// Stop when there are no more levels.
break
}
// Higher levels contain older transactions, so prepend them.
prepended := make([]byte, len(serialized)+len(levelData))
copy(prepended, levelData)
copy(prepended[len(levelData):], serialized)
serialized = prepended
level++
}
// When the requested number of entries to skip is larger than the
// number available, skip them all and return now with the actual number
// skipped.
numEntries := uint32(len(serialized) / txEntrySize)
if numToSkip >= numEntries {
return nil, numEntries, nil
}
// Nothing more to do when there are no requested entries.
if numRequested == 0 {
return nil, numToSkip, nil
}
// Limit the number to load based on the number of available entries,
// the number to skip, and the number requested.
numToLoad := numEntries - numToSkip
if numToLoad > numRequested {
numToLoad = numRequested
}
// Start the offset after all skipped entries and load the calculated
// number.
results := make([]database.BlockRegion, numToLoad)
for i := uint32(0); i < numToLoad; i++ {
// Calculate the read offset according to the reverse flag.
var offset uint32
if reverse {
offset = (numEntries - numToSkip - i - 1) * txEntrySize
} else {
offset = (numToSkip + i) * txEntrySize
}
// Deserialize and populate the result.
err := deserializeAddrIndexEntry(serialized[offset:],
&results[i], fetchBlockHash)
if err != nil {
// Ensure any deserialization errors are returned as
// database corruption errors.
if isDeserializeErr(err) {
err = database.Error{
ErrorCode: database.ErrCorruption,
Description: fmt.Sprintf("failed to "+
"deserialized address index "+
"for key %x: %v", addrKey, err),
}
}
return nil, 0, err
}
}
return results, numToSkip, nil
} | [
"func",
"dbFetchAddrIndexEntries",
"(",
"bucket",
"internalBucket",
",",
"addrKey",
"[",
"addrKeySize",
"]",
"byte",
",",
"numToSkip",
",",
"numRequested",
"uint32",
",",
"reverse",
"bool",
",",
"fetchBlockHash",
"fetchBlockHashFunc",
")",
"(",
"[",
"]",
"database",
".",
"BlockRegion",
",",
"uint32",
",",
"error",
")",
"{",
"// When the reverse flag is not set, all levels need to be fetched",
"// because numToSkip and numRequested are counted from the oldest",
"// transactions (highest level) and thus the total count is needed.",
"// However, when the reverse flag is set, only enough records to satisfy",
"// the requested amount are needed.",
"var",
"level",
"uint8",
"\n",
"var",
"serialized",
"[",
"]",
"byte",
"\n",
"for",
"!",
"reverse",
"||",
"len",
"(",
"serialized",
")",
"<",
"int",
"(",
"numToSkip",
"+",
"numRequested",
")",
"*",
"txEntrySize",
"{",
"curLevelKey",
":=",
"keyForLevel",
"(",
"addrKey",
",",
"level",
")",
"\n",
"levelData",
":=",
"bucket",
".",
"Get",
"(",
"curLevelKey",
"[",
":",
"]",
")",
"\n",
"if",
"levelData",
"==",
"nil",
"{",
"// Stop when there are no more levels.",
"break",
"\n",
"}",
"\n\n",
"// Higher levels contain older transactions, so prepend them.",
"prepended",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"serialized",
")",
"+",
"len",
"(",
"levelData",
")",
")",
"\n",
"copy",
"(",
"prepended",
",",
"levelData",
")",
"\n",
"copy",
"(",
"prepended",
"[",
"len",
"(",
"levelData",
")",
":",
"]",
",",
"serialized",
")",
"\n",
"serialized",
"=",
"prepended",
"\n",
"level",
"++",
"\n",
"}",
"\n\n",
"// When the requested number of entries to skip is larger than the",
"// number available, skip them all and return now with the actual number",
"// skipped.",
"numEntries",
":=",
"uint32",
"(",
"len",
"(",
"serialized",
")",
"/",
"txEntrySize",
")",
"\n",
"if",
"numToSkip",
">=",
"numEntries",
"{",
"return",
"nil",
",",
"numEntries",
",",
"nil",
"\n",
"}",
"\n\n",
"// Nothing more to do when there are no requested entries.",
"if",
"numRequested",
"==",
"0",
"{",
"return",
"nil",
",",
"numToSkip",
",",
"nil",
"\n",
"}",
"\n\n",
"// Limit the number to load based on the number of available entries,",
"// the number to skip, and the number requested.",
"numToLoad",
":=",
"numEntries",
"-",
"numToSkip",
"\n",
"if",
"numToLoad",
">",
"numRequested",
"{",
"numToLoad",
"=",
"numRequested",
"\n",
"}",
"\n\n",
"// Start the offset after all skipped entries and load the calculated",
"// number.",
"results",
":=",
"make",
"(",
"[",
"]",
"database",
".",
"BlockRegion",
",",
"numToLoad",
")",
"\n",
"for",
"i",
":=",
"uint32",
"(",
"0",
")",
";",
"i",
"<",
"numToLoad",
";",
"i",
"++",
"{",
"// Calculate the read offset according to the reverse flag.",
"var",
"offset",
"uint32",
"\n",
"if",
"reverse",
"{",
"offset",
"=",
"(",
"numEntries",
"-",
"numToSkip",
"-",
"i",
"-",
"1",
")",
"*",
"txEntrySize",
"\n",
"}",
"else",
"{",
"offset",
"=",
"(",
"numToSkip",
"+",
"i",
")",
"*",
"txEntrySize",
"\n",
"}",
"\n\n",
"// Deserialize and populate the result.",
"err",
":=",
"deserializeAddrIndexEntry",
"(",
"serialized",
"[",
"offset",
":",
"]",
",",
"&",
"results",
"[",
"i",
"]",
",",
"fetchBlockHash",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Ensure any deserialization errors are returned as",
"// database corruption errors.",
"if",
"isDeserializeErr",
"(",
"err",
")",
"{",
"err",
"=",
"database",
".",
"Error",
"{",
"ErrorCode",
":",
"database",
".",
"ErrCorruption",
",",
"Description",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"addrKey",
",",
"err",
")",
",",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"0",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"results",
",",
"numToSkip",
",",
"nil",
"\n",
"}"
] | // dbFetchAddrIndexEntries returns block regions for transactions referenced by
// the given address key and the number of entries skipped since it could have
// been less in the case where there are less total entries than the requested
// number of entries to skip. | [
"dbFetchAddrIndexEntries",
"returns",
"block",
"regions",
"for",
"transactions",
"referenced",
"by",
"the",
"given",
"address",
"key",
"and",
"the",
"number",
"of",
"entries",
"skipped",
"since",
"it",
"could",
"have",
"been",
"less",
"in",
"the",
"case",
"where",
"there",
"are",
"less",
"total",
"entries",
"than",
"the",
"requested",
"number",
"of",
"entries",
"to",
"skip",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/addrindex.go#L256-L332 | train |
btcsuite/btcd | blockchain/indexers/addrindex.go | minEntriesToReachLevel | func minEntriesToReachLevel(level uint8) int {
maxEntriesForLevel := level0MaxEntries
minRequired := 1
for l := uint8(1); l <= level; l++ {
minRequired += maxEntriesForLevel
maxEntriesForLevel *= 2
}
return minRequired
} | go | func minEntriesToReachLevel(level uint8) int {
maxEntriesForLevel := level0MaxEntries
minRequired := 1
for l := uint8(1); l <= level; l++ {
minRequired += maxEntriesForLevel
maxEntriesForLevel *= 2
}
return minRequired
} | [
"func",
"minEntriesToReachLevel",
"(",
"level",
"uint8",
")",
"int",
"{",
"maxEntriesForLevel",
":=",
"level0MaxEntries",
"\n",
"minRequired",
":=",
"1",
"\n",
"for",
"l",
":=",
"uint8",
"(",
"1",
")",
";",
"l",
"<=",
"level",
";",
"l",
"++",
"{",
"minRequired",
"+=",
"maxEntriesForLevel",
"\n",
"maxEntriesForLevel",
"*=",
"2",
"\n",
"}",
"\n",
"return",
"minRequired",
"\n",
"}"
] | // minEntriesToReachLevel returns the minimum number of entries that are
// required to reach the given address index level. | [
"minEntriesToReachLevel",
"returns",
"the",
"minimum",
"number",
"of",
"entries",
"that",
"are",
"required",
"to",
"reach",
"the",
"given",
"address",
"index",
"level",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/addrindex.go#L336-L344 | train |
btcsuite/btcd | blockchain/indexers/addrindex.go | maxEntriesForLevel | func maxEntriesForLevel(level uint8) int {
numEntries := level0MaxEntries
for l := level; l > 0; l-- {
numEntries *= 2
}
return numEntries
} | go | func maxEntriesForLevel(level uint8) int {
numEntries := level0MaxEntries
for l := level; l > 0; l-- {
numEntries *= 2
}
return numEntries
} | [
"func",
"maxEntriesForLevel",
"(",
"level",
"uint8",
")",
"int",
"{",
"numEntries",
":=",
"level0MaxEntries",
"\n",
"for",
"l",
":=",
"level",
";",
"l",
">",
"0",
";",
"l",
"--",
"{",
"numEntries",
"*=",
"2",
"\n",
"}",
"\n",
"return",
"numEntries",
"\n",
"}"
] | // maxEntriesForLevel returns the maximum number of entries allowed for the
// given address index level. | [
"maxEntriesForLevel",
"returns",
"the",
"maximum",
"number",
"of",
"entries",
"allowed",
"for",
"the",
"given",
"address",
"index",
"level",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/addrindex.go#L348-L354 | train |
btcsuite/btcd | blockchain/indexers/addrindex.go | addrToKey | func addrToKey(addr btcutil.Address) ([addrKeySize]byte, error) {
switch addr := addr.(type) {
case *btcutil.AddressPubKeyHash:
var result [addrKeySize]byte
result[0] = addrKeyTypePubKeyHash
copy(result[1:], addr.Hash160()[:])
return result, nil
case *btcutil.AddressScriptHash:
var result [addrKeySize]byte
result[0] = addrKeyTypeScriptHash
copy(result[1:], addr.Hash160()[:])
return result, nil
case *btcutil.AddressPubKey:
var result [addrKeySize]byte
result[0] = addrKeyTypePubKeyHash
copy(result[1:], addr.AddressPubKeyHash().Hash160()[:])
return result, nil
case *btcutil.AddressWitnessScriptHash:
var result [addrKeySize]byte
result[0] = addrKeyTypeWitnessScriptHash
// P2WSH outputs utilize a 32-byte data push created by hashing
// the script with sha256 instead of hash160. In order to keep
// all address entries within the database uniform and compact,
// we use a hash160 here to reduce the size of the salient data
// push to 20-bytes.
copy(result[1:], btcutil.Hash160(addr.ScriptAddress()))
return result, nil
case *btcutil.AddressWitnessPubKeyHash:
var result [addrKeySize]byte
result[0] = addrKeyTypeWitnessPubKeyHash
copy(result[1:], addr.Hash160()[:])
return result, nil
}
return [addrKeySize]byte{}, errUnsupportedAddressType
} | go | func addrToKey(addr btcutil.Address) ([addrKeySize]byte, error) {
switch addr := addr.(type) {
case *btcutil.AddressPubKeyHash:
var result [addrKeySize]byte
result[0] = addrKeyTypePubKeyHash
copy(result[1:], addr.Hash160()[:])
return result, nil
case *btcutil.AddressScriptHash:
var result [addrKeySize]byte
result[0] = addrKeyTypeScriptHash
copy(result[1:], addr.Hash160()[:])
return result, nil
case *btcutil.AddressPubKey:
var result [addrKeySize]byte
result[0] = addrKeyTypePubKeyHash
copy(result[1:], addr.AddressPubKeyHash().Hash160()[:])
return result, nil
case *btcutil.AddressWitnessScriptHash:
var result [addrKeySize]byte
result[0] = addrKeyTypeWitnessScriptHash
// P2WSH outputs utilize a 32-byte data push created by hashing
// the script with sha256 instead of hash160. In order to keep
// all address entries within the database uniform and compact,
// we use a hash160 here to reduce the size of the salient data
// push to 20-bytes.
copy(result[1:], btcutil.Hash160(addr.ScriptAddress()))
return result, nil
case *btcutil.AddressWitnessPubKeyHash:
var result [addrKeySize]byte
result[0] = addrKeyTypeWitnessPubKeyHash
copy(result[1:], addr.Hash160()[:])
return result, nil
}
return [addrKeySize]byte{}, errUnsupportedAddressType
} | [
"func",
"addrToKey",
"(",
"addr",
"btcutil",
".",
"Address",
")",
"(",
"[",
"addrKeySize",
"]",
"byte",
",",
"error",
")",
"{",
"switch",
"addr",
":=",
"addr",
".",
"(",
"type",
")",
"{",
"case",
"*",
"btcutil",
".",
"AddressPubKeyHash",
":",
"var",
"result",
"[",
"addrKeySize",
"]",
"byte",
"\n",
"result",
"[",
"0",
"]",
"=",
"addrKeyTypePubKeyHash",
"\n",
"copy",
"(",
"result",
"[",
"1",
":",
"]",
",",
"addr",
".",
"Hash160",
"(",
")",
"[",
":",
"]",
")",
"\n",
"return",
"result",
",",
"nil",
"\n\n",
"case",
"*",
"btcutil",
".",
"AddressScriptHash",
":",
"var",
"result",
"[",
"addrKeySize",
"]",
"byte",
"\n",
"result",
"[",
"0",
"]",
"=",
"addrKeyTypeScriptHash",
"\n",
"copy",
"(",
"result",
"[",
"1",
":",
"]",
",",
"addr",
".",
"Hash160",
"(",
")",
"[",
":",
"]",
")",
"\n",
"return",
"result",
",",
"nil",
"\n\n",
"case",
"*",
"btcutil",
".",
"AddressPubKey",
":",
"var",
"result",
"[",
"addrKeySize",
"]",
"byte",
"\n",
"result",
"[",
"0",
"]",
"=",
"addrKeyTypePubKeyHash",
"\n",
"copy",
"(",
"result",
"[",
"1",
":",
"]",
",",
"addr",
".",
"AddressPubKeyHash",
"(",
")",
".",
"Hash160",
"(",
")",
"[",
":",
"]",
")",
"\n",
"return",
"result",
",",
"nil",
"\n\n",
"case",
"*",
"btcutil",
".",
"AddressWitnessScriptHash",
":",
"var",
"result",
"[",
"addrKeySize",
"]",
"byte",
"\n",
"result",
"[",
"0",
"]",
"=",
"addrKeyTypeWitnessScriptHash",
"\n\n",
"// P2WSH outputs utilize a 32-byte data push created by hashing",
"// the script with sha256 instead of hash160. In order to keep",
"// all address entries within the database uniform and compact,",
"// we use a hash160 here to reduce the size of the salient data",
"// push to 20-bytes.",
"copy",
"(",
"result",
"[",
"1",
":",
"]",
",",
"btcutil",
".",
"Hash160",
"(",
"addr",
".",
"ScriptAddress",
"(",
")",
")",
")",
"\n",
"return",
"result",
",",
"nil",
"\n\n",
"case",
"*",
"btcutil",
".",
"AddressWitnessPubKeyHash",
":",
"var",
"result",
"[",
"addrKeySize",
"]",
"byte",
"\n",
"result",
"[",
"0",
"]",
"=",
"addrKeyTypeWitnessPubKeyHash",
"\n",
"copy",
"(",
"result",
"[",
"1",
":",
"]",
",",
"addr",
".",
"Hash160",
"(",
")",
"[",
":",
"]",
")",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"[",
"addrKeySize",
"]",
"byte",
"{",
"}",
",",
"errUnsupportedAddressType",
"\n",
"}"
] | // addrToKey converts known address types to an addrindex key. An error is
// returned for unsupported types. | [
"addrToKey",
"converts",
"known",
"address",
"types",
"to",
"an",
"addrindex",
"key",
".",
"An",
"error",
"is",
"returned",
"for",
"unsupported",
"types",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/addrindex.go#L530-L570 | train |
btcsuite/btcd | blockchain/indexers/addrindex.go | Create | func (idx *AddrIndex) Create(dbTx database.Tx) error {
_, err := dbTx.Metadata().CreateBucket(addrIndexKey)
return err
} | go | func (idx *AddrIndex) Create(dbTx database.Tx) error {
_, err := dbTx.Metadata().CreateBucket(addrIndexKey)
return err
} | [
"func",
"(",
"idx",
"*",
"AddrIndex",
")",
"Create",
"(",
"dbTx",
"database",
".",
"Tx",
")",
"error",
"{",
"_",
",",
"err",
":=",
"dbTx",
".",
"Metadata",
"(",
")",
".",
"CreateBucket",
"(",
"addrIndexKey",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Create is invoked when the indexer manager determines the index needs
// to be created for the first time. It creates the bucket for the address
// index.
//
// This is part of the Indexer interface. | [
"Create",
"is",
"invoked",
"when",
"the",
"indexer",
"manager",
"determines",
"the",
"index",
"needs",
"to",
"be",
"created",
"for",
"the",
"first",
"time",
".",
"It",
"creates",
"the",
"bucket",
"for",
"the",
"address",
"index",
".",
"This",
"is",
"part",
"of",
"the",
"Indexer",
"interface",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/addrindex.go#L648-L651 | train |
btcsuite/btcd | blockchain/indexers/addrindex.go | indexPkScript | func (idx *AddrIndex) indexPkScript(data writeIndexData, pkScript []byte, txIdx int) {
// Nothing to index if the script is non-standard or otherwise doesn't
// contain any addresses.
_, addrs, _, err := txscript.ExtractPkScriptAddrs(pkScript,
idx.chainParams)
if err != nil || len(addrs) == 0 {
return
}
for _, addr := range addrs {
addrKey, err := addrToKey(addr)
if err != nil {
// Ignore unsupported address types.
continue
}
// Avoid inserting the transaction more than once. Since the
// transactions are indexed serially any duplicates will be
// indexed in a row, so checking the most recent entry for the
// address is enough to detect duplicates.
indexedTxns := data[addrKey]
numTxns := len(indexedTxns)
if numTxns > 0 && indexedTxns[numTxns-1] == txIdx {
continue
}
indexedTxns = append(indexedTxns, txIdx)
data[addrKey] = indexedTxns
}
} | go | func (idx *AddrIndex) indexPkScript(data writeIndexData, pkScript []byte, txIdx int) {
// Nothing to index if the script is non-standard or otherwise doesn't
// contain any addresses.
_, addrs, _, err := txscript.ExtractPkScriptAddrs(pkScript,
idx.chainParams)
if err != nil || len(addrs) == 0 {
return
}
for _, addr := range addrs {
addrKey, err := addrToKey(addr)
if err != nil {
// Ignore unsupported address types.
continue
}
// Avoid inserting the transaction more than once. Since the
// transactions are indexed serially any duplicates will be
// indexed in a row, so checking the most recent entry for the
// address is enough to detect duplicates.
indexedTxns := data[addrKey]
numTxns := len(indexedTxns)
if numTxns > 0 && indexedTxns[numTxns-1] == txIdx {
continue
}
indexedTxns = append(indexedTxns, txIdx)
data[addrKey] = indexedTxns
}
} | [
"func",
"(",
"idx",
"*",
"AddrIndex",
")",
"indexPkScript",
"(",
"data",
"writeIndexData",
",",
"pkScript",
"[",
"]",
"byte",
",",
"txIdx",
"int",
")",
"{",
"// Nothing to index if the script is non-standard or otherwise doesn't",
"// contain any addresses.",
"_",
",",
"addrs",
",",
"_",
",",
"err",
":=",
"txscript",
".",
"ExtractPkScriptAddrs",
"(",
"pkScript",
",",
"idx",
".",
"chainParams",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"len",
"(",
"addrs",
")",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"addr",
":=",
"range",
"addrs",
"{",
"addrKey",
",",
"err",
":=",
"addrToKey",
"(",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Ignore unsupported address types.",
"continue",
"\n",
"}",
"\n\n",
"// Avoid inserting the transaction more than once. Since the",
"// transactions are indexed serially any duplicates will be",
"// indexed in a row, so checking the most recent entry for the",
"// address is enough to detect duplicates.",
"indexedTxns",
":=",
"data",
"[",
"addrKey",
"]",
"\n",
"numTxns",
":=",
"len",
"(",
"indexedTxns",
")",
"\n",
"if",
"numTxns",
">",
"0",
"&&",
"indexedTxns",
"[",
"numTxns",
"-",
"1",
"]",
"==",
"txIdx",
"{",
"continue",
"\n",
"}",
"\n",
"indexedTxns",
"=",
"append",
"(",
"indexedTxns",
",",
"txIdx",
")",
"\n",
"data",
"[",
"addrKey",
"]",
"=",
"indexedTxns",
"\n",
"}",
"\n",
"}"
] | // indexPkScript extracts all standard addresses from the passed public key
// script and maps each of them to the associated transaction using the passed
// map. | [
"indexPkScript",
"extracts",
"all",
"standard",
"addresses",
"from",
"the",
"passed",
"public",
"key",
"script",
"and",
"maps",
"each",
"of",
"them",
"to",
"the",
"associated",
"transaction",
"using",
"the",
"passed",
"map",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/addrindex.go#L662-L690 | train |
btcsuite/btcd | blockchain/indexers/addrindex.go | indexBlock | func (idx *AddrIndex) indexBlock(data writeIndexData, block *btcutil.Block,
stxos []blockchain.SpentTxOut) {
stxoIndex := 0
for txIdx, tx := range block.Transactions() {
// Coinbases do not reference any inputs. Since the block is
// required to have already gone through full validation, it has
// already been proven on the first transaction in the block is
// a coinbase.
if txIdx != 0 {
for range tx.MsgTx().TxIn {
// We'll access the slice of all the
// transactions spent in this block properly
// ordered to fetch the previous input script.
pkScript := stxos[stxoIndex].PkScript
idx.indexPkScript(data, pkScript, txIdx)
// With an input indexed, we'll advance the
// stxo coutner.
stxoIndex++
}
}
for _, txOut := range tx.MsgTx().TxOut {
idx.indexPkScript(data, txOut.PkScript, txIdx)
}
}
} | go | func (idx *AddrIndex) indexBlock(data writeIndexData, block *btcutil.Block,
stxos []blockchain.SpentTxOut) {
stxoIndex := 0
for txIdx, tx := range block.Transactions() {
// Coinbases do not reference any inputs. Since the block is
// required to have already gone through full validation, it has
// already been proven on the first transaction in the block is
// a coinbase.
if txIdx != 0 {
for range tx.MsgTx().TxIn {
// We'll access the slice of all the
// transactions spent in this block properly
// ordered to fetch the previous input script.
pkScript := stxos[stxoIndex].PkScript
idx.indexPkScript(data, pkScript, txIdx)
// With an input indexed, we'll advance the
// stxo coutner.
stxoIndex++
}
}
for _, txOut := range tx.MsgTx().TxOut {
idx.indexPkScript(data, txOut.PkScript, txIdx)
}
}
} | [
"func",
"(",
"idx",
"*",
"AddrIndex",
")",
"indexBlock",
"(",
"data",
"writeIndexData",
",",
"block",
"*",
"btcutil",
".",
"Block",
",",
"stxos",
"[",
"]",
"blockchain",
".",
"SpentTxOut",
")",
"{",
"stxoIndex",
":=",
"0",
"\n",
"for",
"txIdx",
",",
"tx",
":=",
"range",
"block",
".",
"Transactions",
"(",
")",
"{",
"// Coinbases do not reference any inputs. Since the block is",
"// required to have already gone through full validation, it has",
"// already been proven on the first transaction in the block is",
"// a coinbase.",
"if",
"txIdx",
"!=",
"0",
"{",
"for",
"range",
"tx",
".",
"MsgTx",
"(",
")",
".",
"TxIn",
"{",
"// We'll access the slice of all the",
"// transactions spent in this block properly",
"// ordered to fetch the previous input script.",
"pkScript",
":=",
"stxos",
"[",
"stxoIndex",
"]",
".",
"PkScript",
"\n",
"idx",
".",
"indexPkScript",
"(",
"data",
",",
"pkScript",
",",
"txIdx",
")",
"\n\n",
"// With an input indexed, we'll advance the",
"// stxo coutner.",
"stxoIndex",
"++",
"\n",
"}",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"txOut",
":=",
"range",
"tx",
".",
"MsgTx",
"(",
")",
".",
"TxOut",
"{",
"idx",
".",
"indexPkScript",
"(",
"data",
",",
"txOut",
".",
"PkScript",
",",
"txIdx",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // indexBlock extract all of the standard addresses from all of the transactions
// in the passed block and maps each of them to the associated transaction using
// the passed map. | [
"indexBlock",
"extract",
"all",
"of",
"the",
"standard",
"addresses",
"from",
"all",
"of",
"the",
"transactions",
"in",
"the",
"passed",
"block",
"and",
"maps",
"each",
"of",
"them",
"to",
"the",
"associated",
"transaction",
"using",
"the",
"passed",
"map",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/addrindex.go#L695-L722 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.