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 | blockchain/indexers/addrindex.go | ConnectBlock | func (idx *AddrIndex) ConnectBlock(dbTx database.Tx, block *btcutil.Block,
stxos []blockchain.SpentTxOut) error {
// The offset and length of the transactions within the serialized
// block.
txLocs, err := block.TxLoc()
if err != nil {
return err
}
// Get the internal block ID associated with the block.
blockID, err := dbFetchBlockIDByHash(dbTx, block.Hash())
if err != nil {
return err
}
// Build all of the address to transaction mappings in a local map.
addrsToTxns := make(writeIndexData)
idx.indexBlock(addrsToTxns, block, stxos)
// Add all of the index entries for each address.
addrIdxBucket := dbTx.Metadata().Bucket(addrIndexKey)
for addrKey, txIdxs := range addrsToTxns {
for _, txIdx := range txIdxs {
err := dbPutAddrIndexEntry(addrIdxBucket, addrKey,
blockID, txLocs[txIdx])
if err != nil {
return err
}
}
}
return nil
} | go | func (idx *AddrIndex) ConnectBlock(dbTx database.Tx, block *btcutil.Block,
stxos []blockchain.SpentTxOut) error {
// The offset and length of the transactions within the serialized
// block.
txLocs, err := block.TxLoc()
if err != nil {
return err
}
// Get the internal block ID associated with the block.
blockID, err := dbFetchBlockIDByHash(dbTx, block.Hash())
if err != nil {
return err
}
// Build all of the address to transaction mappings in a local map.
addrsToTxns := make(writeIndexData)
idx.indexBlock(addrsToTxns, block, stxos)
// Add all of the index entries for each address.
addrIdxBucket := dbTx.Metadata().Bucket(addrIndexKey)
for addrKey, txIdxs := range addrsToTxns {
for _, txIdx := range txIdxs {
err := dbPutAddrIndexEntry(addrIdxBucket, addrKey,
blockID, txLocs[txIdx])
if err != nil {
return err
}
}
}
return nil
} | [
"func",
"(",
"idx",
"*",
"AddrIndex",
")",
"ConnectBlock",
"(",
"dbTx",
"database",
".",
"Tx",
",",
"block",
"*",
"btcutil",
".",
"Block",
",",
"stxos",
"[",
"]",
"blockchain",
".",
"SpentTxOut",
")",
"error",
"{",
"// The offset and length of the transactions within the serialized",
"// block.",
"txLocs",
",",
"err",
":=",
"block",
".",
"TxLoc",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Get the internal block ID associated with the block.",
"blockID",
",",
"err",
":=",
"dbFetchBlockIDByHash",
"(",
"dbTx",
",",
"block",
".",
"Hash",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Build all of the address to transaction mappings in a local map.",
"addrsToTxns",
":=",
"make",
"(",
"writeIndexData",
")",
"\n",
"idx",
".",
"indexBlock",
"(",
"addrsToTxns",
",",
"block",
",",
"stxos",
")",
"\n\n",
"// Add all of the index entries for each address.",
"addrIdxBucket",
":=",
"dbTx",
".",
"Metadata",
"(",
")",
".",
"Bucket",
"(",
"addrIndexKey",
")",
"\n",
"for",
"addrKey",
",",
"txIdxs",
":=",
"range",
"addrsToTxns",
"{",
"for",
"_",
",",
"txIdx",
":=",
"range",
"txIdxs",
"{",
"err",
":=",
"dbPutAddrIndexEntry",
"(",
"addrIdxBucket",
",",
"addrKey",
",",
"blockID",
",",
"txLocs",
"[",
"txIdx",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // ConnectBlock is invoked by the index manager when a new block has been
// connected to the main chain. This indexer adds a mapping for each address
// the transactions in the block involve.
//
// This is part of the Indexer interface. | [
"ConnectBlock",
"is",
"invoked",
"by",
"the",
"index",
"manager",
"when",
"a",
"new",
"block",
"has",
"been",
"connected",
"to",
"the",
"main",
"chain",
".",
"This",
"indexer",
"adds",
"a",
"mapping",
"for",
"each",
"address",
"the",
"transactions",
"in",
"the",
"block",
"involve",
".",
"This",
"is",
"part",
"of",
"the",
"Indexer",
"interface",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/addrindex.go#L729-L762 | train |
btcsuite/btcd | blockchain/indexers/addrindex.go | DisconnectBlock | func (idx *AddrIndex) DisconnectBlock(dbTx database.Tx, block *btcutil.Block,
stxos []blockchain.SpentTxOut) error {
// Build all of the address to transaction mappings in a local map.
addrsToTxns := make(writeIndexData)
idx.indexBlock(addrsToTxns, block, stxos)
// Remove all of the index entries for each address.
bucket := dbTx.Metadata().Bucket(addrIndexKey)
for addrKey, txIdxs := range addrsToTxns {
err := dbRemoveAddrIndexEntries(bucket, addrKey, len(txIdxs))
if err != nil {
return err
}
}
return nil
} | go | func (idx *AddrIndex) DisconnectBlock(dbTx database.Tx, block *btcutil.Block,
stxos []blockchain.SpentTxOut) error {
// Build all of the address to transaction mappings in a local map.
addrsToTxns := make(writeIndexData)
idx.indexBlock(addrsToTxns, block, stxos)
// Remove all of the index entries for each address.
bucket := dbTx.Metadata().Bucket(addrIndexKey)
for addrKey, txIdxs := range addrsToTxns {
err := dbRemoveAddrIndexEntries(bucket, addrKey, len(txIdxs))
if err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"idx",
"*",
"AddrIndex",
")",
"DisconnectBlock",
"(",
"dbTx",
"database",
".",
"Tx",
",",
"block",
"*",
"btcutil",
".",
"Block",
",",
"stxos",
"[",
"]",
"blockchain",
".",
"SpentTxOut",
")",
"error",
"{",
"// Build all of the address to transaction mappings in a local map.",
"addrsToTxns",
":=",
"make",
"(",
"writeIndexData",
")",
"\n",
"idx",
".",
"indexBlock",
"(",
"addrsToTxns",
",",
"block",
",",
"stxos",
")",
"\n\n",
"// Remove all of the index entries for each address.",
"bucket",
":=",
"dbTx",
".",
"Metadata",
"(",
")",
".",
"Bucket",
"(",
"addrIndexKey",
")",
"\n",
"for",
"addrKey",
",",
"txIdxs",
":=",
"range",
"addrsToTxns",
"{",
"err",
":=",
"dbRemoveAddrIndexEntries",
"(",
"bucket",
",",
"addrKey",
",",
"len",
"(",
"txIdxs",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // DisconnectBlock is invoked by the index manager when a block has been
// disconnected from the main chain. This indexer removes the address mappings
// each transaction in the block involve.
//
// This is part of the Indexer interface. | [
"DisconnectBlock",
"is",
"invoked",
"by",
"the",
"index",
"manager",
"when",
"a",
"block",
"has",
"been",
"disconnected",
"from",
"the",
"main",
"chain",
".",
"This",
"indexer",
"removes",
"the",
"address",
"mappings",
"each",
"transaction",
"in",
"the",
"block",
"involve",
".",
"This",
"is",
"part",
"of",
"the",
"Indexer",
"interface",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/addrindex.go#L769-L786 | train |
btcsuite/btcd | blockchain/indexers/addrindex.go | NewAddrIndex | func NewAddrIndex(db database.DB, chainParams *chaincfg.Params) *AddrIndex {
return &AddrIndex{
db: db,
chainParams: chainParams,
txnsByAddr: make(map[[addrKeySize]byte]map[chainhash.Hash]*btcutil.Tx),
addrsByTx: make(map[chainhash.Hash]map[[addrKeySize]byte]struct{}),
}
} | go | func NewAddrIndex(db database.DB, chainParams *chaincfg.Params) *AddrIndex {
return &AddrIndex{
db: db,
chainParams: chainParams,
txnsByAddr: make(map[[addrKeySize]byte]map[chainhash.Hash]*btcutil.Tx),
addrsByTx: make(map[chainhash.Hash]map[[addrKeySize]byte]struct{}),
}
} | [
"func",
"NewAddrIndex",
"(",
"db",
"database",
".",
"DB",
",",
"chainParams",
"*",
"chaincfg",
".",
"Params",
")",
"*",
"AddrIndex",
"{",
"return",
"&",
"AddrIndex",
"{",
"db",
":",
"db",
",",
"chainParams",
":",
"chainParams",
",",
"txnsByAddr",
":",
"make",
"(",
"map",
"[",
"[",
"addrKeySize",
"]",
"byte",
"]",
"map",
"[",
"chainhash",
".",
"Hash",
"]",
"*",
"btcutil",
".",
"Tx",
")",
",",
"addrsByTx",
":",
"make",
"(",
"map",
"[",
"chainhash",
".",
"Hash",
"]",
"map",
"[",
"[",
"addrKeySize",
"]",
"byte",
"]",
"struct",
"{",
"}",
")",
",",
"}",
"\n",
"}"
] | // NewAddrIndex returns a new instance of an indexer that is used to create a
// mapping of all addresses in the blockchain to the respective transactions
// that involve them.
//
// It implements the Indexer interface which plugs into the IndexManager that in
// turn is used by the blockchain package. This allows the index to be
// seamlessly maintained along with the chain. | [
"NewAddrIndex",
"returns",
"a",
"new",
"instance",
"of",
"an",
"indexer",
"that",
"is",
"used",
"to",
"create",
"a",
"mapping",
"of",
"all",
"addresses",
"in",
"the",
"blockchain",
"to",
"the",
"respective",
"transactions",
"that",
"involve",
"them",
".",
"It",
"implements",
"the",
"Indexer",
"interface",
"which",
"plugs",
"into",
"the",
"IndexManager",
"that",
"in",
"turn",
"is",
"used",
"by",
"the",
"blockchain",
"package",
".",
"This",
"allows",
"the",
"index",
"to",
"be",
"seamlessly",
"maintained",
"along",
"with",
"the",
"chain",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/addrindex.go#L954-L961 | train |
btcsuite/btcd | blockchain/indexers/addrindex.go | DropAddrIndex | func DropAddrIndex(db database.DB, interrupt <-chan struct{}) error {
return dropIndex(db, addrIndexKey, addrIndexName, interrupt)
} | go | func DropAddrIndex(db database.DB, interrupt <-chan struct{}) error {
return dropIndex(db, addrIndexKey, addrIndexName, interrupt)
} | [
"func",
"DropAddrIndex",
"(",
"db",
"database",
".",
"DB",
",",
"interrupt",
"<-",
"chan",
"struct",
"{",
"}",
")",
"error",
"{",
"return",
"dropIndex",
"(",
"db",
",",
"addrIndexKey",
",",
"addrIndexName",
",",
"interrupt",
")",
"\n",
"}"
] | // DropAddrIndex drops the address index from the provided database if it
// exists. | [
"DropAddrIndex",
"drops",
"the",
"address",
"index",
"from",
"the",
"provided",
"database",
"if",
"it",
"exists",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/addrindex.go#L965-L967 | train |
btcsuite/btcd | wire/msgtx.go | Borrow | func (c scriptFreeList) Borrow(size uint64) []byte {
if size > freeListMaxScriptSize {
return make([]byte, size)
}
var buf []byte
select {
case buf = <-c:
default:
buf = make([]byte, freeListMaxScriptSize)
}
return buf[:size]
} | go | func (c scriptFreeList) Borrow(size uint64) []byte {
if size > freeListMaxScriptSize {
return make([]byte, size)
}
var buf []byte
select {
case buf = <-c:
default:
buf = make([]byte, freeListMaxScriptSize)
}
return buf[:size]
} | [
"func",
"(",
"c",
"scriptFreeList",
")",
"Borrow",
"(",
"size",
"uint64",
")",
"[",
"]",
"byte",
"{",
"if",
"size",
">",
"freeListMaxScriptSize",
"{",
"return",
"make",
"(",
"[",
"]",
"byte",
",",
"size",
")",
"\n",
"}",
"\n\n",
"var",
"buf",
"[",
"]",
"byte",
"\n",
"select",
"{",
"case",
"buf",
"=",
"<-",
"c",
":",
"default",
":",
"buf",
"=",
"make",
"(",
"[",
"]",
"byte",
",",
"freeListMaxScriptSize",
")",
"\n",
"}",
"\n",
"return",
"buf",
"[",
":",
"size",
"]",
"\n",
"}"
] | // Borrow returns a byte slice from the free list with a length according the
// provided size. A new buffer is allocated if there are any items available.
//
// When the size is larger than the max size allowed for items on the free list
// a new buffer of the appropriate size is allocated and returned. It is safe
// to attempt to return said buffer via the Return function as it will be
// ignored and allowed to go the garbage collector. | [
"Borrow",
"returns",
"a",
"byte",
"slice",
"from",
"the",
"free",
"list",
"with",
"a",
"length",
"according",
"the",
"provided",
"size",
".",
"A",
"new",
"buffer",
"is",
"allocated",
"if",
"there",
"are",
"any",
"items",
"available",
".",
"When",
"the",
"size",
"is",
"larger",
"than",
"the",
"max",
"size",
"allowed",
"for",
"items",
"on",
"the",
"free",
"list",
"a",
"new",
"buffer",
"of",
"the",
"appropriate",
"size",
"is",
"allocated",
"and",
"returned",
".",
"It",
"is",
"safe",
"to",
"attempt",
"to",
"return",
"said",
"buffer",
"via",
"the",
"Return",
"function",
"as",
"it",
"will",
"be",
"ignored",
"and",
"allowed",
"to",
"go",
"the",
"garbage",
"collector",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgtx.go#L138-L150 | train |
btcsuite/btcd | wire/msgtx.go | Return | func (c scriptFreeList) Return(buf []byte) {
// Ignore any buffers returned that aren't the expected size for the
// free list.
if cap(buf) != freeListMaxScriptSize {
return
}
// Return the buffer to the free list when it's not full. Otherwise let
// it be garbage collected.
select {
case c <- buf:
default:
// Let it go to the garbage collector.
}
} | go | func (c scriptFreeList) Return(buf []byte) {
// Ignore any buffers returned that aren't the expected size for the
// free list.
if cap(buf) != freeListMaxScriptSize {
return
}
// Return the buffer to the free list when it's not full. Otherwise let
// it be garbage collected.
select {
case c <- buf:
default:
// Let it go to the garbage collector.
}
} | [
"func",
"(",
"c",
"scriptFreeList",
")",
"Return",
"(",
"buf",
"[",
"]",
"byte",
")",
"{",
"// Ignore any buffers returned that aren't the expected size for the",
"// free list.",
"if",
"cap",
"(",
"buf",
")",
"!=",
"freeListMaxScriptSize",
"{",
"return",
"\n",
"}",
"\n\n",
"// Return the buffer to the free list when it's not full. Otherwise let",
"// it be garbage collected.",
"select",
"{",
"case",
"c",
"<-",
"buf",
":",
"default",
":",
"// Let it go to the garbage collector.",
"}",
"\n",
"}"
] | // Return puts the provided byte slice back on the free list when it has a cap
// of the expected length. The buffer is expected to have been obtained via
// the Borrow function. Any slices that are not of the appropriate size, such
// as those whose size is greater than the largest allowed free list item size
// are simply ignored so they can go to the garbage collector. | [
"Return",
"puts",
"the",
"provided",
"byte",
"slice",
"back",
"on",
"the",
"free",
"list",
"when",
"it",
"has",
"a",
"cap",
"of",
"the",
"expected",
"length",
".",
"The",
"buffer",
"is",
"expected",
"to",
"have",
"been",
"obtained",
"via",
"the",
"Borrow",
"function",
".",
"Any",
"slices",
"that",
"are",
"not",
"of",
"the",
"appropriate",
"size",
"such",
"as",
"those",
"whose",
"size",
"is",
"greater",
"than",
"the",
"largest",
"allowed",
"free",
"list",
"item",
"size",
"are",
"simply",
"ignored",
"so",
"they",
"can",
"go",
"to",
"the",
"garbage",
"collector",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgtx.go#L157-L171 | train |
btcsuite/btcd | wire/msgtx.go | NewOutPoint | func NewOutPoint(hash *chainhash.Hash, index uint32) *OutPoint {
return &OutPoint{
Hash: *hash,
Index: index,
}
} | go | func NewOutPoint(hash *chainhash.Hash, index uint32) *OutPoint {
return &OutPoint{
Hash: *hash,
Index: index,
}
} | [
"func",
"NewOutPoint",
"(",
"hash",
"*",
"chainhash",
".",
"Hash",
",",
"index",
"uint32",
")",
"*",
"OutPoint",
"{",
"return",
"&",
"OutPoint",
"{",
"Hash",
":",
"*",
"hash",
",",
"Index",
":",
"index",
",",
"}",
"\n",
"}"
] | // NewOutPoint returns a new bitcoin transaction outpoint point with the
// provided hash and index. | [
"NewOutPoint",
"returns",
"a",
"new",
"bitcoin",
"transaction",
"outpoint",
"point",
"with",
"the",
"provided",
"hash",
"and",
"index",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgtx.go#L187-L192 | train |
btcsuite/btcd | wire/msgtx.go | SerializeSize | func (t *TxIn) SerializeSize() int {
// Outpoint Hash 32 bytes + Outpoint Index 4 bytes + Sequence 4 bytes +
// serialized varint size for the length of SignatureScript +
// SignatureScript bytes.
return 40 + VarIntSerializeSize(uint64(len(t.SignatureScript))) +
len(t.SignatureScript)
} | go | func (t *TxIn) SerializeSize() int {
// Outpoint Hash 32 bytes + Outpoint Index 4 bytes + Sequence 4 bytes +
// serialized varint size for the length of SignatureScript +
// SignatureScript bytes.
return 40 + VarIntSerializeSize(uint64(len(t.SignatureScript))) +
len(t.SignatureScript)
} | [
"func",
"(",
"t",
"*",
"TxIn",
")",
"SerializeSize",
"(",
")",
"int",
"{",
"// Outpoint Hash 32 bytes + Outpoint Index 4 bytes + Sequence 4 bytes +",
"// serialized varint size for the length of SignatureScript +",
"// SignatureScript bytes.",
"return",
"40",
"+",
"VarIntSerializeSize",
"(",
"uint64",
"(",
"len",
"(",
"t",
".",
"SignatureScript",
")",
")",
")",
"+",
"len",
"(",
"t",
".",
"SignatureScript",
")",
"\n",
"}"
] | // SerializeSize returns the number of bytes it would take to serialize the
// the transaction input. | [
"SerializeSize",
"returns",
"the",
"number",
"of",
"bytes",
"it",
"would",
"take",
"to",
"serialize",
"the",
"the",
"transaction",
"input",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgtx.go#L219-L225 | train |
btcsuite/btcd | wire/msgtx.go | NewTxIn | func NewTxIn(prevOut *OutPoint, signatureScript []byte, witness [][]byte) *TxIn {
return &TxIn{
PreviousOutPoint: *prevOut,
SignatureScript: signatureScript,
Witness: witness,
Sequence: MaxTxInSequenceNum,
}
} | go | func NewTxIn(prevOut *OutPoint, signatureScript []byte, witness [][]byte) *TxIn {
return &TxIn{
PreviousOutPoint: *prevOut,
SignatureScript: signatureScript,
Witness: witness,
Sequence: MaxTxInSequenceNum,
}
} | [
"func",
"NewTxIn",
"(",
"prevOut",
"*",
"OutPoint",
",",
"signatureScript",
"[",
"]",
"byte",
",",
"witness",
"[",
"]",
"[",
"]",
"byte",
")",
"*",
"TxIn",
"{",
"return",
"&",
"TxIn",
"{",
"PreviousOutPoint",
":",
"*",
"prevOut",
",",
"SignatureScript",
":",
"signatureScript",
",",
"Witness",
":",
"witness",
",",
"Sequence",
":",
"MaxTxInSequenceNum",
",",
"}",
"\n",
"}"
] | // NewTxIn returns a new bitcoin transaction input with the provided
// previous outpoint point and signature script with a default sequence of
// MaxTxInSequenceNum. | [
"NewTxIn",
"returns",
"a",
"new",
"bitcoin",
"transaction",
"input",
"with",
"the",
"provided",
"previous",
"outpoint",
"point",
"and",
"signature",
"script",
"with",
"a",
"default",
"sequence",
"of",
"MaxTxInSequenceNum",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgtx.go#L230-L237 | train |
btcsuite/btcd | wire/msgtx.go | SerializeSize | func (t TxWitness) SerializeSize() int {
// A varint to signal the number of elements the witness has.
n := VarIntSerializeSize(uint64(len(t)))
// For each element in the witness, we'll need a varint to signal the
// size of the element, then finally the number of bytes the element
// itself comprises.
for _, witItem := range t {
n += VarIntSerializeSize(uint64(len(witItem)))
n += len(witItem)
}
return n
} | go | func (t TxWitness) SerializeSize() int {
// A varint to signal the number of elements the witness has.
n := VarIntSerializeSize(uint64(len(t)))
// For each element in the witness, we'll need a varint to signal the
// size of the element, then finally the number of bytes the element
// itself comprises.
for _, witItem := range t {
n += VarIntSerializeSize(uint64(len(witItem)))
n += len(witItem)
}
return n
} | [
"func",
"(",
"t",
"TxWitness",
")",
"SerializeSize",
"(",
")",
"int",
"{",
"// A varint to signal the number of elements the witness has.",
"n",
":=",
"VarIntSerializeSize",
"(",
"uint64",
"(",
"len",
"(",
"t",
")",
")",
")",
"\n\n",
"// For each element in the witness, we'll need a varint to signal the",
"// size of the element, then finally the number of bytes the element",
"// itself comprises.",
"for",
"_",
",",
"witItem",
":=",
"range",
"t",
"{",
"n",
"+=",
"VarIntSerializeSize",
"(",
"uint64",
"(",
"len",
"(",
"witItem",
")",
")",
")",
"\n",
"n",
"+=",
"len",
"(",
"witItem",
")",
"\n",
"}",
"\n\n",
"return",
"n",
"\n",
"}"
] | // SerializeSize returns the number of bytes it would take to serialize the the
// transaction input's witness. | [
"SerializeSize",
"returns",
"the",
"number",
"of",
"bytes",
"it",
"would",
"take",
"to",
"serialize",
"the",
"the",
"transaction",
"input",
"s",
"witness",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgtx.go#L245-L258 | train |
btcsuite/btcd | wire/msgtx.go | SerializeSize | func (t *TxOut) SerializeSize() int {
// Value 8 bytes + serialized varint size for the length of PkScript +
// PkScript bytes.
return 8 + VarIntSerializeSize(uint64(len(t.PkScript))) + len(t.PkScript)
} | go | func (t *TxOut) SerializeSize() int {
// Value 8 bytes + serialized varint size for the length of PkScript +
// PkScript bytes.
return 8 + VarIntSerializeSize(uint64(len(t.PkScript))) + len(t.PkScript)
} | [
"func",
"(",
"t",
"*",
"TxOut",
")",
"SerializeSize",
"(",
")",
"int",
"{",
"// Value 8 bytes + serialized varint size for the length of PkScript +",
"// PkScript bytes.",
"return",
"8",
"+",
"VarIntSerializeSize",
"(",
"uint64",
"(",
"len",
"(",
"t",
".",
"PkScript",
")",
")",
")",
"+",
"len",
"(",
"t",
".",
"PkScript",
")",
"\n",
"}"
] | // SerializeSize returns the number of bytes it would take to serialize the
// the transaction output. | [
"SerializeSize",
"returns",
"the",
"number",
"of",
"bytes",
"it",
"would",
"take",
"to",
"serialize",
"the",
"the",
"transaction",
"output",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgtx.go#L268-L272 | train |
btcsuite/btcd | wire/msgtx.go | NewTxOut | func NewTxOut(value int64, pkScript []byte) *TxOut {
return &TxOut{
Value: value,
PkScript: pkScript,
}
} | go | func NewTxOut(value int64, pkScript []byte) *TxOut {
return &TxOut{
Value: value,
PkScript: pkScript,
}
} | [
"func",
"NewTxOut",
"(",
"value",
"int64",
",",
"pkScript",
"[",
"]",
"byte",
")",
"*",
"TxOut",
"{",
"return",
"&",
"TxOut",
"{",
"Value",
":",
"value",
",",
"PkScript",
":",
"pkScript",
",",
"}",
"\n",
"}"
] | // NewTxOut returns a new bitcoin transaction output with the provided
// transaction value and public key script. | [
"NewTxOut",
"returns",
"a",
"new",
"bitcoin",
"transaction",
"output",
"with",
"the",
"provided",
"transaction",
"value",
"and",
"public",
"key",
"script",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgtx.go#L276-L281 | train |
btcsuite/btcd | wire/msgtx.go | AddTxIn | func (msg *MsgTx) AddTxIn(ti *TxIn) {
msg.TxIn = append(msg.TxIn, ti)
} | go | func (msg *MsgTx) AddTxIn(ti *TxIn) {
msg.TxIn = append(msg.TxIn, ti)
} | [
"func",
"(",
"msg",
"*",
"MsgTx",
")",
"AddTxIn",
"(",
"ti",
"*",
"TxIn",
")",
"{",
"msg",
".",
"TxIn",
"=",
"append",
"(",
"msg",
".",
"TxIn",
",",
"ti",
")",
"\n",
"}"
] | // AddTxIn adds a transaction input to the message. | [
"AddTxIn",
"adds",
"a",
"transaction",
"input",
"to",
"the",
"message",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgtx.go#L297-L299 | train |
btcsuite/btcd | wire/msgtx.go | AddTxOut | func (msg *MsgTx) AddTxOut(to *TxOut) {
msg.TxOut = append(msg.TxOut, to)
} | go | func (msg *MsgTx) AddTxOut(to *TxOut) {
msg.TxOut = append(msg.TxOut, to)
} | [
"func",
"(",
"msg",
"*",
"MsgTx",
")",
"AddTxOut",
"(",
"to",
"*",
"TxOut",
")",
"{",
"msg",
".",
"TxOut",
"=",
"append",
"(",
"msg",
".",
"TxOut",
",",
"to",
")",
"\n",
"}"
] | // AddTxOut adds a transaction output to the message. | [
"AddTxOut",
"adds",
"a",
"transaction",
"output",
"to",
"the",
"message",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgtx.go#L302-L304 | train |
btcsuite/btcd | wire/msgtx.go | TxHash | func (msg *MsgTx) TxHash() chainhash.Hash {
// Encode the transaction and calculate double sha256 on the result.
// Ignore the error returns since the only way the encode could fail
// is being out of memory or due to nil pointers, both of which would
// cause a run-time panic.
buf := bytes.NewBuffer(make([]byte, 0, msg.SerializeSizeStripped()))
_ = msg.SerializeNoWitness(buf)
return chainhash.DoubleHashH(buf.Bytes())
} | go | func (msg *MsgTx) TxHash() chainhash.Hash {
// Encode the transaction and calculate double sha256 on the result.
// Ignore the error returns since the only way the encode could fail
// is being out of memory or due to nil pointers, both of which would
// cause a run-time panic.
buf := bytes.NewBuffer(make([]byte, 0, msg.SerializeSizeStripped()))
_ = msg.SerializeNoWitness(buf)
return chainhash.DoubleHashH(buf.Bytes())
} | [
"func",
"(",
"msg",
"*",
"MsgTx",
")",
"TxHash",
"(",
")",
"chainhash",
".",
"Hash",
"{",
"// Encode the transaction and calculate double sha256 on the result.",
"// Ignore the error returns since the only way the encode could fail",
"// is being out of memory or due to nil pointers, both of which would",
"// cause a run-time panic.",
"buf",
":=",
"bytes",
".",
"NewBuffer",
"(",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"msg",
".",
"SerializeSizeStripped",
"(",
")",
")",
")",
"\n",
"_",
"=",
"msg",
".",
"SerializeNoWitness",
"(",
"buf",
")",
"\n",
"return",
"chainhash",
".",
"DoubleHashH",
"(",
"buf",
".",
"Bytes",
"(",
")",
")",
"\n",
"}"
] | // TxHash generates the Hash for the transaction. | [
"TxHash",
"generates",
"the",
"Hash",
"for",
"the",
"transaction",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgtx.go#L307-L315 | train |
btcsuite/btcd | wire/msgtx.go | WitnessHash | func (msg *MsgTx) WitnessHash() chainhash.Hash {
if msg.HasWitness() {
buf := bytes.NewBuffer(make([]byte, 0, msg.SerializeSize()))
_ = msg.Serialize(buf)
return chainhash.DoubleHashH(buf.Bytes())
}
return msg.TxHash()
} | go | func (msg *MsgTx) WitnessHash() chainhash.Hash {
if msg.HasWitness() {
buf := bytes.NewBuffer(make([]byte, 0, msg.SerializeSize()))
_ = msg.Serialize(buf)
return chainhash.DoubleHashH(buf.Bytes())
}
return msg.TxHash()
} | [
"func",
"(",
"msg",
"*",
"MsgTx",
")",
"WitnessHash",
"(",
")",
"chainhash",
".",
"Hash",
"{",
"if",
"msg",
".",
"HasWitness",
"(",
")",
"{",
"buf",
":=",
"bytes",
".",
"NewBuffer",
"(",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"msg",
".",
"SerializeSize",
"(",
")",
")",
")",
"\n",
"_",
"=",
"msg",
".",
"Serialize",
"(",
"buf",
")",
"\n",
"return",
"chainhash",
".",
"DoubleHashH",
"(",
"buf",
".",
"Bytes",
"(",
")",
")",
"\n",
"}",
"\n\n",
"return",
"msg",
".",
"TxHash",
"(",
")",
"\n",
"}"
] | // WitnessHash generates the hash of the transaction serialized according to
// the new witness serialization defined in BIP0141 and BIP0144. The final
// output is used within the Segregated Witness commitment of all the witnesses
// within a block. If a transaction has no witness data, then the witness hash,
// is the same as its txid. | [
"WitnessHash",
"generates",
"the",
"hash",
"of",
"the",
"transaction",
"serialized",
"according",
"to",
"the",
"new",
"witness",
"serialization",
"defined",
"in",
"BIP0141",
"and",
"BIP0144",
".",
"The",
"final",
"output",
"is",
"used",
"within",
"the",
"Segregated",
"Witness",
"commitment",
"of",
"all",
"the",
"witnesses",
"within",
"a",
"block",
".",
"If",
"a",
"transaction",
"has",
"no",
"witness",
"data",
"then",
"the",
"witness",
"hash",
"is",
"the",
"same",
"as",
"its",
"txid",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgtx.go#L322-L330 | train |
btcsuite/btcd | wire/msgtx.go | Copy | func (msg *MsgTx) Copy() *MsgTx {
// Create new tx and start by copying primitive values and making space
// for the transaction inputs and outputs.
newTx := MsgTx{
Version: msg.Version,
TxIn: make([]*TxIn, 0, len(msg.TxIn)),
TxOut: make([]*TxOut, 0, len(msg.TxOut)),
LockTime: msg.LockTime,
}
// Deep copy the old TxIn data.
for _, oldTxIn := range msg.TxIn {
// Deep copy the old previous outpoint.
oldOutPoint := oldTxIn.PreviousOutPoint
newOutPoint := OutPoint{}
newOutPoint.Hash.SetBytes(oldOutPoint.Hash[:])
newOutPoint.Index = oldOutPoint.Index
// Deep copy the old signature script.
var newScript []byte
oldScript := oldTxIn.SignatureScript
oldScriptLen := len(oldScript)
if oldScriptLen > 0 {
newScript = make([]byte, oldScriptLen)
copy(newScript, oldScript[:oldScriptLen])
}
// Create new txIn with the deep copied data.
newTxIn := TxIn{
PreviousOutPoint: newOutPoint,
SignatureScript: newScript,
Sequence: oldTxIn.Sequence,
}
// If the transaction is witnessy, then also copy the
// witnesses.
if len(oldTxIn.Witness) != 0 {
// Deep copy the old witness data.
newTxIn.Witness = make([][]byte, len(oldTxIn.Witness))
for i, oldItem := range oldTxIn.Witness {
newItem := make([]byte, len(oldItem))
copy(newItem, oldItem)
newTxIn.Witness[i] = newItem
}
}
// Finally, append this fully copied txin.
newTx.TxIn = append(newTx.TxIn, &newTxIn)
}
// Deep copy the old TxOut data.
for _, oldTxOut := range msg.TxOut {
// Deep copy the old PkScript
var newScript []byte
oldScript := oldTxOut.PkScript
oldScriptLen := len(oldScript)
if oldScriptLen > 0 {
newScript = make([]byte, oldScriptLen)
copy(newScript, oldScript[:oldScriptLen])
}
// Create new txOut with the deep copied data and append it to
// new Tx.
newTxOut := TxOut{
Value: oldTxOut.Value,
PkScript: newScript,
}
newTx.TxOut = append(newTx.TxOut, &newTxOut)
}
return &newTx
} | go | func (msg *MsgTx) Copy() *MsgTx {
// Create new tx and start by copying primitive values and making space
// for the transaction inputs and outputs.
newTx := MsgTx{
Version: msg.Version,
TxIn: make([]*TxIn, 0, len(msg.TxIn)),
TxOut: make([]*TxOut, 0, len(msg.TxOut)),
LockTime: msg.LockTime,
}
// Deep copy the old TxIn data.
for _, oldTxIn := range msg.TxIn {
// Deep copy the old previous outpoint.
oldOutPoint := oldTxIn.PreviousOutPoint
newOutPoint := OutPoint{}
newOutPoint.Hash.SetBytes(oldOutPoint.Hash[:])
newOutPoint.Index = oldOutPoint.Index
// Deep copy the old signature script.
var newScript []byte
oldScript := oldTxIn.SignatureScript
oldScriptLen := len(oldScript)
if oldScriptLen > 0 {
newScript = make([]byte, oldScriptLen)
copy(newScript, oldScript[:oldScriptLen])
}
// Create new txIn with the deep copied data.
newTxIn := TxIn{
PreviousOutPoint: newOutPoint,
SignatureScript: newScript,
Sequence: oldTxIn.Sequence,
}
// If the transaction is witnessy, then also copy the
// witnesses.
if len(oldTxIn.Witness) != 0 {
// Deep copy the old witness data.
newTxIn.Witness = make([][]byte, len(oldTxIn.Witness))
for i, oldItem := range oldTxIn.Witness {
newItem := make([]byte, len(oldItem))
copy(newItem, oldItem)
newTxIn.Witness[i] = newItem
}
}
// Finally, append this fully copied txin.
newTx.TxIn = append(newTx.TxIn, &newTxIn)
}
// Deep copy the old TxOut data.
for _, oldTxOut := range msg.TxOut {
// Deep copy the old PkScript
var newScript []byte
oldScript := oldTxOut.PkScript
oldScriptLen := len(oldScript)
if oldScriptLen > 0 {
newScript = make([]byte, oldScriptLen)
copy(newScript, oldScript[:oldScriptLen])
}
// Create new txOut with the deep copied data and append it to
// new Tx.
newTxOut := TxOut{
Value: oldTxOut.Value,
PkScript: newScript,
}
newTx.TxOut = append(newTx.TxOut, &newTxOut)
}
return &newTx
} | [
"func",
"(",
"msg",
"*",
"MsgTx",
")",
"Copy",
"(",
")",
"*",
"MsgTx",
"{",
"// Create new tx and start by copying primitive values and making space",
"// for the transaction inputs and outputs.",
"newTx",
":=",
"MsgTx",
"{",
"Version",
":",
"msg",
".",
"Version",
",",
"TxIn",
":",
"make",
"(",
"[",
"]",
"*",
"TxIn",
",",
"0",
",",
"len",
"(",
"msg",
".",
"TxIn",
")",
")",
",",
"TxOut",
":",
"make",
"(",
"[",
"]",
"*",
"TxOut",
",",
"0",
",",
"len",
"(",
"msg",
".",
"TxOut",
")",
")",
",",
"LockTime",
":",
"msg",
".",
"LockTime",
",",
"}",
"\n\n",
"// Deep copy the old TxIn data.",
"for",
"_",
",",
"oldTxIn",
":=",
"range",
"msg",
".",
"TxIn",
"{",
"// Deep copy the old previous outpoint.",
"oldOutPoint",
":=",
"oldTxIn",
".",
"PreviousOutPoint",
"\n",
"newOutPoint",
":=",
"OutPoint",
"{",
"}",
"\n",
"newOutPoint",
".",
"Hash",
".",
"SetBytes",
"(",
"oldOutPoint",
".",
"Hash",
"[",
":",
"]",
")",
"\n",
"newOutPoint",
".",
"Index",
"=",
"oldOutPoint",
".",
"Index",
"\n\n",
"// Deep copy the old signature script.",
"var",
"newScript",
"[",
"]",
"byte",
"\n",
"oldScript",
":=",
"oldTxIn",
".",
"SignatureScript",
"\n",
"oldScriptLen",
":=",
"len",
"(",
"oldScript",
")",
"\n",
"if",
"oldScriptLen",
">",
"0",
"{",
"newScript",
"=",
"make",
"(",
"[",
"]",
"byte",
",",
"oldScriptLen",
")",
"\n",
"copy",
"(",
"newScript",
",",
"oldScript",
"[",
":",
"oldScriptLen",
"]",
")",
"\n",
"}",
"\n\n",
"// Create new txIn with the deep copied data.",
"newTxIn",
":=",
"TxIn",
"{",
"PreviousOutPoint",
":",
"newOutPoint",
",",
"SignatureScript",
":",
"newScript",
",",
"Sequence",
":",
"oldTxIn",
".",
"Sequence",
",",
"}",
"\n\n",
"// If the transaction is witnessy, then also copy the",
"// witnesses.",
"if",
"len",
"(",
"oldTxIn",
".",
"Witness",
")",
"!=",
"0",
"{",
"// Deep copy the old witness data.",
"newTxIn",
".",
"Witness",
"=",
"make",
"(",
"[",
"]",
"[",
"]",
"byte",
",",
"len",
"(",
"oldTxIn",
".",
"Witness",
")",
")",
"\n",
"for",
"i",
",",
"oldItem",
":=",
"range",
"oldTxIn",
".",
"Witness",
"{",
"newItem",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"oldItem",
")",
")",
"\n",
"copy",
"(",
"newItem",
",",
"oldItem",
")",
"\n",
"newTxIn",
".",
"Witness",
"[",
"i",
"]",
"=",
"newItem",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Finally, append this fully copied txin.",
"newTx",
".",
"TxIn",
"=",
"append",
"(",
"newTx",
".",
"TxIn",
",",
"&",
"newTxIn",
")",
"\n",
"}",
"\n\n",
"// Deep copy the old TxOut data.",
"for",
"_",
",",
"oldTxOut",
":=",
"range",
"msg",
".",
"TxOut",
"{",
"// Deep copy the old PkScript",
"var",
"newScript",
"[",
"]",
"byte",
"\n",
"oldScript",
":=",
"oldTxOut",
".",
"PkScript",
"\n",
"oldScriptLen",
":=",
"len",
"(",
"oldScript",
")",
"\n",
"if",
"oldScriptLen",
">",
"0",
"{",
"newScript",
"=",
"make",
"(",
"[",
"]",
"byte",
",",
"oldScriptLen",
")",
"\n",
"copy",
"(",
"newScript",
",",
"oldScript",
"[",
":",
"oldScriptLen",
"]",
")",
"\n",
"}",
"\n\n",
"// Create new txOut with the deep copied data and append it to",
"// new Tx.",
"newTxOut",
":=",
"TxOut",
"{",
"Value",
":",
"oldTxOut",
".",
"Value",
",",
"PkScript",
":",
"newScript",
",",
"}",
"\n",
"newTx",
".",
"TxOut",
"=",
"append",
"(",
"newTx",
".",
"TxOut",
",",
"&",
"newTxOut",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"newTx",
"\n",
"}"
] | // Copy creates a deep copy of a transaction so that the original does not get
// modified when the copy is manipulated. | [
"Copy",
"creates",
"a",
"deep",
"copy",
"of",
"a",
"transaction",
"so",
"that",
"the",
"original",
"does",
"not",
"get",
"modified",
"when",
"the",
"copy",
"is",
"manipulated",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgtx.go#L334-L405 | train |
btcsuite/btcd | wire/msgtx.go | Deserialize | func (msg *MsgTx) Deserialize(r io.Reader) error {
// 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 BtcDecode.
return msg.BtcDecode(r, 0, WitnessEncoding)
} | go | func (msg *MsgTx) Deserialize(r io.Reader) error {
// 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 BtcDecode.
return msg.BtcDecode(r, 0, WitnessEncoding)
} | [
"func",
"(",
"msg",
"*",
"MsgTx",
")",
"Deserialize",
"(",
"r",
"io",
".",
"Reader",
")",
"error",
"{",
"// 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 BtcDecode.",
"return",
"msg",
".",
"BtcDecode",
"(",
"r",
",",
"0",
",",
"WitnessEncoding",
")",
"\n",
"}"
] | // Deserialize decodes a transaction from r into the receiver using a format
// that is suitable for long-term storage such as a database while respecting
// the Version field in the transaction. This function differs from BtcDecode
// in that BtcDecode decodes from the bitcoin wire protocol as it was sent
// across the network. The wire encoding can technically differ depending on
// the protocol version and doesn't even really need to match the format of a
// stored transaction at all. As of the time this comment was written, the
// encoded transaction is the same in both instances, but there is a distinct
// difference and separating the two allows the API to be flexible enough to
// deal with changes. | [
"Deserialize",
"decodes",
"a",
"transaction",
"from",
"r",
"into",
"the",
"receiver",
"using",
"a",
"format",
"that",
"is",
"suitable",
"for",
"long",
"-",
"term",
"storage",
"such",
"as",
"a",
"database",
"while",
"respecting",
"the",
"Version",
"field",
"in",
"the",
"transaction",
".",
"This",
"function",
"differs",
"from",
"BtcDecode",
"in",
"that",
"BtcDecode",
"decodes",
"from",
"the",
"bitcoin",
"wire",
"protocol",
"as",
"it",
"was",
"sent",
"across",
"the",
"network",
".",
"The",
"wire",
"encoding",
"can",
"technically",
"differ",
"depending",
"on",
"the",
"protocol",
"version",
"and",
"doesn",
"t",
"even",
"really",
"need",
"to",
"match",
"the",
"format",
"of",
"a",
"stored",
"transaction",
"at",
"all",
".",
"As",
"of",
"the",
"time",
"this",
"comment",
"was",
"written",
"the",
"encoded",
"transaction",
"is",
"the",
"same",
"in",
"both",
"instances",
"but",
"there",
"is",
"a",
"distinct",
"difference",
"and",
"separating",
"the",
"two",
"allows",
"the",
"API",
"to",
"be",
"flexible",
"enough",
"to",
"deal",
"with",
"changes",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgtx.go#L662-L667 | train |
btcsuite/btcd | wire/msgtx.go | DeserializeNoWitness | func (msg *MsgTx) DeserializeNoWitness(r io.Reader) error {
return msg.BtcDecode(r, 0, BaseEncoding)
} | go | func (msg *MsgTx) DeserializeNoWitness(r io.Reader) error {
return msg.BtcDecode(r, 0, BaseEncoding)
} | [
"func",
"(",
"msg",
"*",
"MsgTx",
")",
"DeserializeNoWitness",
"(",
"r",
"io",
".",
"Reader",
")",
"error",
"{",
"return",
"msg",
".",
"BtcDecode",
"(",
"r",
",",
"0",
",",
"BaseEncoding",
")",
"\n",
"}"
] | // DeserializeNoWitness decodes a transaction from r into the receiver, where
// the transaction encoding format within r MUST NOT utilize the new
// serialization format created to encode transaction bearing witness data
// within inputs. | [
"DeserializeNoWitness",
"decodes",
"a",
"transaction",
"from",
"r",
"into",
"the",
"receiver",
"where",
"the",
"transaction",
"encoding",
"format",
"within",
"r",
"MUST",
"NOT",
"utilize",
"the",
"new",
"serialization",
"format",
"created",
"to",
"encode",
"transaction",
"bearing",
"witness",
"data",
"within",
"inputs",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgtx.go#L673-L675 | train |
btcsuite/btcd | wire/msgtx.go | BtcEncode | func (msg *MsgTx) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {
err := binarySerializer.PutUint32(w, littleEndian, uint32(msg.Version))
if err != nil {
return err
}
// If the encoding version is set to WitnessEncoding, and the Flags
// field for the MsgTx aren't 0x00, then this indicates the transaction
// is to be encoded using the new witness inclusionary structure
// defined in BIP0144.
doWitness := enc == WitnessEncoding && msg.HasWitness()
if doWitness {
// After the txn's Version field, we include two additional
// bytes specific to the witness encoding. The first byte is an
// always 0x00 marker byte, which allows decoders to
// distinguish a serialized transaction with witnesses from a
// regular (legacy) one. The second byte is the Flag field,
// which at the moment is always 0x01, but may be extended in
// the future to accommodate auxiliary non-committed fields.
if _, err := w.Write(witessMarkerBytes); err != nil {
return err
}
}
count := uint64(len(msg.TxIn))
err = WriteVarInt(w, pver, count)
if err != nil {
return err
}
for _, ti := range msg.TxIn {
err = writeTxIn(w, pver, msg.Version, ti)
if err != nil {
return err
}
}
count = uint64(len(msg.TxOut))
err = WriteVarInt(w, pver, count)
if err != nil {
return err
}
for _, to := range msg.TxOut {
err = WriteTxOut(w, pver, msg.Version, to)
if err != nil {
return err
}
}
// If this transaction is a witness transaction, and the witness
// encoded is desired, then encode the witness for each of the inputs
// within the transaction.
if doWitness {
for _, ti := range msg.TxIn {
err = writeTxWitness(w, pver, msg.Version, ti.Witness)
if err != nil {
return err
}
}
}
return binarySerializer.PutUint32(w, littleEndian, msg.LockTime)
} | go | func (msg *MsgTx) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {
err := binarySerializer.PutUint32(w, littleEndian, uint32(msg.Version))
if err != nil {
return err
}
// If the encoding version is set to WitnessEncoding, and the Flags
// field for the MsgTx aren't 0x00, then this indicates the transaction
// is to be encoded using the new witness inclusionary structure
// defined in BIP0144.
doWitness := enc == WitnessEncoding && msg.HasWitness()
if doWitness {
// After the txn's Version field, we include two additional
// bytes specific to the witness encoding. The first byte is an
// always 0x00 marker byte, which allows decoders to
// distinguish a serialized transaction with witnesses from a
// regular (legacy) one. The second byte is the Flag field,
// which at the moment is always 0x01, but may be extended in
// the future to accommodate auxiliary non-committed fields.
if _, err := w.Write(witessMarkerBytes); err != nil {
return err
}
}
count := uint64(len(msg.TxIn))
err = WriteVarInt(w, pver, count)
if err != nil {
return err
}
for _, ti := range msg.TxIn {
err = writeTxIn(w, pver, msg.Version, ti)
if err != nil {
return err
}
}
count = uint64(len(msg.TxOut))
err = WriteVarInt(w, pver, count)
if err != nil {
return err
}
for _, to := range msg.TxOut {
err = WriteTxOut(w, pver, msg.Version, to)
if err != nil {
return err
}
}
// If this transaction is a witness transaction, and the witness
// encoded is desired, then encode the witness for each of the inputs
// within the transaction.
if doWitness {
for _, ti := range msg.TxIn {
err = writeTxWitness(w, pver, msg.Version, ti.Witness)
if err != nil {
return err
}
}
}
return binarySerializer.PutUint32(w, littleEndian, msg.LockTime)
} | [
"func",
"(",
"msg",
"*",
"MsgTx",
")",
"BtcEncode",
"(",
"w",
"io",
".",
"Writer",
",",
"pver",
"uint32",
",",
"enc",
"MessageEncoding",
")",
"error",
"{",
"err",
":=",
"binarySerializer",
".",
"PutUint32",
"(",
"w",
",",
"littleEndian",
",",
"uint32",
"(",
"msg",
".",
"Version",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// If the encoding version is set to WitnessEncoding, and the Flags",
"// field for the MsgTx aren't 0x00, then this indicates the transaction",
"// is to be encoded using the new witness inclusionary structure",
"// defined in BIP0144.",
"doWitness",
":=",
"enc",
"==",
"WitnessEncoding",
"&&",
"msg",
".",
"HasWitness",
"(",
")",
"\n",
"if",
"doWitness",
"{",
"// After the txn's Version field, we include two additional",
"// bytes specific to the witness encoding. The first byte is an",
"// always 0x00 marker byte, which allows decoders to",
"// distinguish a serialized transaction with witnesses from a",
"// regular (legacy) one. The second byte is the Flag field,",
"// which at the moment is always 0x01, but may be extended in",
"// the future to accommodate auxiliary non-committed fields.",
"if",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"witessMarkerBytes",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"count",
":=",
"uint64",
"(",
"len",
"(",
"msg",
".",
"TxIn",
")",
")",
"\n",
"err",
"=",
"WriteVarInt",
"(",
"w",
",",
"pver",
",",
"count",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"ti",
":=",
"range",
"msg",
".",
"TxIn",
"{",
"err",
"=",
"writeTxIn",
"(",
"w",
",",
"pver",
",",
"msg",
".",
"Version",
",",
"ti",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"count",
"=",
"uint64",
"(",
"len",
"(",
"msg",
".",
"TxOut",
")",
")",
"\n",
"err",
"=",
"WriteVarInt",
"(",
"w",
",",
"pver",
",",
"count",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"to",
":=",
"range",
"msg",
".",
"TxOut",
"{",
"err",
"=",
"WriteTxOut",
"(",
"w",
",",
"pver",
",",
"msg",
".",
"Version",
",",
"to",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// If this transaction is a witness transaction, and the witness",
"// encoded is desired, then encode the witness for each of the inputs",
"// within the transaction.",
"if",
"doWitness",
"{",
"for",
"_",
",",
"ti",
":=",
"range",
"msg",
".",
"TxIn",
"{",
"err",
"=",
"writeTxWitness",
"(",
"w",
",",
"pver",
",",
"msg",
".",
"Version",
",",
"ti",
".",
"Witness",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"binarySerializer",
".",
"PutUint32",
"(",
"w",
",",
"littleEndian",
",",
"msg",
".",
"LockTime",
")",
"\n",
"}"
] | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
// This is part of the Message interface implementation.
// See Serialize for encoding transactions to be stored to disk, such as in a
// database, as opposed to encoding transactions 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",
"transactions",
"to",
"be",
"stored",
"to",
"disk",
"such",
"as",
"in",
"a",
"database",
"as",
"opposed",
"to",
"encoding",
"transactions",
"for",
"the",
"wire",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgtx.go#L681-L744 | train |
btcsuite/btcd | wire/msgtx.go | HasWitness | func (msg *MsgTx) HasWitness() bool {
for _, txIn := range msg.TxIn {
if len(txIn.Witness) != 0 {
return true
}
}
return false
} | go | func (msg *MsgTx) HasWitness() bool {
for _, txIn := range msg.TxIn {
if len(txIn.Witness) != 0 {
return true
}
}
return false
} | [
"func",
"(",
"msg",
"*",
"MsgTx",
")",
"HasWitness",
"(",
")",
"bool",
"{",
"for",
"_",
",",
"txIn",
":=",
"range",
"msg",
".",
"TxIn",
"{",
"if",
"len",
"(",
"txIn",
".",
"Witness",
")",
"!=",
"0",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"false",
"\n",
"}"
] | // HasWitness returns false if none of the inputs within the transaction
// contain witness data, true false otherwise. | [
"HasWitness",
"returns",
"false",
"if",
"none",
"of",
"the",
"inputs",
"within",
"the",
"transaction",
"contain",
"witness",
"data",
"true",
"false",
"otherwise",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgtx.go#L748-L756 | train |
btcsuite/btcd | wire/msgtx.go | Serialize | func (msg *MsgTx) Serialize(w io.Writer) error {
// 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 BtcEncode.
//
// Passing a encoding type of WitnessEncoding to BtcEncode for MsgTx
// indicates that the transaction's witnesses (if any) should be
// serialized according to the new serialization structure defined in
// BIP0144.
return msg.BtcEncode(w, 0, WitnessEncoding)
} | go | func (msg *MsgTx) Serialize(w io.Writer) error {
// 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 BtcEncode.
//
// Passing a encoding type of WitnessEncoding to BtcEncode for MsgTx
// indicates that the transaction's witnesses (if any) should be
// serialized according to the new serialization structure defined in
// BIP0144.
return msg.BtcEncode(w, 0, WitnessEncoding)
} | [
"func",
"(",
"msg",
"*",
"MsgTx",
")",
"Serialize",
"(",
"w",
"io",
".",
"Writer",
")",
"error",
"{",
"// 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 BtcEncode.",
"//",
"// Passing a encoding type of WitnessEncoding to BtcEncode for MsgTx",
"// indicates that the transaction's witnesses (if any) should be",
"// serialized according to the new serialization structure defined in",
"// BIP0144.",
"return",
"msg",
".",
"BtcEncode",
"(",
"w",
",",
"0",
",",
"WitnessEncoding",
")",
"\n",
"}"
] | // Serialize encodes the transaction to w using a format that suitable for
// long-term storage such as a database while respecting the Version field in
// the transaction. This function differs from BtcEncode in that BtcEncode
// encodes the transaction to the bitcoin wire protocol in order to be sent
// across the network. The wire encoding can technically differ depending on
// the protocol version and doesn't even really need to match the format of a
// stored transaction at all. As of the time this comment was written, the
// encoded transaction is the same in both instances, but there is a distinct
// difference and separating the two allows the API to be flexible enough to
// deal with changes. | [
"Serialize",
"encodes",
"the",
"transaction",
"to",
"w",
"using",
"a",
"format",
"that",
"suitable",
"for",
"long",
"-",
"term",
"storage",
"such",
"as",
"a",
"database",
"while",
"respecting",
"the",
"Version",
"field",
"in",
"the",
"transaction",
".",
"This",
"function",
"differs",
"from",
"BtcEncode",
"in",
"that",
"BtcEncode",
"encodes",
"the",
"transaction",
"to",
"the",
"bitcoin",
"wire",
"protocol",
"in",
"order",
"to",
"be",
"sent",
"across",
"the",
"network",
".",
"The",
"wire",
"encoding",
"can",
"technically",
"differ",
"depending",
"on",
"the",
"protocol",
"version",
"and",
"doesn",
"t",
"even",
"really",
"need",
"to",
"match",
"the",
"format",
"of",
"a",
"stored",
"transaction",
"at",
"all",
".",
"As",
"of",
"the",
"time",
"this",
"comment",
"was",
"written",
"the",
"encoded",
"transaction",
"is",
"the",
"same",
"in",
"both",
"instances",
"but",
"there",
"is",
"a",
"distinct",
"difference",
"and",
"separating",
"the",
"two",
"allows",
"the",
"API",
"to",
"be",
"flexible",
"enough",
"to",
"deal",
"with",
"changes",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgtx.go#L768-L778 | train |
btcsuite/btcd | wire/msgtx.go | baseSize | func (msg *MsgTx) baseSize() int {
// Version 4 bytes + LockTime 4 bytes + Serialized varint size for the
// number of transaction inputs and outputs.
n := 8 + VarIntSerializeSize(uint64(len(msg.TxIn))) +
VarIntSerializeSize(uint64(len(msg.TxOut)))
for _, txIn := range msg.TxIn {
n += txIn.SerializeSize()
}
for _, txOut := range msg.TxOut {
n += txOut.SerializeSize()
}
return n
} | go | func (msg *MsgTx) baseSize() int {
// Version 4 bytes + LockTime 4 bytes + Serialized varint size for the
// number of transaction inputs and outputs.
n := 8 + VarIntSerializeSize(uint64(len(msg.TxIn))) +
VarIntSerializeSize(uint64(len(msg.TxOut)))
for _, txIn := range msg.TxIn {
n += txIn.SerializeSize()
}
for _, txOut := range msg.TxOut {
n += txOut.SerializeSize()
}
return n
} | [
"func",
"(",
"msg",
"*",
"MsgTx",
")",
"baseSize",
"(",
")",
"int",
"{",
"// Version 4 bytes + LockTime 4 bytes + Serialized varint size for the",
"// number of transaction inputs and outputs.",
"n",
":=",
"8",
"+",
"VarIntSerializeSize",
"(",
"uint64",
"(",
"len",
"(",
"msg",
".",
"TxIn",
")",
")",
")",
"+",
"VarIntSerializeSize",
"(",
"uint64",
"(",
"len",
"(",
"msg",
".",
"TxOut",
")",
")",
")",
"\n\n",
"for",
"_",
",",
"txIn",
":=",
"range",
"msg",
".",
"TxIn",
"{",
"n",
"+=",
"txIn",
".",
"SerializeSize",
"(",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"txOut",
":=",
"range",
"msg",
".",
"TxOut",
"{",
"n",
"+=",
"txOut",
".",
"SerializeSize",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"n",
"\n",
"}"
] | // baseSize returns the serialized size of the transaction without accounting
// for any witness data. | [
"baseSize",
"returns",
"the",
"serialized",
"size",
"of",
"the",
"transaction",
"without",
"accounting",
"for",
"any",
"witness",
"data",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgtx.go#L789-L804 | train |
btcsuite/btcd | wire/msgtx.go | SerializeSize | func (msg *MsgTx) SerializeSize() int {
n := msg.baseSize()
if msg.HasWitness() {
// The marker, and flag fields take up two additional bytes.
n += 2
// Additionally, factor in the serialized size of each of the
// witnesses for each txin.
for _, txin := range msg.TxIn {
n += txin.Witness.SerializeSize()
}
}
return n
} | go | func (msg *MsgTx) SerializeSize() int {
n := msg.baseSize()
if msg.HasWitness() {
// The marker, and flag fields take up two additional bytes.
n += 2
// Additionally, factor in the serialized size of each of the
// witnesses for each txin.
for _, txin := range msg.TxIn {
n += txin.Witness.SerializeSize()
}
}
return n
} | [
"func",
"(",
"msg",
"*",
"MsgTx",
")",
"SerializeSize",
"(",
")",
"int",
"{",
"n",
":=",
"msg",
".",
"baseSize",
"(",
")",
"\n\n",
"if",
"msg",
".",
"HasWitness",
"(",
")",
"{",
"// The marker, and flag fields take up two additional bytes.",
"n",
"+=",
"2",
"\n\n",
"// Additionally, factor in the serialized size of each of the",
"// witnesses for each txin.",
"for",
"_",
",",
"txin",
":=",
"range",
"msg",
".",
"TxIn",
"{",
"n",
"+=",
"txin",
".",
"Witness",
".",
"SerializeSize",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"n",
"\n",
"}"
] | // SerializeSize returns the number of bytes it would take to serialize the
// the transaction. | [
"SerializeSize",
"returns",
"the",
"number",
"of",
"bytes",
"it",
"would",
"take",
"to",
"serialize",
"the",
"the",
"transaction",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgtx.go#L808-L823 | train |
btcsuite/btcd | wire/msgtx.go | PkScriptLocs | func (msg *MsgTx) PkScriptLocs() []int {
numTxOut := len(msg.TxOut)
if numTxOut == 0 {
return nil
}
// The starting offset in the serialized transaction of the first
// transaction output is:
//
// Version 4 bytes + serialized varint size for the number of
// transaction inputs and outputs + serialized size of each transaction
// input.
n := 4 + VarIntSerializeSize(uint64(len(msg.TxIn))) +
VarIntSerializeSize(uint64(numTxOut))
// If this transaction has a witness input, the an additional two bytes
// for the marker, and flag byte need to be taken into account.
if len(msg.TxIn) > 0 && msg.TxIn[0].Witness != nil {
n += 2
}
for _, txIn := range msg.TxIn {
n += txIn.SerializeSize()
}
// Calculate and set the appropriate offset for each public key script.
pkScriptLocs := make([]int, numTxOut)
for i, txOut := range msg.TxOut {
// The offset of the script in the transaction output is:
//
// Value 8 bytes + serialized varint size for the length of
// PkScript.
n += 8 + VarIntSerializeSize(uint64(len(txOut.PkScript)))
pkScriptLocs[i] = n
n += len(txOut.PkScript)
}
return pkScriptLocs
} | go | func (msg *MsgTx) PkScriptLocs() []int {
numTxOut := len(msg.TxOut)
if numTxOut == 0 {
return nil
}
// The starting offset in the serialized transaction of the first
// transaction output is:
//
// Version 4 bytes + serialized varint size for the number of
// transaction inputs and outputs + serialized size of each transaction
// input.
n := 4 + VarIntSerializeSize(uint64(len(msg.TxIn))) +
VarIntSerializeSize(uint64(numTxOut))
// If this transaction has a witness input, the an additional two bytes
// for the marker, and flag byte need to be taken into account.
if len(msg.TxIn) > 0 && msg.TxIn[0].Witness != nil {
n += 2
}
for _, txIn := range msg.TxIn {
n += txIn.SerializeSize()
}
// Calculate and set the appropriate offset for each public key script.
pkScriptLocs := make([]int, numTxOut)
for i, txOut := range msg.TxOut {
// The offset of the script in the transaction output is:
//
// Value 8 bytes + serialized varint size for the length of
// PkScript.
n += 8 + VarIntSerializeSize(uint64(len(txOut.PkScript)))
pkScriptLocs[i] = n
n += len(txOut.PkScript)
}
return pkScriptLocs
} | [
"func",
"(",
"msg",
"*",
"MsgTx",
")",
"PkScriptLocs",
"(",
")",
"[",
"]",
"int",
"{",
"numTxOut",
":=",
"len",
"(",
"msg",
".",
"TxOut",
")",
"\n",
"if",
"numTxOut",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// The starting offset in the serialized transaction of the first",
"// transaction output is:",
"//",
"// Version 4 bytes + serialized varint size for the number of",
"// transaction inputs and outputs + serialized size of each transaction",
"// input.",
"n",
":=",
"4",
"+",
"VarIntSerializeSize",
"(",
"uint64",
"(",
"len",
"(",
"msg",
".",
"TxIn",
")",
")",
")",
"+",
"VarIntSerializeSize",
"(",
"uint64",
"(",
"numTxOut",
")",
")",
"\n\n",
"// If this transaction has a witness input, the an additional two bytes",
"// for the marker, and flag byte need to be taken into account.",
"if",
"len",
"(",
"msg",
".",
"TxIn",
")",
">",
"0",
"&&",
"msg",
".",
"TxIn",
"[",
"0",
"]",
".",
"Witness",
"!=",
"nil",
"{",
"n",
"+=",
"2",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"txIn",
":=",
"range",
"msg",
".",
"TxIn",
"{",
"n",
"+=",
"txIn",
".",
"SerializeSize",
"(",
")",
"\n",
"}",
"\n\n",
"// Calculate and set the appropriate offset for each public key script.",
"pkScriptLocs",
":=",
"make",
"(",
"[",
"]",
"int",
",",
"numTxOut",
")",
"\n",
"for",
"i",
",",
"txOut",
":=",
"range",
"msg",
".",
"TxOut",
"{",
"// The offset of the script in the transaction output is:",
"//",
"// Value 8 bytes + serialized varint size for the length of",
"// PkScript.",
"n",
"+=",
"8",
"+",
"VarIntSerializeSize",
"(",
"uint64",
"(",
"len",
"(",
"txOut",
".",
"PkScript",
")",
")",
")",
"\n",
"pkScriptLocs",
"[",
"i",
"]",
"=",
"n",
"\n",
"n",
"+=",
"len",
"(",
"txOut",
".",
"PkScript",
")",
"\n",
"}",
"\n\n",
"return",
"pkScriptLocs",
"\n",
"}"
] | // PkScriptLocs returns a slice containing the start of each public key script
// within the raw serialized transaction. The caller can easily obtain the
// length of each script by using len on the script available via the
// appropriate transaction output entry. | [
"PkScriptLocs",
"returns",
"a",
"slice",
"containing",
"the",
"start",
"of",
"each",
"public",
"key",
"script",
"within",
"the",
"raw",
"serialized",
"transaction",
".",
"The",
"caller",
"can",
"easily",
"obtain",
"the",
"length",
"of",
"each",
"script",
"by",
"using",
"len",
"on",
"the",
"script",
"available",
"via",
"the",
"appropriate",
"transaction",
"output",
"entry",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgtx.go#L847-L885 | train |
btcsuite/btcd | wire/msgtx.go | NewMsgTx | func NewMsgTx(version int32) *MsgTx {
return &MsgTx{
Version: version,
TxIn: make([]*TxIn, 0, defaultTxInOutAlloc),
TxOut: make([]*TxOut, 0, defaultTxInOutAlloc),
}
} | go | func NewMsgTx(version int32) *MsgTx {
return &MsgTx{
Version: version,
TxIn: make([]*TxIn, 0, defaultTxInOutAlloc),
TxOut: make([]*TxOut, 0, defaultTxInOutAlloc),
}
} | [
"func",
"NewMsgTx",
"(",
"version",
"int32",
")",
"*",
"MsgTx",
"{",
"return",
"&",
"MsgTx",
"{",
"Version",
":",
"version",
",",
"TxIn",
":",
"make",
"(",
"[",
"]",
"*",
"TxIn",
",",
"0",
",",
"defaultTxInOutAlloc",
")",
",",
"TxOut",
":",
"make",
"(",
"[",
"]",
"*",
"TxOut",
",",
"0",
",",
"defaultTxInOutAlloc",
")",
",",
"}",
"\n",
"}"
] | // NewMsgTx returns a new bitcoin tx message that conforms to the Message
// interface. The return instance has a default version of TxVersion and there
// are no transaction inputs or outputs. Also, the lock time is set to zero
// to indicate the transaction is valid immediately as opposed to some time in
// future. | [
"NewMsgTx",
"returns",
"a",
"new",
"bitcoin",
"tx",
"message",
"that",
"conforms",
"to",
"the",
"Message",
"interface",
".",
"The",
"return",
"instance",
"has",
"a",
"default",
"version",
"of",
"TxVersion",
"and",
"there",
"are",
"no",
"transaction",
"inputs",
"or",
"outputs",
".",
"Also",
"the",
"lock",
"time",
"is",
"set",
"to",
"zero",
"to",
"indicate",
"the",
"transaction",
"is",
"valid",
"immediately",
"as",
"opposed",
"to",
"some",
"time",
"in",
"future",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgtx.go#L892-L898 | train |
btcsuite/btcd | wire/msgtx.go | readOutPoint | func readOutPoint(r io.Reader, pver uint32, version int32, op *OutPoint) error {
_, err := io.ReadFull(r, op.Hash[:])
if err != nil {
return err
}
op.Index, err = binarySerializer.Uint32(r, littleEndian)
return err
} | go | func readOutPoint(r io.Reader, pver uint32, version int32, op *OutPoint) error {
_, err := io.ReadFull(r, op.Hash[:])
if err != nil {
return err
}
op.Index, err = binarySerializer.Uint32(r, littleEndian)
return err
} | [
"func",
"readOutPoint",
"(",
"r",
"io",
".",
"Reader",
",",
"pver",
"uint32",
",",
"version",
"int32",
",",
"op",
"*",
"OutPoint",
")",
"error",
"{",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"op",
".",
"Hash",
"[",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"op",
".",
"Index",
",",
"err",
"=",
"binarySerializer",
".",
"Uint32",
"(",
"r",
",",
"littleEndian",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // readOutPoint reads the next sequence of bytes from r as an OutPoint. | [
"readOutPoint",
"reads",
"the",
"next",
"sequence",
"of",
"bytes",
"from",
"r",
"as",
"an",
"OutPoint",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgtx.go#L901-L909 | train |
btcsuite/btcd | wire/msgtx.go | writeOutPoint | func writeOutPoint(w io.Writer, pver uint32, version int32, op *OutPoint) error {
_, err := w.Write(op.Hash[:])
if err != nil {
return err
}
return binarySerializer.PutUint32(w, littleEndian, op.Index)
} | go | func writeOutPoint(w io.Writer, pver uint32, version int32, op *OutPoint) error {
_, err := w.Write(op.Hash[:])
if err != nil {
return err
}
return binarySerializer.PutUint32(w, littleEndian, op.Index)
} | [
"func",
"writeOutPoint",
"(",
"w",
"io",
".",
"Writer",
",",
"pver",
"uint32",
",",
"version",
"int32",
",",
"op",
"*",
"OutPoint",
")",
"error",
"{",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"op",
".",
"Hash",
"[",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"binarySerializer",
".",
"PutUint32",
"(",
"w",
",",
"littleEndian",
",",
"op",
".",
"Index",
")",
"\n",
"}"
] | // writeOutPoint encodes op to the bitcoin protocol encoding for an OutPoint
// to w. | [
"writeOutPoint",
"encodes",
"op",
"to",
"the",
"bitcoin",
"protocol",
"encoding",
"for",
"an",
"OutPoint",
"to",
"w",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgtx.go#L913-L920 | train |
btcsuite/btcd | wire/msgtx.go | readScript | func readScript(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("readScript", str)
}
b := scriptPool.Borrow(count)
_, err = io.ReadFull(r, b)
if err != nil {
scriptPool.Return(b)
return nil, err
}
return b, nil
} | go | func readScript(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("readScript", str)
}
b := scriptPool.Borrow(count)
_, err = io.ReadFull(r, b)
if err != nil {
scriptPool.Return(b)
return nil, err
}
return b, nil
} | [
"func",
"readScript",
"(",
"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",
":=",
"scriptPool",
".",
"Borrow",
"(",
"count",
")",
"\n",
"_",
",",
"err",
"=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"b",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"scriptPool",
".",
"Return",
"(",
"b",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"b",
",",
"nil",
"\n",
"}"
] | // readScript reads a variable length byte array that represents a transaction
// script. It 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. | [
"readScript",
"reads",
"a",
"variable",
"length",
"byte",
"array",
"that",
"represents",
"a",
"transaction",
"script",
".",
"It",
"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/msgtx.go#L929-L951 | train |
btcsuite/btcd | wire/msgtx.go | writeTxWitness | func writeTxWitness(w io.Writer, pver uint32, version int32, wit [][]byte) error {
err := WriteVarInt(w, pver, uint64(len(wit)))
if err != nil {
return err
}
for _, item := range wit {
err = WriteVarBytes(w, pver, item)
if err != nil {
return err
}
}
return nil
} | go | func writeTxWitness(w io.Writer, pver uint32, version int32, wit [][]byte) error {
err := WriteVarInt(w, pver, uint64(len(wit)))
if err != nil {
return err
}
for _, item := range wit {
err = WriteVarBytes(w, pver, item)
if err != nil {
return err
}
}
return nil
} | [
"func",
"writeTxWitness",
"(",
"w",
"io",
".",
"Writer",
",",
"pver",
"uint32",
",",
"version",
"int32",
",",
"wit",
"[",
"]",
"[",
"]",
"byte",
")",
"error",
"{",
"err",
":=",
"WriteVarInt",
"(",
"w",
",",
"pver",
",",
"uint64",
"(",
"len",
"(",
"wit",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"item",
":=",
"range",
"wit",
"{",
"err",
"=",
"WriteVarBytes",
"(",
"w",
",",
"pver",
",",
"item",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // writeTxWitness encodes the bitcoin protocol encoding for a transaction
// input's witness into to w. | [
"writeTxWitness",
"encodes",
"the",
"bitcoin",
"protocol",
"encoding",
"for",
"a",
"transaction",
"input",
"s",
"witness",
"into",
"to",
"w",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgtx.go#L1015-L1027 | train |
btcsuite/btcd | database/ffldb/db.go | Swap | func (s bulkFetchDataSorter) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
} | go | func (s bulkFetchDataSorter) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
} | [
"func",
"(",
"s",
"bulkFetchDataSorter",
")",
"Swap",
"(",
"i",
",",
"j",
"int",
")",
"{",
"s",
"[",
"i",
"]",
",",
"s",
"[",
"j",
"]",
"=",
"s",
"[",
"j",
"]",
",",
"s",
"[",
"i",
"]",
"\n",
"}"
] | // Swap swaps the items at the passed indices. It is part of the
// sort.Interface implementation. | [
"Swap",
"swaps",
"the",
"items",
"at",
"the",
"passed",
"indices",
".",
"It",
"is",
"part",
"of",
"the",
"sort",
".",
"Interface",
"implementation",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L112-L114 | train |
btcsuite/btcd | database/ffldb/db.go | Less | func (s bulkFetchDataSorter) Less(i, j int) bool {
if s[i].blockFileNum < s[j].blockFileNum {
return true
}
if s[i].blockFileNum > s[j].blockFileNum {
return false
}
return s[i].fileOffset < s[j].fileOffset
} | go | func (s bulkFetchDataSorter) Less(i, j int) bool {
if s[i].blockFileNum < s[j].blockFileNum {
return true
}
if s[i].blockFileNum > s[j].blockFileNum {
return false
}
return s[i].fileOffset < s[j].fileOffset
} | [
"func",
"(",
"s",
"bulkFetchDataSorter",
")",
"Less",
"(",
"i",
",",
"j",
"int",
")",
"bool",
"{",
"if",
"s",
"[",
"i",
"]",
".",
"blockFileNum",
"<",
"s",
"[",
"j",
"]",
".",
"blockFileNum",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"s",
"[",
"i",
"]",
".",
"blockFileNum",
">",
"s",
"[",
"j",
"]",
".",
"blockFileNum",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"return",
"s",
"[",
"i",
"]",
".",
"fileOffset",
"<",
"s",
"[",
"j",
"]",
".",
"fileOffset",
"\n",
"}"
] | // Less returns whether the item with index i should sort before the item with
// index j. It is part of the sort.Interface implementation. | [
"Less",
"returns",
"whether",
"the",
"item",
"with",
"index",
"i",
"should",
"sort",
"before",
"the",
"item",
"with",
"index",
"j",
".",
"It",
"is",
"part",
"of",
"the",
"sort",
".",
"Interface",
"implementation",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L118-L127 | train |
btcsuite/btcd | database/ffldb/db.go | makeDbErr | func makeDbErr(c database.ErrorCode, desc string, err error) database.Error {
return database.Error{ErrorCode: c, Description: desc, Err: err}
} | go | func makeDbErr(c database.ErrorCode, desc string, err error) database.Error {
return database.Error{ErrorCode: c, Description: desc, Err: err}
} | [
"func",
"makeDbErr",
"(",
"c",
"database",
".",
"ErrorCode",
",",
"desc",
"string",
",",
"err",
"error",
")",
"database",
".",
"Error",
"{",
"return",
"database",
".",
"Error",
"{",
"ErrorCode",
":",
"c",
",",
"Description",
":",
"desc",
",",
"Err",
":",
"err",
"}",
"\n",
"}"
] | // makeDbErr creates a database.Error given a set of arguments. | [
"makeDbErr",
"creates",
"a",
"database",
".",
"Error",
"given",
"a",
"set",
"of",
"arguments",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L130-L132 | train |
btcsuite/btcd | database/ffldb/db.go | convertErr | func convertErr(desc string, ldbErr error) database.Error {
// Use the driver-specific error code by default. The code below will
// update this with the converted error if it's recognized.
var code = database.ErrDriverSpecific
switch {
// Database corruption errors.
case ldberrors.IsCorrupted(ldbErr):
code = database.ErrCorruption
// Database open/create errors.
case ldbErr == leveldb.ErrClosed:
code = database.ErrDbNotOpen
// Transaction errors.
case ldbErr == leveldb.ErrSnapshotReleased:
code = database.ErrTxClosed
case ldbErr == leveldb.ErrIterReleased:
code = database.ErrTxClosed
}
return database.Error{ErrorCode: code, Description: desc, Err: ldbErr}
} | go | func convertErr(desc string, ldbErr error) database.Error {
// Use the driver-specific error code by default. The code below will
// update this with the converted error if it's recognized.
var code = database.ErrDriverSpecific
switch {
// Database corruption errors.
case ldberrors.IsCorrupted(ldbErr):
code = database.ErrCorruption
// Database open/create errors.
case ldbErr == leveldb.ErrClosed:
code = database.ErrDbNotOpen
// Transaction errors.
case ldbErr == leveldb.ErrSnapshotReleased:
code = database.ErrTxClosed
case ldbErr == leveldb.ErrIterReleased:
code = database.ErrTxClosed
}
return database.Error{ErrorCode: code, Description: desc, Err: ldbErr}
} | [
"func",
"convertErr",
"(",
"desc",
"string",
",",
"ldbErr",
"error",
")",
"database",
".",
"Error",
"{",
"// Use the driver-specific error code by default. The code below will",
"// update this with the converted error if it's recognized.",
"var",
"code",
"=",
"database",
".",
"ErrDriverSpecific",
"\n\n",
"switch",
"{",
"// Database corruption errors.",
"case",
"ldberrors",
".",
"IsCorrupted",
"(",
"ldbErr",
")",
":",
"code",
"=",
"database",
".",
"ErrCorruption",
"\n\n",
"// Database open/create errors.",
"case",
"ldbErr",
"==",
"leveldb",
".",
"ErrClosed",
":",
"code",
"=",
"database",
".",
"ErrDbNotOpen",
"\n\n",
"// Transaction errors.",
"case",
"ldbErr",
"==",
"leveldb",
".",
"ErrSnapshotReleased",
":",
"code",
"=",
"database",
".",
"ErrTxClosed",
"\n",
"case",
"ldbErr",
"==",
"leveldb",
".",
"ErrIterReleased",
":",
"code",
"=",
"database",
".",
"ErrTxClosed",
"\n",
"}",
"\n\n",
"return",
"database",
".",
"Error",
"{",
"ErrorCode",
":",
"code",
",",
"Description",
":",
"desc",
",",
"Err",
":",
"ldbErr",
"}",
"\n",
"}"
] | // convertErr converts the passed leveldb error into a database error with an
// equivalent error code and the passed description. It also sets the passed
// error as the underlying error. | [
"convertErr",
"converts",
"the",
"passed",
"leveldb",
"error",
"into",
"a",
"database",
"error",
"with",
"an",
"equivalent",
"error",
"code",
"and",
"the",
"passed",
"description",
".",
"It",
"also",
"sets",
"the",
"passed",
"error",
"as",
"the",
"underlying",
"error",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L137-L159 | train |
btcsuite/btcd | database/ffldb/db.go | copySlice | func copySlice(slice []byte) []byte {
ret := make([]byte, len(slice))
copy(ret, slice)
return ret
} | go | func copySlice(slice []byte) []byte {
ret := make([]byte, len(slice))
copy(ret, slice)
return ret
} | [
"func",
"copySlice",
"(",
"slice",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"ret",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"slice",
")",
")",
"\n",
"copy",
"(",
"ret",
",",
"slice",
")",
"\n",
"return",
"ret",
"\n",
"}"
] | // copySlice returns a copy of the passed slice. This is mostly used to copy
// leveldb iterator keys and values since they are only valid until the iterator
// is moved instead of during the entirety of the transaction. | [
"copySlice",
"returns",
"a",
"copy",
"of",
"the",
"passed",
"slice",
".",
"This",
"is",
"mostly",
"used",
"to",
"copy",
"leveldb",
"iterator",
"keys",
"and",
"values",
"since",
"they",
"are",
"only",
"valid",
"until",
"the",
"iterator",
"is",
"moved",
"instead",
"of",
"during",
"the",
"entirety",
"of",
"the",
"transaction",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L164-L168 | train |
btcsuite/btcd | database/ffldb/db.go | Bucket | func (c *cursor) Bucket() database.Bucket {
// Ensure transaction state is valid.
if err := c.bucket.tx.checkClosed(); err != nil {
return nil
}
return c.bucket
} | go | func (c *cursor) Bucket() database.Bucket {
// Ensure transaction state is valid.
if err := c.bucket.tx.checkClosed(); err != nil {
return nil
}
return c.bucket
} | [
"func",
"(",
"c",
"*",
"cursor",
")",
"Bucket",
"(",
")",
"database",
".",
"Bucket",
"{",
"// Ensure transaction state is valid.",
"if",
"err",
":=",
"c",
".",
"bucket",
".",
"tx",
".",
"checkClosed",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"c",
".",
"bucket",
"\n",
"}"
] | // Bucket returns the bucket the cursor was created for.
//
// This function is part of the database.Cursor interface implementation. | [
"Bucket",
"returns",
"the",
"bucket",
"the",
"cursor",
"was",
"created",
"for",
".",
"This",
"function",
"is",
"part",
"of",
"the",
"database",
".",
"Cursor",
"interface",
"implementation",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L185-L192 | train |
btcsuite/btcd | database/ffldb/db.go | skipPendingUpdates | func (c *cursor) skipPendingUpdates(forwards bool) {
for c.dbIter.Valid() {
var skip bool
key := c.dbIter.Key()
if c.bucket.tx.pendingRemove.Has(key) {
skip = true
} else if c.bucket.tx.pendingKeys.Has(key) {
skip = true
}
if !skip {
break
}
if forwards {
c.dbIter.Next()
} else {
c.dbIter.Prev()
}
}
} | go | func (c *cursor) skipPendingUpdates(forwards bool) {
for c.dbIter.Valid() {
var skip bool
key := c.dbIter.Key()
if c.bucket.tx.pendingRemove.Has(key) {
skip = true
} else if c.bucket.tx.pendingKeys.Has(key) {
skip = true
}
if !skip {
break
}
if forwards {
c.dbIter.Next()
} else {
c.dbIter.Prev()
}
}
} | [
"func",
"(",
"c",
"*",
"cursor",
")",
"skipPendingUpdates",
"(",
"forwards",
"bool",
")",
"{",
"for",
"c",
".",
"dbIter",
".",
"Valid",
"(",
")",
"{",
"var",
"skip",
"bool",
"\n",
"key",
":=",
"c",
".",
"dbIter",
".",
"Key",
"(",
")",
"\n",
"if",
"c",
".",
"bucket",
".",
"tx",
".",
"pendingRemove",
".",
"Has",
"(",
"key",
")",
"{",
"skip",
"=",
"true",
"\n",
"}",
"else",
"if",
"c",
".",
"bucket",
".",
"tx",
".",
"pendingKeys",
".",
"Has",
"(",
"key",
")",
"{",
"skip",
"=",
"true",
"\n",
"}",
"\n",
"if",
"!",
"skip",
"{",
"break",
"\n",
"}",
"\n\n",
"if",
"forwards",
"{",
"c",
".",
"dbIter",
".",
"Next",
"(",
")",
"\n",
"}",
"else",
"{",
"c",
".",
"dbIter",
".",
"Prev",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // skipPendingUpdates skips any keys at the current database iterator position
// that are being updated by the transaction. The forwards flag indicates the
// direction the cursor is moving. | [
"skipPendingUpdates",
"skips",
"any",
"keys",
"at",
"the",
"current",
"database",
"iterator",
"position",
"that",
"are",
"being",
"updated",
"by",
"the",
"transaction",
".",
"The",
"forwards",
"flag",
"indicates",
"the",
"direction",
"the",
"cursor",
"is",
"moving",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L230-L249 | train |
btcsuite/btcd | database/ffldb/db.go | chooseIterator | func (c *cursor) chooseIterator(forwards bool) bool {
// Skip any keys at the current database iterator position that are
// being updated by the transaction.
c.skipPendingUpdates(forwards)
// When both iterators are exhausted, the cursor is exhausted too.
if !c.dbIter.Valid() && !c.pendingIter.Valid() {
c.currentIter = nil
return false
}
// Choose the database iterator when the pending keys iterator is
// exhausted.
if !c.pendingIter.Valid() {
c.currentIter = c.dbIter
return true
}
// Choose the pending keys iterator when the database iterator is
// exhausted.
if !c.dbIter.Valid() {
c.currentIter = c.pendingIter
return true
}
// Both iterators are valid, so choose the iterator with either the
// smaller or larger key depending on the forwards flag.
compare := bytes.Compare(c.dbIter.Key(), c.pendingIter.Key())
if (forwards && compare > 0) || (!forwards && compare < 0) {
c.currentIter = c.pendingIter
} else {
c.currentIter = c.dbIter
}
return true
} | go | func (c *cursor) chooseIterator(forwards bool) bool {
// Skip any keys at the current database iterator position that are
// being updated by the transaction.
c.skipPendingUpdates(forwards)
// When both iterators are exhausted, the cursor is exhausted too.
if !c.dbIter.Valid() && !c.pendingIter.Valid() {
c.currentIter = nil
return false
}
// Choose the database iterator when the pending keys iterator is
// exhausted.
if !c.pendingIter.Valid() {
c.currentIter = c.dbIter
return true
}
// Choose the pending keys iterator when the database iterator is
// exhausted.
if !c.dbIter.Valid() {
c.currentIter = c.pendingIter
return true
}
// Both iterators are valid, so choose the iterator with either the
// smaller or larger key depending on the forwards flag.
compare := bytes.Compare(c.dbIter.Key(), c.pendingIter.Key())
if (forwards && compare > 0) || (!forwards && compare < 0) {
c.currentIter = c.pendingIter
} else {
c.currentIter = c.dbIter
}
return true
} | [
"func",
"(",
"c",
"*",
"cursor",
")",
"chooseIterator",
"(",
"forwards",
"bool",
")",
"bool",
"{",
"// Skip any keys at the current database iterator position that are",
"// being updated by the transaction.",
"c",
".",
"skipPendingUpdates",
"(",
"forwards",
")",
"\n\n",
"// When both iterators are exhausted, the cursor is exhausted too.",
"if",
"!",
"c",
".",
"dbIter",
".",
"Valid",
"(",
")",
"&&",
"!",
"c",
".",
"pendingIter",
".",
"Valid",
"(",
")",
"{",
"c",
".",
"currentIter",
"=",
"nil",
"\n",
"return",
"false",
"\n",
"}",
"\n\n",
"// Choose the database iterator when the pending keys iterator is",
"// exhausted.",
"if",
"!",
"c",
".",
"pendingIter",
".",
"Valid",
"(",
")",
"{",
"c",
".",
"currentIter",
"=",
"c",
".",
"dbIter",
"\n",
"return",
"true",
"\n",
"}",
"\n\n",
"// Choose the pending keys iterator when the database iterator is",
"// exhausted.",
"if",
"!",
"c",
".",
"dbIter",
".",
"Valid",
"(",
")",
"{",
"c",
".",
"currentIter",
"=",
"c",
".",
"pendingIter",
"\n",
"return",
"true",
"\n",
"}",
"\n\n",
"// Both iterators are valid, so choose the iterator with either the",
"// smaller or larger key depending on the forwards flag.",
"compare",
":=",
"bytes",
".",
"Compare",
"(",
"c",
".",
"dbIter",
".",
"Key",
"(",
")",
",",
"c",
".",
"pendingIter",
".",
"Key",
"(",
")",
")",
"\n",
"if",
"(",
"forwards",
"&&",
"compare",
">",
"0",
")",
"||",
"(",
"!",
"forwards",
"&&",
"compare",
"<",
"0",
")",
"{",
"c",
".",
"currentIter",
"=",
"c",
".",
"pendingIter",
"\n",
"}",
"else",
"{",
"c",
".",
"currentIter",
"=",
"c",
".",
"dbIter",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // chooseIterator first skips any entries in the database iterator that are
// being updated by the transaction and sets the current iterator to the
// appropriate iterator depending on their validity and the order they compare
// in while taking into account the direction flag. When the cursor is being
// moved forwards and both iterators are valid, the iterator with the smaller
// key is chosen and vice versa when the cursor is being moved backwards. | [
"chooseIterator",
"first",
"skips",
"any",
"entries",
"in",
"the",
"database",
"iterator",
"that",
"are",
"being",
"updated",
"by",
"the",
"transaction",
"and",
"sets",
"the",
"current",
"iterator",
"to",
"the",
"appropriate",
"iterator",
"depending",
"on",
"their",
"validity",
"and",
"the",
"order",
"they",
"compare",
"in",
"while",
"taking",
"into",
"account",
"the",
"direction",
"flag",
".",
"When",
"the",
"cursor",
"is",
"being",
"moved",
"forwards",
"and",
"both",
"iterators",
"are",
"valid",
"the",
"iterator",
"with",
"the",
"smaller",
"key",
"is",
"chosen",
"and",
"vice",
"versa",
"when",
"the",
"cursor",
"is",
"being",
"moved",
"backwards",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L257-L291 | train |
btcsuite/btcd | database/ffldb/db.go | rawKey | func (c *cursor) rawKey() []byte {
// Nothing to return if cursor is exhausted.
if c.currentIter == nil {
return nil
}
return copySlice(c.currentIter.Key())
} | go | func (c *cursor) rawKey() []byte {
// Nothing to return if cursor is exhausted.
if c.currentIter == nil {
return nil
}
return copySlice(c.currentIter.Key())
} | [
"func",
"(",
"c",
"*",
"cursor",
")",
"rawKey",
"(",
")",
"[",
"]",
"byte",
"{",
"// Nothing to return if cursor is exhausted.",
"if",
"c",
".",
"currentIter",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"copySlice",
"(",
"c",
".",
"currentIter",
".",
"Key",
"(",
")",
")",
"\n",
"}"
] | // rawKey returns the current key the cursor is pointing to without stripping
// the current bucket prefix or bucket index prefix. | [
"rawKey",
"returns",
"the",
"current",
"key",
"the",
"cursor",
"is",
"pointing",
"to",
"without",
"stripping",
"the",
"current",
"bucket",
"prefix",
"or",
"bucket",
"index",
"prefix",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L389-L396 | train |
btcsuite/btcd | database/ffldb/db.go | Key | func (c *cursor) Key() []byte {
// Ensure transaction state is valid.
if err := c.bucket.tx.checkClosed(); err != nil {
return nil
}
// Nothing to return if cursor is exhausted.
if c.currentIter == nil {
return nil
}
// Slice out the actual key name and make a copy since it is no longer
// valid after iterating to the next item.
//
// The key is after the bucket index prefix and parent ID when the
// cursor is pointing to a nested bucket.
key := c.currentIter.Key()
if bytes.HasPrefix(key, bucketIndexPrefix) {
key = key[len(bucketIndexPrefix)+4:]
return copySlice(key)
}
// The key is after the bucket ID when the cursor is pointing to a
// normal entry.
key = key[len(c.bucket.id):]
return copySlice(key)
} | go | func (c *cursor) Key() []byte {
// Ensure transaction state is valid.
if err := c.bucket.tx.checkClosed(); err != nil {
return nil
}
// Nothing to return if cursor is exhausted.
if c.currentIter == nil {
return nil
}
// Slice out the actual key name and make a copy since it is no longer
// valid after iterating to the next item.
//
// The key is after the bucket index prefix and parent ID when the
// cursor is pointing to a nested bucket.
key := c.currentIter.Key()
if bytes.HasPrefix(key, bucketIndexPrefix) {
key = key[len(bucketIndexPrefix)+4:]
return copySlice(key)
}
// The key is after the bucket ID when the cursor is pointing to a
// normal entry.
key = key[len(c.bucket.id):]
return copySlice(key)
} | [
"func",
"(",
"c",
"*",
"cursor",
")",
"Key",
"(",
")",
"[",
"]",
"byte",
"{",
"// Ensure transaction state is valid.",
"if",
"err",
":=",
"c",
".",
"bucket",
".",
"tx",
".",
"checkClosed",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Nothing to return if cursor is exhausted.",
"if",
"c",
".",
"currentIter",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Slice out the actual key name and make a copy since it is no longer",
"// valid after iterating to the next item.",
"//",
"// The key is after the bucket index prefix and parent ID when the",
"// cursor is pointing to a nested bucket.",
"key",
":=",
"c",
".",
"currentIter",
".",
"Key",
"(",
")",
"\n",
"if",
"bytes",
".",
"HasPrefix",
"(",
"key",
",",
"bucketIndexPrefix",
")",
"{",
"key",
"=",
"key",
"[",
"len",
"(",
"bucketIndexPrefix",
")",
"+",
"4",
":",
"]",
"\n",
"return",
"copySlice",
"(",
"key",
")",
"\n",
"}",
"\n\n",
"// The key is after the bucket ID when the cursor is pointing to a",
"// normal entry.",
"key",
"=",
"key",
"[",
"len",
"(",
"c",
".",
"bucket",
".",
"id",
")",
":",
"]",
"\n",
"return",
"copySlice",
"(",
"key",
")",
"\n",
"}"
] | // Key returns the current key the cursor is pointing to.
//
// This function is part of the database.Cursor interface implementation. | [
"Key",
"returns",
"the",
"current",
"key",
"the",
"cursor",
"is",
"pointing",
"to",
".",
"This",
"function",
"is",
"part",
"of",
"the",
"database",
".",
"Cursor",
"interface",
"implementation",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L401-L427 | train |
btcsuite/btcd | database/ffldb/db.go | rawValue | func (c *cursor) rawValue() []byte {
// Nothing to return if cursor is exhausted.
if c.currentIter == nil {
return nil
}
return copySlice(c.currentIter.Value())
} | go | func (c *cursor) rawValue() []byte {
// Nothing to return if cursor is exhausted.
if c.currentIter == nil {
return nil
}
return copySlice(c.currentIter.Value())
} | [
"func",
"(",
"c",
"*",
"cursor",
")",
"rawValue",
"(",
")",
"[",
"]",
"byte",
"{",
"// Nothing to return if cursor is exhausted.",
"if",
"c",
".",
"currentIter",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"copySlice",
"(",
"c",
".",
"currentIter",
".",
"Value",
"(",
")",
")",
"\n",
"}"
] | // rawValue returns the current value the cursor is pointing to without
// stripping without filtering bucket index values. | [
"rawValue",
"returns",
"the",
"current",
"value",
"the",
"cursor",
"is",
"pointing",
"to",
"without",
"stripping",
"without",
"filtering",
"bucket",
"index",
"values",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L431-L438 | train |
btcsuite/btcd | database/ffldb/db.go | Value | func (c *cursor) Value() []byte {
// Ensure transaction state is valid.
if err := c.bucket.tx.checkClosed(); err != nil {
return nil
}
// Nothing to return if cursor is exhausted.
if c.currentIter == nil {
return nil
}
// Return nil for the value when the cursor is pointing to a nested
// bucket.
if bytes.HasPrefix(c.currentIter.Key(), bucketIndexPrefix) {
return nil
}
return copySlice(c.currentIter.Value())
} | go | func (c *cursor) Value() []byte {
// Ensure transaction state is valid.
if err := c.bucket.tx.checkClosed(); err != nil {
return nil
}
// Nothing to return if cursor is exhausted.
if c.currentIter == nil {
return nil
}
// Return nil for the value when the cursor is pointing to a nested
// bucket.
if bytes.HasPrefix(c.currentIter.Key(), bucketIndexPrefix) {
return nil
}
return copySlice(c.currentIter.Value())
} | [
"func",
"(",
"c",
"*",
"cursor",
")",
"Value",
"(",
")",
"[",
"]",
"byte",
"{",
"// Ensure transaction state is valid.",
"if",
"err",
":=",
"c",
".",
"bucket",
".",
"tx",
".",
"checkClosed",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Nothing to return if cursor is exhausted.",
"if",
"c",
".",
"currentIter",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Return nil for the value when the cursor is pointing to a nested",
"// bucket.",
"if",
"bytes",
".",
"HasPrefix",
"(",
"c",
".",
"currentIter",
".",
"Key",
"(",
")",
",",
"bucketIndexPrefix",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"copySlice",
"(",
"c",
".",
"currentIter",
".",
"Value",
"(",
")",
")",
"\n",
"}"
] | // Value returns the current value the cursor is pointing to. This will be nil
// for nested buckets.
//
// This function is part of the database.Cursor interface implementation. | [
"Value",
"returns",
"the",
"current",
"value",
"the",
"cursor",
"is",
"pointing",
"to",
".",
"This",
"will",
"be",
"nil",
"for",
"nested",
"buckets",
".",
"This",
"function",
"is",
"part",
"of",
"the",
"database",
".",
"Cursor",
"interface",
"implementation",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L444-L462 | train |
btcsuite/btcd | database/ffldb/db.go | bucketIndexKey | func bucketIndexKey(parentID [4]byte, key []byte) []byte {
// The serialized bucket index key format is:
// <bucketindexprefix><parentbucketid><bucketname>
indexKey := make([]byte, len(bucketIndexPrefix)+4+len(key))
copy(indexKey, bucketIndexPrefix)
copy(indexKey[len(bucketIndexPrefix):], parentID[:])
copy(indexKey[len(bucketIndexPrefix)+4:], key)
return indexKey
} | go | func bucketIndexKey(parentID [4]byte, key []byte) []byte {
// The serialized bucket index key format is:
// <bucketindexprefix><parentbucketid><bucketname>
indexKey := make([]byte, len(bucketIndexPrefix)+4+len(key))
copy(indexKey, bucketIndexPrefix)
copy(indexKey[len(bucketIndexPrefix):], parentID[:])
copy(indexKey[len(bucketIndexPrefix)+4:], key)
return indexKey
} | [
"func",
"bucketIndexKey",
"(",
"parentID",
"[",
"4",
"]",
"byte",
",",
"key",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"// The serialized bucket index key format is:",
"// <bucketindexprefix><parentbucketid><bucketname>",
"indexKey",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"bucketIndexPrefix",
")",
"+",
"4",
"+",
"len",
"(",
"key",
")",
")",
"\n",
"copy",
"(",
"indexKey",
",",
"bucketIndexPrefix",
")",
"\n",
"copy",
"(",
"indexKey",
"[",
"len",
"(",
"bucketIndexPrefix",
")",
":",
"]",
",",
"parentID",
"[",
":",
"]",
")",
"\n",
"copy",
"(",
"indexKey",
"[",
"len",
"(",
"bucketIndexPrefix",
")",
"+",
"4",
":",
"]",
",",
"key",
")",
"\n",
"return",
"indexKey",
"\n",
"}"
] | // bucketIndexKey returns the actual key to use for storing and retrieving a
// child bucket in the bucket index. This is required because additional
// information is needed to distinguish nested buckets with the same name. | [
"bucketIndexKey",
"returns",
"the",
"actual",
"key",
"to",
"use",
"for",
"storing",
"and",
"retrieving",
"a",
"child",
"bucket",
"in",
"the",
"bucket",
"index",
".",
"This",
"is",
"required",
"because",
"additional",
"information",
"is",
"needed",
"to",
"distinguish",
"nested",
"buckets",
"with",
"the",
"same",
"name",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L565-L573 | train |
btcsuite/btcd | database/ffldb/db.go | bucketizedKey | func bucketizedKey(bucketID [4]byte, key []byte) []byte {
// The serialized block index key format is:
// <bucketid><key>
bKey := make([]byte, 4+len(key))
copy(bKey, bucketID[:])
copy(bKey[4:], key)
return bKey
} | go | func bucketizedKey(bucketID [4]byte, key []byte) []byte {
// The serialized block index key format is:
// <bucketid><key>
bKey := make([]byte, 4+len(key))
copy(bKey, bucketID[:])
copy(bKey[4:], key)
return bKey
} | [
"func",
"bucketizedKey",
"(",
"bucketID",
"[",
"4",
"]",
"byte",
",",
"key",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"// The serialized block index key format is:",
"// <bucketid><key>",
"bKey",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"4",
"+",
"len",
"(",
"key",
")",
")",
"\n",
"copy",
"(",
"bKey",
",",
"bucketID",
"[",
":",
"]",
")",
"\n",
"copy",
"(",
"bKey",
"[",
"4",
":",
"]",
",",
"key",
")",
"\n",
"return",
"bKey",
"\n",
"}"
] | // bucketizedKey returns the actual key to use for storing and retrieving a key
// for the provided bucket ID. This is required because bucketizing is handled
// through the use of a unique prefix per bucket. | [
"bucketizedKey",
"returns",
"the",
"actual",
"key",
"to",
"use",
"for",
"storing",
"and",
"retrieving",
"a",
"key",
"for",
"the",
"provided",
"bucket",
"ID",
".",
"This",
"is",
"required",
"because",
"bucketizing",
"is",
"handled",
"through",
"the",
"use",
"of",
"a",
"unique",
"prefix",
"per",
"bucket",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L578-L585 | train |
btcsuite/btcd | database/ffldb/db.go | Bucket | func (b *bucket) Bucket(key []byte) database.Bucket {
// Ensure transaction state is valid.
if err := b.tx.checkClosed(); err != nil {
return nil
}
// Attempt to fetch the ID for the child bucket. The bucket does not
// exist if the bucket index entry does not exist.
childID := b.tx.fetchKey(bucketIndexKey(b.id, key))
if childID == nil {
return nil
}
childBucket := &bucket{tx: b.tx}
copy(childBucket.id[:], childID)
return childBucket
} | go | func (b *bucket) Bucket(key []byte) database.Bucket {
// Ensure transaction state is valid.
if err := b.tx.checkClosed(); err != nil {
return nil
}
// Attempt to fetch the ID for the child bucket. The bucket does not
// exist if the bucket index entry does not exist.
childID := b.tx.fetchKey(bucketIndexKey(b.id, key))
if childID == nil {
return nil
}
childBucket := &bucket{tx: b.tx}
copy(childBucket.id[:], childID)
return childBucket
} | [
"func",
"(",
"b",
"*",
"bucket",
")",
"Bucket",
"(",
"key",
"[",
"]",
"byte",
")",
"database",
".",
"Bucket",
"{",
"// Ensure transaction state is valid.",
"if",
"err",
":=",
"b",
".",
"tx",
".",
"checkClosed",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Attempt to fetch the ID for the child bucket. The bucket does not",
"// exist if the bucket index entry does not exist.",
"childID",
":=",
"b",
".",
"tx",
".",
"fetchKey",
"(",
"bucketIndexKey",
"(",
"b",
".",
"id",
",",
"key",
")",
")",
"\n",
"if",
"childID",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"childBucket",
":=",
"&",
"bucket",
"{",
"tx",
":",
"b",
".",
"tx",
"}",
"\n",
"copy",
"(",
"childBucket",
".",
"id",
"[",
":",
"]",
",",
"childID",
")",
"\n",
"return",
"childBucket",
"\n",
"}"
] | // Bucket retrieves a nested bucket with the given key. Returns nil if
// the bucket does not exist.
//
// This function is part of the database.Bucket interface implementation. | [
"Bucket",
"retrieves",
"a",
"nested",
"bucket",
"with",
"the",
"given",
"key",
".",
"Returns",
"nil",
"if",
"the",
"bucket",
"does",
"not",
"exist",
".",
"This",
"function",
"is",
"part",
"of",
"the",
"database",
".",
"Bucket",
"interface",
"implementation",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L591-L607 | train |
btcsuite/btcd | database/ffldb/db.go | removeActiveIter | func (tx *transaction) removeActiveIter(iter *treap.Iterator) {
// An indexing for loop is intentionally used over a range here as range
// does not reevaluate the slice on each iteration nor does it adjust
// the index for the modified slice.
tx.activeIterLock.Lock()
for i := 0; i < len(tx.activeIters); i++ {
if tx.activeIters[i] == iter {
copy(tx.activeIters[i:], tx.activeIters[i+1:])
tx.activeIters[len(tx.activeIters)-1] = nil
tx.activeIters = tx.activeIters[:len(tx.activeIters)-1]
}
}
tx.activeIterLock.Unlock()
} | go | func (tx *transaction) removeActiveIter(iter *treap.Iterator) {
// An indexing for loop is intentionally used over a range here as range
// does not reevaluate the slice on each iteration nor does it adjust
// the index for the modified slice.
tx.activeIterLock.Lock()
for i := 0; i < len(tx.activeIters); i++ {
if tx.activeIters[i] == iter {
copy(tx.activeIters[i:], tx.activeIters[i+1:])
tx.activeIters[len(tx.activeIters)-1] = nil
tx.activeIters = tx.activeIters[:len(tx.activeIters)-1]
}
}
tx.activeIterLock.Unlock()
} | [
"func",
"(",
"tx",
"*",
"transaction",
")",
"removeActiveIter",
"(",
"iter",
"*",
"treap",
".",
"Iterator",
")",
"{",
"// An indexing for loop is intentionally used over a range here as range",
"// does not reevaluate the slice on each iteration nor does it adjust",
"// the index for the modified slice.",
"tx",
".",
"activeIterLock",
".",
"Lock",
"(",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"tx",
".",
"activeIters",
")",
";",
"i",
"++",
"{",
"if",
"tx",
".",
"activeIters",
"[",
"i",
"]",
"==",
"iter",
"{",
"copy",
"(",
"tx",
".",
"activeIters",
"[",
"i",
":",
"]",
",",
"tx",
".",
"activeIters",
"[",
"i",
"+",
"1",
":",
"]",
")",
"\n",
"tx",
".",
"activeIters",
"[",
"len",
"(",
"tx",
".",
"activeIters",
")",
"-",
"1",
"]",
"=",
"nil",
"\n",
"tx",
".",
"activeIters",
"=",
"tx",
".",
"activeIters",
"[",
":",
"len",
"(",
"tx",
".",
"activeIters",
")",
"-",
"1",
"]",
"\n",
"}",
"\n",
"}",
"\n",
"tx",
".",
"activeIterLock",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // removeActiveIter removes the passed iterator from the list of active
// iterators against the pending keys treap. | [
"removeActiveIter",
"removes",
"the",
"passed",
"iterator",
"from",
"the",
"list",
"of",
"active",
"iterators",
"against",
"the",
"pending",
"keys",
"treap",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L985-L998 | train |
btcsuite/btcd | database/ffldb/db.go | addActiveIter | func (tx *transaction) addActiveIter(iter *treap.Iterator) {
tx.activeIterLock.Lock()
tx.activeIters = append(tx.activeIters, iter)
tx.activeIterLock.Unlock()
} | go | func (tx *transaction) addActiveIter(iter *treap.Iterator) {
tx.activeIterLock.Lock()
tx.activeIters = append(tx.activeIters, iter)
tx.activeIterLock.Unlock()
} | [
"func",
"(",
"tx",
"*",
"transaction",
")",
"addActiveIter",
"(",
"iter",
"*",
"treap",
".",
"Iterator",
")",
"{",
"tx",
".",
"activeIterLock",
".",
"Lock",
"(",
")",
"\n",
"tx",
".",
"activeIters",
"=",
"append",
"(",
"tx",
".",
"activeIters",
",",
"iter",
")",
"\n",
"tx",
".",
"activeIterLock",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // addActiveIter adds the passed iterator to the list of active iterators for
// the pending keys treap. | [
"addActiveIter",
"adds",
"the",
"passed",
"iterator",
"to",
"the",
"list",
"of",
"active",
"iterators",
"for",
"the",
"pending",
"keys",
"treap",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L1002-L1006 | train |
btcsuite/btcd | database/ffldb/db.go | notifyActiveIters | func (tx *transaction) notifyActiveIters() {
tx.activeIterLock.RLock()
for _, iter := range tx.activeIters {
iter.ForceReseek()
}
tx.activeIterLock.RUnlock()
} | go | func (tx *transaction) notifyActiveIters() {
tx.activeIterLock.RLock()
for _, iter := range tx.activeIters {
iter.ForceReseek()
}
tx.activeIterLock.RUnlock()
} | [
"func",
"(",
"tx",
"*",
"transaction",
")",
"notifyActiveIters",
"(",
")",
"{",
"tx",
".",
"activeIterLock",
".",
"RLock",
"(",
")",
"\n",
"for",
"_",
",",
"iter",
":=",
"range",
"tx",
".",
"activeIters",
"{",
"iter",
".",
"ForceReseek",
"(",
")",
"\n",
"}",
"\n",
"tx",
".",
"activeIterLock",
".",
"RUnlock",
"(",
")",
"\n",
"}"
] | // notifyActiveIters notifies all of the active iterators for the pending keys
// treap that it has been updated. | [
"notifyActiveIters",
"notifies",
"all",
"of",
"the",
"active",
"iterators",
"for",
"the",
"pending",
"keys",
"treap",
"that",
"it",
"has",
"been",
"updated",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L1010-L1016 | train |
btcsuite/btcd | database/ffldb/db.go | checkClosed | func (tx *transaction) checkClosed() error {
// The transaction is no longer valid if it has been closed.
if tx.closed {
return makeDbErr(database.ErrTxClosed, errTxClosedStr, nil)
}
return nil
} | go | func (tx *transaction) checkClosed() error {
// The transaction is no longer valid if it has been closed.
if tx.closed {
return makeDbErr(database.ErrTxClosed, errTxClosedStr, nil)
}
return nil
} | [
"func",
"(",
"tx",
"*",
"transaction",
")",
"checkClosed",
"(",
")",
"error",
"{",
"// The transaction is no longer valid if it has been closed.",
"if",
"tx",
".",
"closed",
"{",
"return",
"makeDbErr",
"(",
"database",
".",
"ErrTxClosed",
",",
"errTxClosedStr",
",",
"nil",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // checkClosed returns an error if the the database or transaction is closed. | [
"checkClosed",
"returns",
"an",
"error",
"if",
"the",
"the",
"database",
"or",
"transaction",
"is",
"closed",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L1019-L1026 | train |
btcsuite/btcd | database/ffldb/db.go | hasKey | func (tx *transaction) hasKey(key []byte) bool {
// When the transaction is writable, check the pending transaction
// state first.
if tx.writable {
if tx.pendingRemove.Has(key) {
return false
}
if tx.pendingKeys.Has(key) {
return true
}
}
// Consult the database cache and underlying database.
return tx.snapshot.Has(key)
} | go | func (tx *transaction) hasKey(key []byte) bool {
// When the transaction is writable, check the pending transaction
// state first.
if tx.writable {
if tx.pendingRemove.Has(key) {
return false
}
if tx.pendingKeys.Has(key) {
return true
}
}
// Consult the database cache and underlying database.
return tx.snapshot.Has(key)
} | [
"func",
"(",
"tx",
"*",
"transaction",
")",
"hasKey",
"(",
"key",
"[",
"]",
"byte",
")",
"bool",
"{",
"// When the transaction is writable, check the pending transaction",
"// state first.",
"if",
"tx",
".",
"writable",
"{",
"if",
"tx",
".",
"pendingRemove",
".",
"Has",
"(",
"key",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"tx",
".",
"pendingKeys",
".",
"Has",
"(",
"key",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Consult the database cache and underlying database.",
"return",
"tx",
".",
"snapshot",
".",
"Has",
"(",
"key",
")",
"\n",
"}"
] | // hasKey returns whether or not the provided key exists in the database while
// taking into account the current transaction state. | [
"hasKey",
"returns",
"whether",
"or",
"not",
"the",
"provided",
"key",
"exists",
"in",
"the",
"database",
"while",
"taking",
"into",
"account",
"the",
"current",
"transaction",
"state",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L1030-L1044 | train |
btcsuite/btcd | database/ffldb/db.go | hasBlock | func (tx *transaction) hasBlock(hash *chainhash.Hash) bool {
// Return true if the block is pending to be written on commit since
// it exists from the viewpoint of this transaction.
if _, exists := tx.pendingBlocks[*hash]; exists {
return true
}
return tx.hasKey(bucketizedKey(blockIdxBucketID, hash[:]))
} | go | func (tx *transaction) hasBlock(hash *chainhash.Hash) bool {
// Return true if the block is pending to be written on commit since
// it exists from the viewpoint of this transaction.
if _, exists := tx.pendingBlocks[*hash]; exists {
return true
}
return tx.hasKey(bucketizedKey(blockIdxBucketID, hash[:]))
} | [
"func",
"(",
"tx",
"*",
"transaction",
")",
"hasBlock",
"(",
"hash",
"*",
"chainhash",
".",
"Hash",
")",
"bool",
"{",
"// Return true if the block is pending to be written on commit since",
"// it exists from the viewpoint of this transaction.",
"if",
"_",
",",
"exists",
":=",
"tx",
".",
"pendingBlocks",
"[",
"*",
"hash",
"]",
";",
"exists",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"return",
"tx",
".",
"hasKey",
"(",
"bucketizedKey",
"(",
"blockIdxBucketID",
",",
"hash",
"[",
":",
"]",
")",
")",
"\n",
"}"
] | // hasBlock returns whether or not a block with the given hash exists. | [
"hasBlock",
"returns",
"whether",
"or",
"not",
"a",
"block",
"with",
"the",
"given",
"hash",
"exists",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L1128-L1136 | train |
btcsuite/btcd | database/ffldb/db.go | fetchBlockRow | func (tx *transaction) fetchBlockRow(hash *chainhash.Hash) ([]byte, error) {
blockRow := tx.blockIdxBucket.Get(hash[:])
if blockRow == nil {
str := fmt.Sprintf("block %s does not exist", hash)
return nil, makeDbErr(database.ErrBlockNotFound, str, nil)
}
return blockRow, nil
} | go | func (tx *transaction) fetchBlockRow(hash *chainhash.Hash) ([]byte, error) {
blockRow := tx.blockIdxBucket.Get(hash[:])
if blockRow == nil {
str := fmt.Sprintf("block %s does not exist", hash)
return nil, makeDbErr(database.ErrBlockNotFound, str, nil)
}
return blockRow, nil
} | [
"func",
"(",
"tx",
"*",
"transaction",
")",
"fetchBlockRow",
"(",
"hash",
"*",
"chainhash",
".",
"Hash",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"blockRow",
":=",
"tx",
".",
"blockIdxBucket",
".",
"Get",
"(",
"hash",
"[",
":",
"]",
")",
"\n",
"if",
"blockRow",
"==",
"nil",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"hash",
")",
"\n",
"return",
"nil",
",",
"makeDbErr",
"(",
"database",
".",
"ErrBlockNotFound",
",",
"str",
",",
"nil",
")",
"\n",
"}",
"\n\n",
"return",
"blockRow",
",",
"nil",
"\n",
"}"
] | // fetchBlockRow fetches the metadata stored in the block index for the provided
// hash. It will return ErrBlockNotFound if there is no entry. | [
"fetchBlockRow",
"fetches",
"the",
"metadata",
"stored",
"in",
"the",
"block",
"index",
"for",
"the",
"provided",
"hash",
".",
"It",
"will",
"return",
"ErrBlockNotFound",
"if",
"there",
"is",
"no",
"entry",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L1231-L1239 | train |
btcsuite/btcd | database/ffldb/db.go | fetchPendingRegion | func (tx *transaction) fetchPendingRegion(region *database.BlockRegion) ([]byte, error) {
// Nothing to do if the block is not pending to be written on commit.
idx, exists := tx.pendingBlocks[*region.Hash]
if !exists {
return nil, nil
}
// Ensure the region is within the bounds of the block.
blockBytes := tx.pendingBlockData[idx].bytes
blockLen := uint32(len(blockBytes))
endOffset := region.Offset + region.Len
if endOffset < region.Offset || endOffset > blockLen {
str := fmt.Sprintf("block %s region offset %d, length %d "+
"exceeds block length of %d", region.Hash,
region.Offset, region.Len, blockLen)
return nil, makeDbErr(database.ErrBlockRegionInvalid, str, nil)
}
// Return the bytes from the pending block.
return blockBytes[region.Offset:endOffset:endOffset], nil
} | go | func (tx *transaction) fetchPendingRegion(region *database.BlockRegion) ([]byte, error) {
// Nothing to do if the block is not pending to be written on commit.
idx, exists := tx.pendingBlocks[*region.Hash]
if !exists {
return nil, nil
}
// Ensure the region is within the bounds of the block.
blockBytes := tx.pendingBlockData[idx].bytes
blockLen := uint32(len(blockBytes))
endOffset := region.Offset + region.Len
if endOffset < region.Offset || endOffset > blockLen {
str := fmt.Sprintf("block %s region offset %d, length %d "+
"exceeds block length of %d", region.Hash,
region.Offset, region.Len, blockLen)
return nil, makeDbErr(database.ErrBlockRegionInvalid, str, nil)
}
// Return the bytes from the pending block.
return blockBytes[region.Offset:endOffset:endOffset], nil
} | [
"func",
"(",
"tx",
"*",
"transaction",
")",
"fetchPendingRegion",
"(",
"region",
"*",
"database",
".",
"BlockRegion",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"// Nothing to do if the block is not pending to be written on commit.",
"idx",
",",
"exists",
":=",
"tx",
".",
"pendingBlocks",
"[",
"*",
"region",
".",
"Hash",
"]",
"\n",
"if",
"!",
"exists",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"// Ensure the region is within the bounds of the block.",
"blockBytes",
":=",
"tx",
".",
"pendingBlockData",
"[",
"idx",
"]",
".",
"bytes",
"\n",
"blockLen",
":=",
"uint32",
"(",
"len",
"(",
"blockBytes",
")",
")",
"\n",
"endOffset",
":=",
"region",
".",
"Offset",
"+",
"region",
".",
"Len",
"\n",
"if",
"endOffset",
"<",
"region",
".",
"Offset",
"||",
"endOffset",
">",
"blockLen",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"region",
".",
"Hash",
",",
"region",
".",
"Offset",
",",
"region",
".",
"Len",
",",
"blockLen",
")",
"\n",
"return",
"nil",
",",
"makeDbErr",
"(",
"database",
".",
"ErrBlockRegionInvalid",
",",
"str",
",",
"nil",
")",
"\n",
"}",
"\n\n",
"// Return the bytes from the pending block.",
"return",
"blockBytes",
"[",
"region",
".",
"Offset",
":",
"endOffset",
":",
"endOffset",
"]",
",",
"nil",
"\n",
"}"
] | // fetchPendingRegion attempts to fetch the provided region from any block which
// are pending to be written on commit. It will return nil for the byte slice
// when the region references a block which is not pending. When the region
// does reference a pending block, it is bounds checked and returns
// ErrBlockRegionInvalid if invalid. | [
"fetchPendingRegion",
"attempts",
"to",
"fetch",
"the",
"provided",
"region",
"from",
"any",
"block",
"which",
"are",
"pending",
"to",
"be",
"written",
"on",
"commit",
".",
"It",
"will",
"return",
"nil",
"for",
"the",
"byte",
"slice",
"when",
"the",
"region",
"references",
"a",
"block",
"which",
"is",
"not",
"pending",
".",
"When",
"the",
"region",
"does",
"reference",
"a",
"pending",
"block",
"it",
"is",
"bounds",
"checked",
"and",
"returns",
"ErrBlockRegionInvalid",
"if",
"invalid",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L1384-L1404 | train |
btcsuite/btcd | database/ffldb/db.go | close | func (tx *transaction) close() {
tx.closed = true
// Clear pending blocks that would have been written on commit.
tx.pendingBlocks = nil
tx.pendingBlockData = nil
// Clear pending keys that would have been written or deleted on commit.
tx.pendingKeys = nil
tx.pendingRemove = nil
// Release the snapshot.
if tx.snapshot != nil {
tx.snapshot.Release()
tx.snapshot = nil
}
tx.db.closeLock.RUnlock()
// Release the writer lock for writable transactions to unblock any
// other write transaction which are possibly waiting.
if tx.writable {
tx.db.writeLock.Unlock()
}
} | go | func (tx *transaction) close() {
tx.closed = true
// Clear pending blocks that would have been written on commit.
tx.pendingBlocks = nil
tx.pendingBlockData = nil
// Clear pending keys that would have been written or deleted on commit.
tx.pendingKeys = nil
tx.pendingRemove = nil
// Release the snapshot.
if tx.snapshot != nil {
tx.snapshot.Release()
tx.snapshot = nil
}
tx.db.closeLock.RUnlock()
// Release the writer lock for writable transactions to unblock any
// other write transaction which are possibly waiting.
if tx.writable {
tx.db.writeLock.Unlock()
}
} | [
"func",
"(",
"tx",
"*",
"transaction",
")",
"close",
"(",
")",
"{",
"tx",
".",
"closed",
"=",
"true",
"\n\n",
"// Clear pending blocks that would have been written on commit.",
"tx",
".",
"pendingBlocks",
"=",
"nil",
"\n",
"tx",
".",
"pendingBlockData",
"=",
"nil",
"\n\n",
"// Clear pending keys that would have been written or deleted on commit.",
"tx",
".",
"pendingKeys",
"=",
"nil",
"\n",
"tx",
".",
"pendingRemove",
"=",
"nil",
"\n\n",
"// Release the snapshot.",
"if",
"tx",
".",
"snapshot",
"!=",
"nil",
"{",
"tx",
".",
"snapshot",
".",
"Release",
"(",
")",
"\n",
"tx",
".",
"snapshot",
"=",
"nil",
"\n",
"}",
"\n\n",
"tx",
".",
"db",
".",
"closeLock",
".",
"RUnlock",
"(",
")",
"\n\n",
"// Release the writer lock for writable transactions to unblock any",
"// other write transaction which are possibly waiting.",
"if",
"tx",
".",
"writable",
"{",
"tx",
".",
"db",
".",
"writeLock",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // close marks the transaction closed then releases any pending data, the
// underlying snapshot, the transaction read lock, and the write lock when the
// transaction is writable. | [
"close",
"marks",
"the",
"transaction",
"closed",
"then",
"releases",
"any",
"pending",
"data",
"the",
"underlying",
"snapshot",
"the",
"transaction",
"read",
"lock",
"and",
"the",
"write",
"lock",
"when",
"the",
"transaction",
"is",
"writable",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L1589-L1613 | train |
btcsuite/btcd | database/ffldb/db.go | writePendingAndCommit | func (tx *transaction) writePendingAndCommit() error {
// Save the current block store write position for potential rollback.
// These variables are only updated here in this function and there can
// only be one write transaction active at a time, so it's safe to store
// them for potential rollback.
wc := tx.db.store.writeCursor
wc.RLock()
oldBlkFileNum := wc.curFileNum
oldBlkOffset := wc.curOffset
wc.RUnlock()
// rollback is a closure that is used to rollback all writes to the
// block files.
rollback := func() {
// Rollback any modifications made to the block files if needed.
tx.db.store.handleRollback(oldBlkFileNum, oldBlkOffset)
}
// Loop through all of the pending blocks to store and write them.
for _, blockData := range tx.pendingBlockData {
log.Tracef("Storing block %s", blockData.hash)
location, err := tx.db.store.writeBlock(blockData.bytes)
if err != nil {
rollback()
return err
}
// Add a record in the block index for the block. The record
// includes the location information needed to locate the block
// on the filesystem as well as the block header since they are
// so commonly needed.
blockRow := serializeBlockLoc(location)
err = tx.blockIdxBucket.Put(blockData.hash[:], blockRow)
if err != nil {
rollback()
return err
}
}
// Update the metadata for the current write file and offset.
writeRow := serializeWriteRow(wc.curFileNum, wc.curOffset)
if err := tx.metaBucket.Put(writeLocKeyName, writeRow); err != nil {
rollback()
return convertErr("failed to store write cursor", err)
}
// Atomically update the database cache. The cache automatically
// handles flushing to the underlying persistent storage database.
return tx.db.cache.commitTx(tx)
} | go | func (tx *transaction) writePendingAndCommit() error {
// Save the current block store write position for potential rollback.
// These variables are only updated here in this function and there can
// only be one write transaction active at a time, so it's safe to store
// them for potential rollback.
wc := tx.db.store.writeCursor
wc.RLock()
oldBlkFileNum := wc.curFileNum
oldBlkOffset := wc.curOffset
wc.RUnlock()
// rollback is a closure that is used to rollback all writes to the
// block files.
rollback := func() {
// Rollback any modifications made to the block files if needed.
tx.db.store.handleRollback(oldBlkFileNum, oldBlkOffset)
}
// Loop through all of the pending blocks to store and write them.
for _, blockData := range tx.pendingBlockData {
log.Tracef("Storing block %s", blockData.hash)
location, err := tx.db.store.writeBlock(blockData.bytes)
if err != nil {
rollback()
return err
}
// Add a record in the block index for the block. The record
// includes the location information needed to locate the block
// on the filesystem as well as the block header since they are
// so commonly needed.
blockRow := serializeBlockLoc(location)
err = tx.blockIdxBucket.Put(blockData.hash[:], blockRow)
if err != nil {
rollback()
return err
}
}
// Update the metadata for the current write file and offset.
writeRow := serializeWriteRow(wc.curFileNum, wc.curOffset)
if err := tx.metaBucket.Put(writeLocKeyName, writeRow); err != nil {
rollback()
return convertErr("failed to store write cursor", err)
}
// Atomically update the database cache. The cache automatically
// handles flushing to the underlying persistent storage database.
return tx.db.cache.commitTx(tx)
} | [
"func",
"(",
"tx",
"*",
"transaction",
")",
"writePendingAndCommit",
"(",
")",
"error",
"{",
"// Save the current block store write position for potential rollback.",
"// These variables are only updated here in this function and there can",
"// only be one write transaction active at a time, so it's safe to store",
"// them for potential rollback.",
"wc",
":=",
"tx",
".",
"db",
".",
"store",
".",
"writeCursor",
"\n",
"wc",
".",
"RLock",
"(",
")",
"\n",
"oldBlkFileNum",
":=",
"wc",
".",
"curFileNum",
"\n",
"oldBlkOffset",
":=",
"wc",
".",
"curOffset",
"\n",
"wc",
".",
"RUnlock",
"(",
")",
"\n\n",
"// rollback is a closure that is used to rollback all writes to the",
"// block files.",
"rollback",
":=",
"func",
"(",
")",
"{",
"// Rollback any modifications made to the block files if needed.",
"tx",
".",
"db",
".",
"store",
".",
"handleRollback",
"(",
"oldBlkFileNum",
",",
"oldBlkOffset",
")",
"\n",
"}",
"\n\n",
"// Loop through all of the pending blocks to store and write them.",
"for",
"_",
",",
"blockData",
":=",
"range",
"tx",
".",
"pendingBlockData",
"{",
"log",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"blockData",
".",
"hash",
")",
"\n",
"location",
",",
"err",
":=",
"tx",
".",
"db",
".",
"store",
".",
"writeBlock",
"(",
"blockData",
".",
"bytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"rollback",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// Add a record in the block index for the block. The record",
"// includes the location information needed to locate the block",
"// on the filesystem as well as the block header since they are",
"// so commonly needed.",
"blockRow",
":=",
"serializeBlockLoc",
"(",
"location",
")",
"\n",
"err",
"=",
"tx",
".",
"blockIdxBucket",
".",
"Put",
"(",
"blockData",
".",
"hash",
"[",
":",
"]",
",",
"blockRow",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"rollback",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Update the metadata for the current write file and offset.",
"writeRow",
":=",
"serializeWriteRow",
"(",
"wc",
".",
"curFileNum",
",",
"wc",
".",
"curOffset",
")",
"\n",
"if",
"err",
":=",
"tx",
".",
"metaBucket",
".",
"Put",
"(",
"writeLocKeyName",
",",
"writeRow",
")",
";",
"err",
"!=",
"nil",
"{",
"rollback",
"(",
")",
"\n",
"return",
"convertErr",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Atomically update the database cache. The cache automatically",
"// handles flushing to the underlying persistent storage database.",
"return",
"tx",
".",
"db",
".",
"cache",
".",
"commitTx",
"(",
"tx",
")",
"\n",
"}"
] | // writePendingAndCommit writes pending block data to the flat block files,
// updates the metadata with their locations as well as the new current write
// location, and commits the metadata to the memory database cache. It also
// properly handles rollback in the case of failures.
//
// This function MUST only be called when there is pending data to be written. | [
"writePendingAndCommit",
"writes",
"pending",
"block",
"data",
"to",
"the",
"flat",
"block",
"files",
"updates",
"the",
"metadata",
"with",
"their",
"locations",
"as",
"well",
"as",
"the",
"new",
"current",
"write",
"location",
"and",
"commits",
"the",
"metadata",
"to",
"the",
"memory",
"database",
"cache",
".",
"It",
"also",
"properly",
"handles",
"rollback",
"in",
"the",
"case",
"of",
"failures",
".",
"This",
"function",
"MUST",
"only",
"be",
"called",
"when",
"there",
"is",
"pending",
"data",
"to",
"be",
"written",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L1621-L1670 | train |
btcsuite/btcd | database/ffldb/db.go | Commit | func (tx *transaction) Commit() error {
// Prevent commits on managed transactions.
if tx.managed {
tx.close()
panic("managed transaction commit not allowed")
}
// Ensure transaction state is valid.
if err := tx.checkClosed(); err != nil {
return err
}
// Regardless of whether the commit succeeds, the transaction is closed
// on return.
defer tx.close()
// Ensure the transaction is writable.
if !tx.writable {
str := "Commit requires a writable database transaction"
return makeDbErr(database.ErrTxNotWritable, str, nil)
}
// Write pending data. The function will rollback if any errors occur.
return tx.writePendingAndCommit()
} | go | func (tx *transaction) Commit() error {
// Prevent commits on managed transactions.
if tx.managed {
tx.close()
panic("managed transaction commit not allowed")
}
// Ensure transaction state is valid.
if err := tx.checkClosed(); err != nil {
return err
}
// Regardless of whether the commit succeeds, the transaction is closed
// on return.
defer tx.close()
// Ensure the transaction is writable.
if !tx.writable {
str := "Commit requires a writable database transaction"
return makeDbErr(database.ErrTxNotWritable, str, nil)
}
// Write pending data. The function will rollback if any errors occur.
return tx.writePendingAndCommit()
} | [
"func",
"(",
"tx",
"*",
"transaction",
")",
"Commit",
"(",
")",
"error",
"{",
"// Prevent commits on managed transactions.",
"if",
"tx",
".",
"managed",
"{",
"tx",
".",
"close",
"(",
")",
"\n",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Ensure transaction state is valid.",
"if",
"err",
":=",
"tx",
".",
"checkClosed",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Regardless of whether the commit succeeds, the transaction is closed",
"// on return.",
"defer",
"tx",
".",
"close",
"(",
")",
"\n\n",
"// Ensure the transaction is writable.",
"if",
"!",
"tx",
".",
"writable",
"{",
"str",
":=",
"\"",
"\"",
"\n",
"return",
"makeDbErr",
"(",
"database",
".",
"ErrTxNotWritable",
",",
"str",
",",
"nil",
")",
"\n",
"}",
"\n\n",
"// Write pending data. The function will rollback if any errors occur.",
"return",
"tx",
".",
"writePendingAndCommit",
"(",
")",
"\n",
"}"
] | // Commit commits all changes that have been made to the root metadata bucket
// and all of its sub-buckets to the database cache which is periodically synced
// to persistent storage. In addition, it commits all new blocks directly to
// persistent storage bypassing the db cache. Blocks can be rather large, so
// this help increase the amount of cache available for the metadata updates and
// is safe since blocks are immutable.
//
// This function is part of the database.Tx interface implementation. | [
"Commit",
"commits",
"all",
"changes",
"that",
"have",
"been",
"made",
"to",
"the",
"root",
"metadata",
"bucket",
"and",
"all",
"of",
"its",
"sub",
"-",
"buckets",
"to",
"the",
"database",
"cache",
"which",
"is",
"periodically",
"synced",
"to",
"persistent",
"storage",
".",
"In",
"addition",
"it",
"commits",
"all",
"new",
"blocks",
"directly",
"to",
"persistent",
"storage",
"bypassing",
"the",
"db",
"cache",
".",
"Blocks",
"can",
"be",
"rather",
"large",
"so",
"this",
"help",
"increase",
"the",
"amount",
"of",
"cache",
"available",
"for",
"the",
"metadata",
"updates",
"and",
"is",
"safe",
"since",
"blocks",
"are",
"immutable",
".",
"This",
"function",
"is",
"part",
"of",
"the",
"database",
".",
"Tx",
"interface",
"implementation",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L1680-L1704 | train |
btcsuite/btcd | database/ffldb/db.go | Rollback | func (tx *transaction) Rollback() error {
// Prevent rollbacks on managed transactions.
if tx.managed {
tx.close()
panic("managed transaction rollback not allowed")
}
// Ensure transaction state is valid.
if err := tx.checkClosed(); err != nil {
return err
}
tx.close()
return nil
} | go | func (tx *transaction) Rollback() error {
// Prevent rollbacks on managed transactions.
if tx.managed {
tx.close()
panic("managed transaction rollback not allowed")
}
// Ensure transaction state is valid.
if err := tx.checkClosed(); err != nil {
return err
}
tx.close()
return nil
} | [
"func",
"(",
"tx",
"*",
"transaction",
")",
"Rollback",
"(",
")",
"error",
"{",
"// Prevent rollbacks on managed transactions.",
"if",
"tx",
".",
"managed",
"{",
"tx",
".",
"close",
"(",
")",
"\n",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Ensure transaction state is valid.",
"if",
"err",
":=",
"tx",
".",
"checkClosed",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"tx",
".",
"close",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Rollback undoes all changes that have been made to the root bucket and all of
// its sub-buckets.
//
// This function is part of the database.Tx interface implementation. | [
"Rollback",
"undoes",
"all",
"changes",
"that",
"have",
"been",
"made",
"to",
"the",
"root",
"bucket",
"and",
"all",
"of",
"its",
"sub",
"-",
"buckets",
".",
"This",
"function",
"is",
"part",
"of",
"the",
"database",
".",
"Tx",
"interface",
"implementation",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L1710-L1724 | train |
btcsuite/btcd | database/ffldb/db.go | begin | func (db *db) begin(writable bool) (*transaction, error) {
// Whenever a new writable transaction is started, grab the write lock
// to ensure only a single write transaction can be active at the same
// time. This lock will not be released until the transaction is
// closed (via Rollback or Commit).
if writable {
db.writeLock.Lock()
}
// Whenever a new transaction is started, grab a read lock against the
// database to ensure Close will wait for the transaction to finish.
// This lock will not be released until the transaction is closed (via
// Rollback or Commit).
db.closeLock.RLock()
if db.closed {
db.closeLock.RUnlock()
if writable {
db.writeLock.Unlock()
}
return nil, makeDbErr(database.ErrDbNotOpen, errDbNotOpenStr,
nil)
}
// Grab a snapshot of the database cache (which in turn also handles the
// underlying database).
snapshot, err := db.cache.Snapshot()
if err != nil {
db.closeLock.RUnlock()
if writable {
db.writeLock.Unlock()
}
return nil, err
}
// The metadata and block index buckets are internal-only buckets, so
// they have defined IDs.
tx := &transaction{
writable: writable,
db: db,
snapshot: snapshot,
pendingKeys: treap.NewMutable(),
pendingRemove: treap.NewMutable(),
}
tx.metaBucket = &bucket{tx: tx, id: metadataBucketID}
tx.blockIdxBucket = &bucket{tx: tx, id: blockIdxBucketID}
return tx, nil
} | go | func (db *db) begin(writable bool) (*transaction, error) {
// Whenever a new writable transaction is started, grab the write lock
// to ensure only a single write transaction can be active at the same
// time. This lock will not be released until the transaction is
// closed (via Rollback or Commit).
if writable {
db.writeLock.Lock()
}
// Whenever a new transaction is started, grab a read lock against the
// database to ensure Close will wait for the transaction to finish.
// This lock will not be released until the transaction is closed (via
// Rollback or Commit).
db.closeLock.RLock()
if db.closed {
db.closeLock.RUnlock()
if writable {
db.writeLock.Unlock()
}
return nil, makeDbErr(database.ErrDbNotOpen, errDbNotOpenStr,
nil)
}
// Grab a snapshot of the database cache (which in turn also handles the
// underlying database).
snapshot, err := db.cache.Snapshot()
if err != nil {
db.closeLock.RUnlock()
if writable {
db.writeLock.Unlock()
}
return nil, err
}
// The metadata and block index buckets are internal-only buckets, so
// they have defined IDs.
tx := &transaction{
writable: writable,
db: db,
snapshot: snapshot,
pendingKeys: treap.NewMutable(),
pendingRemove: treap.NewMutable(),
}
tx.metaBucket = &bucket{tx: tx, id: metadataBucketID}
tx.blockIdxBucket = &bucket{tx: tx, id: blockIdxBucketID}
return tx, nil
} | [
"func",
"(",
"db",
"*",
"db",
")",
"begin",
"(",
"writable",
"bool",
")",
"(",
"*",
"transaction",
",",
"error",
")",
"{",
"// Whenever a new writable transaction is started, grab the write lock",
"// to ensure only a single write transaction can be active at the same",
"// time. This lock will not be released until the transaction is",
"// closed (via Rollback or Commit).",
"if",
"writable",
"{",
"db",
".",
"writeLock",
".",
"Lock",
"(",
")",
"\n",
"}",
"\n\n",
"// Whenever a new transaction is started, grab a read lock against the",
"// database to ensure Close will wait for the transaction to finish.",
"// This lock will not be released until the transaction is closed (via",
"// Rollback or Commit).",
"db",
".",
"closeLock",
".",
"RLock",
"(",
")",
"\n",
"if",
"db",
".",
"closed",
"{",
"db",
".",
"closeLock",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"writable",
"{",
"db",
".",
"writeLock",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"makeDbErr",
"(",
"database",
".",
"ErrDbNotOpen",
",",
"errDbNotOpenStr",
",",
"nil",
")",
"\n",
"}",
"\n\n",
"// Grab a snapshot of the database cache (which in turn also handles the",
"// underlying database).",
"snapshot",
",",
"err",
":=",
"db",
".",
"cache",
".",
"Snapshot",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"db",
".",
"closeLock",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"writable",
"{",
"db",
".",
"writeLock",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// The metadata and block index buckets are internal-only buckets, so",
"// they have defined IDs.",
"tx",
":=",
"&",
"transaction",
"{",
"writable",
":",
"writable",
",",
"db",
":",
"db",
",",
"snapshot",
":",
"snapshot",
",",
"pendingKeys",
":",
"treap",
".",
"NewMutable",
"(",
")",
",",
"pendingRemove",
":",
"treap",
".",
"NewMutable",
"(",
")",
",",
"}",
"\n",
"tx",
".",
"metaBucket",
"=",
"&",
"bucket",
"{",
"tx",
":",
"tx",
",",
"id",
":",
"metadataBucketID",
"}",
"\n",
"tx",
".",
"blockIdxBucket",
"=",
"&",
"bucket",
"{",
"tx",
":",
"tx",
",",
"id",
":",
"blockIdxBucketID",
"}",
"\n",
"return",
"tx",
",",
"nil",
"\n",
"}"
] | // begin is the implementation function for the Begin database method. See its
// documentation for more details.
//
// This function is only separate because it returns the internal transaction
// which is used by the managed transaction code while the database method
// returns the interface. | [
"begin",
"is",
"the",
"implementation",
"function",
"for",
"the",
"Begin",
"database",
"method",
".",
"See",
"its",
"documentation",
"for",
"more",
"details",
".",
"This",
"function",
"is",
"only",
"separate",
"because",
"it",
"returns",
"the",
"internal",
"transaction",
"which",
"is",
"used",
"by",
"the",
"managed",
"transaction",
"code",
"while",
"the",
"database",
"method",
"returns",
"the",
"interface",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L1754-L1801 | train |
btcsuite/btcd | database/ffldb/db.go | View | func (db *db) View(fn func(database.Tx) error) error {
// Start a read-only transaction.
tx, err := db.begin(false)
if err != nil {
return err
}
// Since the user-provided function might panic, ensure the transaction
// releases all mutexes and resources. There is no guarantee the caller
// won't use recover and keep going. Thus, the database must still be
// in a usable state on panics due to caller issues.
defer rollbackOnPanic(tx)
tx.managed = true
err = fn(tx)
tx.managed = false
if err != nil {
// The error is ignored here because nothing was written yet
// and regardless of a rollback failure, the tx is closed now
// anyways.
_ = tx.Rollback()
return err
}
return tx.Rollback()
} | go | func (db *db) View(fn func(database.Tx) error) error {
// Start a read-only transaction.
tx, err := db.begin(false)
if err != nil {
return err
}
// Since the user-provided function might panic, ensure the transaction
// releases all mutexes and resources. There is no guarantee the caller
// won't use recover and keep going. Thus, the database must still be
// in a usable state on panics due to caller issues.
defer rollbackOnPanic(tx)
tx.managed = true
err = fn(tx)
tx.managed = false
if err != nil {
// The error is ignored here because nothing was written yet
// and regardless of a rollback failure, the tx is closed now
// anyways.
_ = tx.Rollback()
return err
}
return tx.Rollback()
} | [
"func",
"(",
"db",
"*",
"db",
")",
"View",
"(",
"fn",
"func",
"(",
"database",
".",
"Tx",
")",
"error",
")",
"error",
"{",
"// Start a read-only transaction.",
"tx",
",",
"err",
":=",
"db",
".",
"begin",
"(",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Since the user-provided function might panic, ensure the transaction",
"// releases all mutexes and resources. There is no guarantee the caller",
"// won't use recover and keep going. Thus, the database must still be",
"// in a usable state on panics due to caller issues.",
"defer",
"rollbackOnPanic",
"(",
"tx",
")",
"\n\n",
"tx",
".",
"managed",
"=",
"true",
"\n",
"err",
"=",
"fn",
"(",
"tx",
")",
"\n",
"tx",
".",
"managed",
"=",
"false",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// The error is ignored here because nothing was written yet",
"// and regardless of a rollback failure, the tx is closed now",
"// anyways.",
"_",
"=",
"tx",
".",
"Rollback",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"tx",
".",
"Rollback",
"(",
")",
"\n",
"}"
] | // View invokes the passed function in the context of a managed read-only
// transaction with the root bucket for the namespace. Any errors returned from
// the user-supplied function are returned from this function.
//
// This function is part of the database.DB interface implementation. | [
"View",
"invokes",
"the",
"passed",
"function",
"in",
"the",
"context",
"of",
"a",
"managed",
"read",
"-",
"only",
"transaction",
"with",
"the",
"root",
"bucket",
"for",
"the",
"namespace",
".",
"Any",
"errors",
"returned",
"from",
"the",
"user",
"-",
"supplied",
"function",
"are",
"returned",
"from",
"this",
"function",
".",
"This",
"function",
"is",
"part",
"of",
"the",
"database",
".",
"DB",
"interface",
"implementation",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L1840-L1865 | train |
btcsuite/btcd | database/ffldb/db.go | initDB | func initDB(ldb *leveldb.DB) error {
// The starting block file write cursor location is file num 0, offset
// 0.
batch := new(leveldb.Batch)
batch.Put(bucketizedKey(metadataBucketID, writeLocKeyName),
serializeWriteRow(0, 0))
// Create block index bucket and set the current bucket id.
//
// NOTE: Since buckets are virtualized through the use of prefixes,
// there is no need to store the bucket index data for the metadata
// bucket in the database. However, the first bucket ID to use does
// need to account for it to ensure there are no key collisions.
batch.Put(bucketIndexKey(metadataBucketID, blockIdxBucketName),
blockIdxBucketID[:])
batch.Put(curBucketIDKeyName, blockIdxBucketID[:])
// Write everything as a single batch.
if err := ldb.Write(batch, nil); err != nil {
str := fmt.Sprintf("failed to initialize metadata database: %v",
err)
return convertErr(str, err)
}
return nil
} | go | func initDB(ldb *leveldb.DB) error {
// The starting block file write cursor location is file num 0, offset
// 0.
batch := new(leveldb.Batch)
batch.Put(bucketizedKey(metadataBucketID, writeLocKeyName),
serializeWriteRow(0, 0))
// Create block index bucket and set the current bucket id.
//
// NOTE: Since buckets are virtualized through the use of prefixes,
// there is no need to store the bucket index data for the metadata
// bucket in the database. However, the first bucket ID to use does
// need to account for it to ensure there are no key collisions.
batch.Put(bucketIndexKey(metadataBucketID, blockIdxBucketName),
blockIdxBucketID[:])
batch.Put(curBucketIDKeyName, blockIdxBucketID[:])
// Write everything as a single batch.
if err := ldb.Write(batch, nil); err != nil {
str := fmt.Sprintf("failed to initialize metadata database: %v",
err)
return convertErr(str, err)
}
return nil
} | [
"func",
"initDB",
"(",
"ldb",
"*",
"leveldb",
".",
"DB",
")",
"error",
"{",
"// The starting block file write cursor location is file num 0, offset",
"// 0.",
"batch",
":=",
"new",
"(",
"leveldb",
".",
"Batch",
")",
"\n",
"batch",
".",
"Put",
"(",
"bucketizedKey",
"(",
"metadataBucketID",
",",
"writeLocKeyName",
")",
",",
"serializeWriteRow",
"(",
"0",
",",
"0",
")",
")",
"\n\n",
"// Create block index bucket and set the current bucket id.",
"//",
"// NOTE: Since buckets are virtualized through the use of prefixes,",
"// there is no need to store the bucket index data for the metadata",
"// bucket in the database. However, the first bucket ID to use does",
"// need to account for it to ensure there are no key collisions.",
"batch",
".",
"Put",
"(",
"bucketIndexKey",
"(",
"metadataBucketID",
",",
"blockIdxBucketName",
")",
",",
"blockIdxBucketID",
"[",
":",
"]",
")",
"\n",
"batch",
".",
"Put",
"(",
"curBucketIDKeyName",
",",
"blockIdxBucketID",
"[",
":",
"]",
")",
"\n\n",
"// Write everything as a single batch.",
"if",
"err",
":=",
"ldb",
".",
"Write",
"(",
"batch",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"convertErr",
"(",
"str",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // initDB creates the initial buckets and values used by the package. This is
// mainly in a separate function for testing purposes. | [
"initDB",
"creates",
"the",
"initial",
"buckets",
"and",
"values",
"used",
"by",
"the",
"package",
".",
"This",
"is",
"mainly",
"in",
"a",
"separate",
"function",
"for",
"testing",
"purposes",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L1956-L1981 | train |
btcsuite/btcd | database/ffldb/db.go | openDB | func openDB(dbPath string, network wire.BitcoinNet, create bool) (database.DB, error) {
// Error if the database doesn't exist and the create flag is not set.
metadataDbPath := filepath.Join(dbPath, metadataDbName)
dbExists := fileExists(metadataDbPath)
if !create && !dbExists {
str := fmt.Sprintf("database %q does not exist", metadataDbPath)
return nil, makeDbErr(database.ErrDbDoesNotExist, str, nil)
}
// Ensure the full path to the database exists.
if !dbExists {
// The error can be ignored here since the call to
// leveldb.OpenFile will fail if the directory couldn't be
// created.
_ = os.MkdirAll(dbPath, 0700)
}
// Open the metadata database (will create it if needed).
opts := opt.Options{
ErrorIfExist: create,
Strict: opt.DefaultStrict,
Compression: opt.NoCompression,
Filter: filter.NewBloomFilter(10),
}
ldb, err := leveldb.OpenFile(metadataDbPath, &opts)
if err != nil {
return nil, convertErr(err.Error(), err)
}
// Create the block store which includes scanning the existing flat
// block files to find what the current write cursor position is
// according to the data that is actually on disk. Also create the
// database cache which wraps the underlying leveldb database to provide
// write caching.
store := newBlockStore(dbPath, network)
cache := newDbCache(ldb, store, defaultCacheSize, defaultFlushSecs)
pdb := &db{store: store, cache: cache}
// Perform any reconciliation needed between the block and metadata as
// well as database initialization, if needed.
return reconcileDB(pdb, create)
} | go | func openDB(dbPath string, network wire.BitcoinNet, create bool) (database.DB, error) {
// Error if the database doesn't exist and the create flag is not set.
metadataDbPath := filepath.Join(dbPath, metadataDbName)
dbExists := fileExists(metadataDbPath)
if !create && !dbExists {
str := fmt.Sprintf("database %q does not exist", metadataDbPath)
return nil, makeDbErr(database.ErrDbDoesNotExist, str, nil)
}
// Ensure the full path to the database exists.
if !dbExists {
// The error can be ignored here since the call to
// leveldb.OpenFile will fail if the directory couldn't be
// created.
_ = os.MkdirAll(dbPath, 0700)
}
// Open the metadata database (will create it if needed).
opts := opt.Options{
ErrorIfExist: create,
Strict: opt.DefaultStrict,
Compression: opt.NoCompression,
Filter: filter.NewBloomFilter(10),
}
ldb, err := leveldb.OpenFile(metadataDbPath, &opts)
if err != nil {
return nil, convertErr(err.Error(), err)
}
// Create the block store which includes scanning the existing flat
// block files to find what the current write cursor position is
// according to the data that is actually on disk. Also create the
// database cache which wraps the underlying leveldb database to provide
// write caching.
store := newBlockStore(dbPath, network)
cache := newDbCache(ldb, store, defaultCacheSize, defaultFlushSecs)
pdb := &db{store: store, cache: cache}
// Perform any reconciliation needed between the block and metadata as
// well as database initialization, if needed.
return reconcileDB(pdb, create)
} | [
"func",
"openDB",
"(",
"dbPath",
"string",
",",
"network",
"wire",
".",
"BitcoinNet",
",",
"create",
"bool",
")",
"(",
"database",
".",
"DB",
",",
"error",
")",
"{",
"// Error if the database doesn't exist and the create flag is not set.",
"metadataDbPath",
":=",
"filepath",
".",
"Join",
"(",
"dbPath",
",",
"metadataDbName",
")",
"\n",
"dbExists",
":=",
"fileExists",
"(",
"metadataDbPath",
")",
"\n",
"if",
"!",
"create",
"&&",
"!",
"dbExists",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"metadataDbPath",
")",
"\n",
"return",
"nil",
",",
"makeDbErr",
"(",
"database",
".",
"ErrDbDoesNotExist",
",",
"str",
",",
"nil",
")",
"\n",
"}",
"\n\n",
"// Ensure the full path to the database exists.",
"if",
"!",
"dbExists",
"{",
"// The error can be ignored here since the call to",
"// leveldb.OpenFile will fail if the directory couldn't be",
"// created.",
"_",
"=",
"os",
".",
"MkdirAll",
"(",
"dbPath",
",",
"0700",
")",
"\n",
"}",
"\n\n",
"// Open the metadata database (will create it if needed).",
"opts",
":=",
"opt",
".",
"Options",
"{",
"ErrorIfExist",
":",
"create",
",",
"Strict",
":",
"opt",
".",
"DefaultStrict",
",",
"Compression",
":",
"opt",
".",
"NoCompression",
",",
"Filter",
":",
"filter",
".",
"NewBloomFilter",
"(",
"10",
")",
",",
"}",
"\n",
"ldb",
",",
"err",
":=",
"leveldb",
".",
"OpenFile",
"(",
"metadataDbPath",
",",
"&",
"opts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"convertErr",
"(",
"err",
".",
"Error",
"(",
")",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Create the block store which includes scanning the existing flat",
"// block files to find what the current write cursor position is",
"// according to the data that is actually on disk. Also create the",
"// database cache which wraps the underlying leveldb database to provide",
"// write caching.",
"store",
":=",
"newBlockStore",
"(",
"dbPath",
",",
"network",
")",
"\n",
"cache",
":=",
"newDbCache",
"(",
"ldb",
",",
"store",
",",
"defaultCacheSize",
",",
"defaultFlushSecs",
")",
"\n",
"pdb",
":=",
"&",
"db",
"{",
"store",
":",
"store",
",",
"cache",
":",
"cache",
"}",
"\n\n",
"// Perform any reconciliation needed between the block and metadata as",
"// well as database initialization, if needed.",
"return",
"reconcileDB",
"(",
"pdb",
",",
"create",
")",
"\n",
"}"
] | // openDB opens the database at the provided path. database.ErrDbDoesNotExist
// is returned if the database doesn't exist and the create flag is not set. | [
"openDB",
"opens",
"the",
"database",
"at",
"the",
"provided",
"path",
".",
"database",
".",
"ErrDbDoesNotExist",
"is",
"returned",
"if",
"the",
"database",
"doesn",
"t",
"exist",
"and",
"the",
"create",
"flag",
"is",
"not",
"set",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/db.go#L1985-L2026 | train |
btcsuite/btcd | wire/msggetcfheaders.go | NewMsgGetCFHeaders | func NewMsgGetCFHeaders(filterType FilterType, startHeight uint32,
stopHash *chainhash.Hash) *MsgGetCFHeaders {
return &MsgGetCFHeaders{
FilterType: filterType,
StartHeight: startHeight,
StopHash: *stopHash,
}
} | go | func NewMsgGetCFHeaders(filterType FilterType, startHeight uint32,
stopHash *chainhash.Hash) *MsgGetCFHeaders {
return &MsgGetCFHeaders{
FilterType: filterType,
StartHeight: startHeight,
StopHash: *stopHash,
}
} | [
"func",
"NewMsgGetCFHeaders",
"(",
"filterType",
"FilterType",
",",
"startHeight",
"uint32",
",",
"stopHash",
"*",
"chainhash",
".",
"Hash",
")",
"*",
"MsgGetCFHeaders",
"{",
"return",
"&",
"MsgGetCFHeaders",
"{",
"FilterType",
":",
"filterType",
",",
"StartHeight",
":",
"startHeight",
",",
"StopHash",
":",
"*",
"stopHash",
",",
"}",
"\n",
"}"
] | // NewMsgGetCFHeaders returns a new bitcoin getcfheader message that conforms to
// the Message interface using the passed parameters and defaults for the
// remaining fields. | [
"NewMsgGetCFHeaders",
"returns",
"a",
"new",
"bitcoin",
"getcfheader",
"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/msggetcfheaders.go#L70-L77 | train |
btcsuite/btcd | database/error.go | makeError | func makeError(c ErrorCode, desc string, err error) Error {
return Error{ErrorCode: c, Description: desc, Err: err}
} | go | func makeError(c ErrorCode, desc string, err error) Error {
return Error{ErrorCode: c, Description: desc, Err: err}
} | [
"func",
"makeError",
"(",
"c",
"ErrorCode",
",",
"desc",
"string",
",",
"err",
"error",
")",
"Error",
"{",
"return",
"Error",
"{",
"ErrorCode",
":",
"c",
",",
"Description",
":",
"desc",
",",
"Err",
":",
"err",
"}",
"\n",
"}"
] | // makeError creates an Error given a set of arguments. The error code must
// be one of the error codes provided by this package. | [
"makeError",
"creates",
"an",
"Error",
"given",
"a",
"set",
"of",
"arguments",
".",
"The",
"error",
"code",
"must",
"be",
"one",
"of",
"the",
"error",
"codes",
"provided",
"by",
"this",
"package",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/error.go#L195-L197 | train |
btcsuite/btcd | btcjson/btcdextcmds.go | NewNodeCmd | func NewNodeCmd(subCmd NodeSubCmd, target string, connectSubCmd *string) *NodeCmd {
return &NodeCmd{
SubCmd: subCmd,
Target: target,
ConnectSubCmd: connectSubCmd,
}
} | go | func NewNodeCmd(subCmd NodeSubCmd, target string, connectSubCmd *string) *NodeCmd {
return &NodeCmd{
SubCmd: subCmd,
Target: target,
ConnectSubCmd: connectSubCmd,
}
} | [
"func",
"NewNodeCmd",
"(",
"subCmd",
"NodeSubCmd",
",",
"target",
"string",
",",
"connectSubCmd",
"*",
"string",
")",
"*",
"NodeCmd",
"{",
"return",
"&",
"NodeCmd",
"{",
"SubCmd",
":",
"subCmd",
",",
"Target",
":",
"target",
",",
"ConnectSubCmd",
":",
"connectSubCmd",
",",
"}",
"\n",
"}"
] | // NewNodeCmd returns a new instance which can be used to issue a `node`
// JSON-RPC command.
//
// The parameters which are pointers indicate they are optional. Passing nil
// for optional parameters will use the default value. | [
"NewNodeCmd",
"returns",
"a",
"new",
"instance",
"which",
"can",
"be",
"used",
"to",
"issue",
"a",
"node",
"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/btcdextcmds.go#L39-L45 | train |
btcsuite/btcd | mining/policy.go | calcInputValueAge | func calcInputValueAge(tx *wire.MsgTx, utxoView *blockchain.UtxoViewpoint, nextBlockHeight int32) float64 {
var totalInputAge float64
for _, txIn := range tx.TxIn {
// Don't attempt to accumulate the total input age if the
// referenced transaction output doesn't exist.
entry := utxoView.LookupEntry(txIn.PreviousOutPoint)
if entry != nil && !entry.IsSpent() {
// Inputs with dependencies currently in the mempool
// have their block height set to a special constant.
// Their input age should computed as zero since their
// parent hasn't made it into a block yet.
var inputAge int32
originHeight := entry.BlockHeight()
if originHeight == UnminedHeight {
inputAge = 0
} else {
inputAge = nextBlockHeight - originHeight
}
// Sum the input value times age.
inputValue := entry.Amount()
totalInputAge += float64(inputValue * int64(inputAge))
}
}
return totalInputAge
} | go | func calcInputValueAge(tx *wire.MsgTx, utxoView *blockchain.UtxoViewpoint, nextBlockHeight int32) float64 {
var totalInputAge float64
for _, txIn := range tx.TxIn {
// Don't attempt to accumulate the total input age if the
// referenced transaction output doesn't exist.
entry := utxoView.LookupEntry(txIn.PreviousOutPoint)
if entry != nil && !entry.IsSpent() {
// Inputs with dependencies currently in the mempool
// have their block height set to a special constant.
// Their input age should computed as zero since their
// parent hasn't made it into a block yet.
var inputAge int32
originHeight := entry.BlockHeight()
if originHeight == UnminedHeight {
inputAge = 0
} else {
inputAge = nextBlockHeight - originHeight
}
// Sum the input value times age.
inputValue := entry.Amount()
totalInputAge += float64(inputValue * int64(inputAge))
}
}
return totalInputAge
} | [
"func",
"calcInputValueAge",
"(",
"tx",
"*",
"wire",
".",
"MsgTx",
",",
"utxoView",
"*",
"blockchain",
".",
"UtxoViewpoint",
",",
"nextBlockHeight",
"int32",
")",
"float64",
"{",
"var",
"totalInputAge",
"float64",
"\n",
"for",
"_",
",",
"txIn",
":=",
"range",
"tx",
".",
"TxIn",
"{",
"// Don't attempt to accumulate the total input age if the",
"// referenced transaction output doesn't exist.",
"entry",
":=",
"utxoView",
".",
"LookupEntry",
"(",
"txIn",
".",
"PreviousOutPoint",
")",
"\n",
"if",
"entry",
"!=",
"nil",
"&&",
"!",
"entry",
".",
"IsSpent",
"(",
")",
"{",
"// Inputs with dependencies currently in the mempool",
"// have their block height set to a special constant.",
"// Their input age should computed as zero since their",
"// parent hasn't made it into a block yet.",
"var",
"inputAge",
"int32",
"\n",
"originHeight",
":=",
"entry",
".",
"BlockHeight",
"(",
")",
"\n",
"if",
"originHeight",
"==",
"UnminedHeight",
"{",
"inputAge",
"=",
"0",
"\n",
"}",
"else",
"{",
"inputAge",
"=",
"nextBlockHeight",
"-",
"originHeight",
"\n",
"}",
"\n\n",
"// Sum the input value times age.",
"inputValue",
":=",
"entry",
".",
"Amount",
"(",
")",
"\n",
"totalInputAge",
"+=",
"float64",
"(",
"inputValue",
"*",
"int64",
"(",
"inputAge",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"totalInputAge",
"\n",
"}"
] | // calcInputValueAge is a helper function used to calculate the input age of
// a transaction. The input age for a txin is the number of confirmations
// since the referenced txout multiplied by its output value. The total input
// age is the sum of this value for each txin. Any inputs to the transaction
// which are currently in the mempool and hence not mined into a block yet,
// contribute no additional input age to the transaction. | [
"calcInputValueAge",
"is",
"a",
"helper",
"function",
"used",
"to",
"calculate",
"the",
"input",
"age",
"of",
"a",
"transaction",
".",
"The",
"input",
"age",
"for",
"a",
"txin",
"is",
"the",
"number",
"of",
"confirmations",
"since",
"the",
"referenced",
"txout",
"multiplied",
"by",
"its",
"output",
"value",
".",
"The",
"total",
"input",
"age",
"is",
"the",
"sum",
"of",
"this",
"value",
"for",
"each",
"txin",
".",
"Any",
"inputs",
"to",
"the",
"transaction",
"which",
"are",
"currently",
"in",
"the",
"mempool",
"and",
"hence",
"not",
"mined",
"into",
"a",
"block",
"yet",
"contribute",
"no",
"additional",
"input",
"age",
"to",
"the",
"transaction",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/policy.go#L65-L91 | train |
btcsuite/btcd | chaincfg/chainhash/hash.go | String | func (hash Hash) String() string {
for i := 0; i < HashSize/2; i++ {
hash[i], hash[HashSize-1-i] = hash[HashSize-1-i], hash[i]
}
return hex.EncodeToString(hash[:])
} | go | func (hash Hash) String() string {
for i := 0; i < HashSize/2; i++ {
hash[i], hash[HashSize-1-i] = hash[HashSize-1-i], hash[i]
}
return hex.EncodeToString(hash[:])
} | [
"func",
"(",
"hash",
"Hash",
")",
"String",
"(",
")",
"string",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"HashSize",
"/",
"2",
";",
"i",
"++",
"{",
"hash",
"[",
"i",
"]",
",",
"hash",
"[",
"HashSize",
"-",
"1",
"-",
"i",
"]",
"=",
"hash",
"[",
"HashSize",
"-",
"1",
"-",
"i",
"]",
",",
"hash",
"[",
"i",
"]",
"\n",
"}",
"\n",
"return",
"hex",
".",
"EncodeToString",
"(",
"hash",
"[",
":",
"]",
")",
"\n",
"}"
] | // String returns the Hash as the hexadecimal string of the byte-reversed
// hash. | [
"String",
"returns",
"the",
"Hash",
"as",
"the",
"hexadecimal",
"string",
"of",
"the",
"byte",
"-",
"reversed",
"hash",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/chaincfg/chainhash/hash.go#L29-L34 | train |
btcsuite/btcd | chaincfg/chainhash/hash.go | IsEqual | func (hash *Hash) IsEqual(target *Hash) bool {
if hash == nil && target == nil {
return true
}
if hash == nil || target == nil {
return false
}
return *hash == *target
} | go | func (hash *Hash) IsEqual(target *Hash) bool {
if hash == nil && target == nil {
return true
}
if hash == nil || target == nil {
return false
}
return *hash == *target
} | [
"func",
"(",
"hash",
"*",
"Hash",
")",
"IsEqual",
"(",
"target",
"*",
"Hash",
")",
"bool",
"{",
"if",
"hash",
"==",
"nil",
"&&",
"target",
"==",
"nil",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"hash",
"==",
"nil",
"||",
"target",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"*",
"hash",
"==",
"*",
"target",
"\n",
"}"
] | // IsEqual returns true if target is the same as hash. | [
"IsEqual",
"returns",
"true",
"if",
"target",
"is",
"the",
"same",
"as",
"hash",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/chaincfg/chainhash/hash.go#L62-L70 | train |
btcsuite/btcd | chaincfg/chainhash/hash.go | NewHash | func NewHash(newHash []byte) (*Hash, error) {
var sh Hash
err := sh.SetBytes(newHash)
if err != nil {
return nil, err
}
return &sh, err
} | go | func NewHash(newHash []byte) (*Hash, error) {
var sh Hash
err := sh.SetBytes(newHash)
if err != nil {
return nil, err
}
return &sh, err
} | [
"func",
"NewHash",
"(",
"newHash",
"[",
"]",
"byte",
")",
"(",
"*",
"Hash",
",",
"error",
")",
"{",
"var",
"sh",
"Hash",
"\n",
"err",
":=",
"sh",
".",
"SetBytes",
"(",
"newHash",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"sh",
",",
"err",
"\n",
"}"
] | // NewHash returns a new Hash from a byte slice. An error is returned if
// the number of bytes passed in is not HashSize. | [
"NewHash",
"returns",
"a",
"new",
"Hash",
"from",
"a",
"byte",
"slice",
".",
"An",
"error",
"is",
"returned",
"if",
"the",
"number",
"of",
"bytes",
"passed",
"in",
"is",
"not",
"HashSize",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/chaincfg/chainhash/hash.go#L74-L81 | train |
btcsuite/btcd | chaincfg/chainhash/hash.go | NewHashFromStr | func NewHashFromStr(hash string) (*Hash, error) {
ret := new(Hash)
err := Decode(ret, hash)
if err != nil {
return nil, err
}
return ret, nil
} | go | func NewHashFromStr(hash string) (*Hash, error) {
ret := new(Hash)
err := Decode(ret, hash)
if err != nil {
return nil, err
}
return ret, nil
} | [
"func",
"NewHashFromStr",
"(",
"hash",
"string",
")",
"(",
"*",
"Hash",
",",
"error",
")",
"{",
"ret",
":=",
"new",
"(",
"Hash",
")",
"\n",
"err",
":=",
"Decode",
"(",
"ret",
",",
"hash",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"ret",
",",
"nil",
"\n",
"}"
] | // NewHashFromStr creates a Hash from a hash string. The string should be
// the hexadecimal string of a byte-reversed hash, but any missing characters
// result in zero padding at the end of the Hash. | [
"NewHashFromStr",
"creates",
"a",
"Hash",
"from",
"a",
"hash",
"string",
".",
"The",
"string",
"should",
"be",
"the",
"hexadecimal",
"string",
"of",
"a",
"byte",
"-",
"reversed",
"hash",
"but",
"any",
"missing",
"characters",
"result",
"in",
"zero",
"padding",
"at",
"the",
"end",
"of",
"the",
"Hash",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/chaincfg/chainhash/hash.go#L86-L93 | train |
btcsuite/btcd | chaincfg/chainhash/hash.go | Decode | func Decode(dst *Hash, src string) error {
// Return error if hash string is too long.
if len(src) > MaxHashStringSize {
return ErrHashStrSize
}
// Hex decoder expects the hash to be a multiple of two. When not, pad
// with a leading zero.
var srcBytes []byte
if len(src)%2 == 0 {
srcBytes = []byte(src)
} else {
srcBytes = make([]byte, 1+len(src))
srcBytes[0] = '0'
copy(srcBytes[1:], src)
}
// Hex decode the source bytes to a temporary destination.
var reversedHash Hash
_, err := hex.Decode(reversedHash[HashSize-hex.DecodedLen(len(srcBytes)):], srcBytes)
if err != nil {
return err
}
// Reverse copy from the temporary hash to destination. Because the
// temporary was zeroed, the written result will be correctly padded.
for i, b := range reversedHash[:HashSize/2] {
dst[i], dst[HashSize-1-i] = reversedHash[HashSize-1-i], b
}
return nil
} | go | func Decode(dst *Hash, src string) error {
// Return error if hash string is too long.
if len(src) > MaxHashStringSize {
return ErrHashStrSize
}
// Hex decoder expects the hash to be a multiple of two. When not, pad
// with a leading zero.
var srcBytes []byte
if len(src)%2 == 0 {
srcBytes = []byte(src)
} else {
srcBytes = make([]byte, 1+len(src))
srcBytes[0] = '0'
copy(srcBytes[1:], src)
}
// Hex decode the source bytes to a temporary destination.
var reversedHash Hash
_, err := hex.Decode(reversedHash[HashSize-hex.DecodedLen(len(srcBytes)):], srcBytes)
if err != nil {
return err
}
// Reverse copy from the temporary hash to destination. Because the
// temporary was zeroed, the written result will be correctly padded.
for i, b := range reversedHash[:HashSize/2] {
dst[i], dst[HashSize-1-i] = reversedHash[HashSize-1-i], b
}
return nil
} | [
"func",
"Decode",
"(",
"dst",
"*",
"Hash",
",",
"src",
"string",
")",
"error",
"{",
"// Return error if hash string is too long.",
"if",
"len",
"(",
"src",
")",
">",
"MaxHashStringSize",
"{",
"return",
"ErrHashStrSize",
"\n",
"}",
"\n\n",
"// Hex decoder expects the hash to be a multiple of two. When not, pad",
"// with a leading zero.",
"var",
"srcBytes",
"[",
"]",
"byte",
"\n",
"if",
"len",
"(",
"src",
")",
"%",
"2",
"==",
"0",
"{",
"srcBytes",
"=",
"[",
"]",
"byte",
"(",
"src",
")",
"\n",
"}",
"else",
"{",
"srcBytes",
"=",
"make",
"(",
"[",
"]",
"byte",
",",
"1",
"+",
"len",
"(",
"src",
")",
")",
"\n",
"srcBytes",
"[",
"0",
"]",
"=",
"'0'",
"\n",
"copy",
"(",
"srcBytes",
"[",
"1",
":",
"]",
",",
"src",
")",
"\n",
"}",
"\n\n",
"// Hex decode the source bytes to a temporary destination.",
"var",
"reversedHash",
"Hash",
"\n",
"_",
",",
"err",
":=",
"hex",
".",
"Decode",
"(",
"reversedHash",
"[",
"HashSize",
"-",
"hex",
".",
"DecodedLen",
"(",
"len",
"(",
"srcBytes",
")",
")",
":",
"]",
",",
"srcBytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Reverse copy from the temporary hash to destination. Because the",
"// temporary was zeroed, the written result will be correctly padded.",
"for",
"i",
",",
"b",
":=",
"range",
"reversedHash",
"[",
":",
"HashSize",
"/",
"2",
"]",
"{",
"dst",
"[",
"i",
"]",
",",
"dst",
"[",
"HashSize",
"-",
"1",
"-",
"i",
"]",
"=",
"reversedHash",
"[",
"HashSize",
"-",
"1",
"-",
"i",
"]",
",",
"b",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Decode decodes the byte-reversed hexadecimal string encoding of a Hash to a
// destination. | [
"Decode",
"decodes",
"the",
"byte",
"-",
"reversed",
"hexadecimal",
"string",
"encoding",
"of",
"a",
"Hash",
"to",
"a",
"destination",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/chaincfg/chainhash/hash.go#L97-L128 | train |
btcsuite/btcd | rpcclient/notify.go | Copy | func (s *notificationState) Copy() *notificationState {
var stateCopy notificationState
stateCopy.notifyBlocks = s.notifyBlocks
stateCopy.notifyNewTx = s.notifyNewTx
stateCopy.notifyNewTxVerbose = s.notifyNewTxVerbose
stateCopy.notifyReceived = make(map[string]struct{})
for addr := range s.notifyReceived {
stateCopy.notifyReceived[addr] = struct{}{}
}
stateCopy.notifySpent = make(map[btcjson.OutPoint]struct{})
for op := range s.notifySpent {
stateCopy.notifySpent[op] = struct{}{}
}
return &stateCopy
} | go | func (s *notificationState) Copy() *notificationState {
var stateCopy notificationState
stateCopy.notifyBlocks = s.notifyBlocks
stateCopy.notifyNewTx = s.notifyNewTx
stateCopy.notifyNewTxVerbose = s.notifyNewTxVerbose
stateCopy.notifyReceived = make(map[string]struct{})
for addr := range s.notifyReceived {
stateCopy.notifyReceived[addr] = struct{}{}
}
stateCopy.notifySpent = make(map[btcjson.OutPoint]struct{})
for op := range s.notifySpent {
stateCopy.notifySpent[op] = struct{}{}
}
return &stateCopy
} | [
"func",
"(",
"s",
"*",
"notificationState",
")",
"Copy",
"(",
")",
"*",
"notificationState",
"{",
"var",
"stateCopy",
"notificationState",
"\n",
"stateCopy",
".",
"notifyBlocks",
"=",
"s",
".",
"notifyBlocks",
"\n",
"stateCopy",
".",
"notifyNewTx",
"=",
"s",
".",
"notifyNewTx",
"\n",
"stateCopy",
".",
"notifyNewTxVerbose",
"=",
"s",
".",
"notifyNewTxVerbose",
"\n",
"stateCopy",
".",
"notifyReceived",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
"\n",
"for",
"addr",
":=",
"range",
"s",
".",
"notifyReceived",
"{",
"stateCopy",
".",
"notifyReceived",
"[",
"addr",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"stateCopy",
".",
"notifySpent",
"=",
"make",
"(",
"map",
"[",
"btcjson",
".",
"OutPoint",
"]",
"struct",
"{",
"}",
")",
"\n",
"for",
"op",
":=",
"range",
"s",
".",
"notifySpent",
"{",
"stateCopy",
".",
"notifySpent",
"[",
"op",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n\n",
"return",
"&",
"stateCopy",
"\n",
"}"
] | // Copy returns a deep copy of the receiver. | [
"Copy",
"returns",
"a",
"deep",
"copy",
"of",
"the",
"receiver",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/notify.go#L43-L58 | train |
btcsuite/btcd | rpcclient/notify.go | newNotificationState | func newNotificationState() *notificationState {
return ¬ificationState{
notifyReceived: make(map[string]struct{}),
notifySpent: make(map[btcjson.OutPoint]struct{}),
}
} | go | func newNotificationState() *notificationState {
return ¬ificationState{
notifyReceived: make(map[string]struct{}),
notifySpent: make(map[btcjson.OutPoint]struct{}),
}
} | [
"func",
"newNotificationState",
"(",
")",
"*",
"notificationState",
"{",
"return",
"&",
"notificationState",
"{",
"notifyReceived",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
",",
"notifySpent",
":",
"make",
"(",
"map",
"[",
"btcjson",
".",
"OutPoint",
"]",
"struct",
"{",
"}",
")",
",",
"}",
"\n",
"}"
] | // newNotificationState returns a new notification state ready to be populated. | [
"newNotificationState",
"returns",
"a",
"new",
"notification",
"state",
"ready",
"to",
"be",
"populated",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/notify.go#L61-L66 | train |
btcsuite/btcd | rpcclient/notify.go | newNilFutureResult | func newNilFutureResult() chan *response {
responseChan := make(chan *response, 1)
responseChan <- &response{result: nil, err: nil}
return responseChan
} | go | func newNilFutureResult() chan *response {
responseChan := make(chan *response, 1)
responseChan <- &response{result: nil, err: nil}
return responseChan
} | [
"func",
"newNilFutureResult",
"(",
")",
"chan",
"*",
"response",
"{",
"responseChan",
":=",
"make",
"(",
"chan",
"*",
"response",
",",
"1",
")",
"\n",
"responseChan",
"<-",
"&",
"response",
"{",
"result",
":",
"nil",
",",
"err",
":",
"nil",
"}",
"\n",
"return",
"responseChan",
"\n",
"}"
] | // newNilFutureResult returns a new future result channel that already has the
// result waiting on the channel with the reply set to nil. This is useful
// to ignore things such as notifications when the caller didn't specify any
// notification handlers. | [
"newNilFutureResult",
"returns",
"a",
"new",
"future",
"result",
"channel",
"that",
"already",
"has",
"the",
"result",
"waiting",
"on",
"the",
"channel",
"with",
"the",
"reply",
"set",
"to",
"nil",
".",
"This",
"is",
"useful",
"to",
"ignore",
"things",
"such",
"as",
"notifications",
"when",
"the",
"caller",
"didn",
"t",
"specify",
"any",
"notification",
"handlers",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/notify.go#L72-L76 | train |
btcsuite/btcd | rpcclient/notify.go | parseChainNtfnParams | func parseChainNtfnParams(params []json.RawMessage) (*chainhash.Hash,
int32, time.Time, error) {
if len(params) != 3 {
return nil, 0, time.Time{}, wrongNumParams(len(params))
}
// Unmarshal first parameter as a string.
var blockHashStr string
err := json.Unmarshal(params[0], &blockHashStr)
if err != nil {
return nil, 0, time.Time{}, err
}
// Unmarshal second parameter as an integer.
var blockHeight int32
err = json.Unmarshal(params[1], &blockHeight)
if err != nil {
return nil, 0, time.Time{}, err
}
// Unmarshal third parameter as unix time.
var blockTimeUnix int64
err = json.Unmarshal(params[2], &blockTimeUnix)
if err != nil {
return nil, 0, time.Time{}, err
}
// Create hash from block hash string.
blockHash, err := chainhash.NewHashFromStr(blockHashStr)
if err != nil {
return nil, 0, time.Time{}, err
}
// Create time.Time from unix time.
blockTime := time.Unix(blockTimeUnix, 0)
return blockHash, blockHeight, blockTime, nil
} | go | func parseChainNtfnParams(params []json.RawMessage) (*chainhash.Hash,
int32, time.Time, error) {
if len(params) != 3 {
return nil, 0, time.Time{}, wrongNumParams(len(params))
}
// Unmarshal first parameter as a string.
var blockHashStr string
err := json.Unmarshal(params[0], &blockHashStr)
if err != nil {
return nil, 0, time.Time{}, err
}
// Unmarshal second parameter as an integer.
var blockHeight int32
err = json.Unmarshal(params[1], &blockHeight)
if err != nil {
return nil, 0, time.Time{}, err
}
// Unmarshal third parameter as unix time.
var blockTimeUnix int64
err = json.Unmarshal(params[2], &blockTimeUnix)
if err != nil {
return nil, 0, time.Time{}, err
}
// Create hash from block hash string.
blockHash, err := chainhash.NewHashFromStr(blockHashStr)
if err != nil {
return nil, 0, time.Time{}, err
}
// Create time.Time from unix time.
blockTime := time.Unix(blockTimeUnix, 0)
return blockHash, blockHeight, blockTime, nil
} | [
"func",
"parseChainNtfnParams",
"(",
"params",
"[",
"]",
"json",
".",
"RawMessage",
")",
"(",
"*",
"chainhash",
".",
"Hash",
",",
"int32",
",",
"time",
".",
"Time",
",",
"error",
")",
"{",
"if",
"len",
"(",
"params",
")",
"!=",
"3",
"{",
"return",
"nil",
",",
"0",
",",
"time",
".",
"Time",
"{",
"}",
",",
"wrongNumParams",
"(",
"len",
"(",
"params",
")",
")",
"\n",
"}",
"\n\n",
"// Unmarshal first parameter as a string.",
"var",
"blockHashStr",
"string",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"params",
"[",
"0",
"]",
",",
"&",
"blockHashStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"0",
",",
"time",
".",
"Time",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"// Unmarshal second parameter as an integer.",
"var",
"blockHeight",
"int32",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"params",
"[",
"1",
"]",
",",
"&",
"blockHeight",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"0",
",",
"time",
".",
"Time",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"// Unmarshal third parameter as unix time.",
"var",
"blockTimeUnix",
"int64",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"params",
"[",
"2",
"]",
",",
"&",
"blockTimeUnix",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"0",
",",
"time",
".",
"Time",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"// Create hash from block hash string.",
"blockHash",
",",
"err",
":=",
"chainhash",
".",
"NewHashFromStr",
"(",
"blockHashStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"0",
",",
"time",
".",
"Time",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"// Create time.Time from unix time.",
"blockTime",
":=",
"time",
".",
"Unix",
"(",
"blockTimeUnix",
",",
"0",
")",
"\n\n",
"return",
"blockHash",
",",
"blockHeight",
",",
"blockTime",
",",
"nil",
"\n",
"}"
] | // parseChainNtfnParams parses out the block hash and height from the parameters
// of blockconnected and blockdisconnected notifications. | [
"parseChainNtfnParams",
"parses",
"out",
"the",
"block",
"hash",
"and",
"height",
"from",
"the",
"parameters",
"of",
"blockconnected",
"and",
"blockdisconnected",
"notifications",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/notify.go#L488-L526 | train |
btcsuite/btcd | rpcclient/notify.go | parseRelevantTxAcceptedParams | func parseRelevantTxAcceptedParams(params []json.RawMessage) (transaction []byte, err error) {
if len(params) < 1 {
return nil, wrongNumParams(len(params))
}
return parseHexParam(params[0])
} | go | func parseRelevantTxAcceptedParams(params []json.RawMessage) (transaction []byte, err error) {
if len(params) < 1 {
return nil, wrongNumParams(len(params))
}
return parseHexParam(params[0])
} | [
"func",
"parseRelevantTxAcceptedParams",
"(",
"params",
"[",
"]",
"json",
".",
"RawMessage",
")",
"(",
"transaction",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"if",
"len",
"(",
"params",
")",
"<",
"1",
"{",
"return",
"nil",
",",
"wrongNumParams",
"(",
"len",
"(",
"params",
")",
")",
"\n",
"}",
"\n\n",
"return",
"parseHexParam",
"(",
"params",
"[",
"0",
"]",
")",
"\n",
"}"
] | // parseRelevantTxAcceptedParams parses out the parameter included in a
// relevanttxaccepted notification. | [
"parseRelevantTxAcceptedParams",
"parses",
"out",
"the",
"parameter",
"included",
"in",
"a",
"relevanttxaccepted",
"notification",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/notify.go#L629-L635 | train |
btcsuite/btcd | rpcclient/notify.go | parseChainTxNtfnParams | func parseChainTxNtfnParams(params []json.RawMessage) (*btcutil.Tx,
*btcjson.BlockDetails, error) {
if len(params) == 0 || len(params) > 2 {
return nil, nil, wrongNumParams(len(params))
}
// Unmarshal first parameter as a string.
var txHex string
err := json.Unmarshal(params[0], &txHex)
if err != nil {
return nil, nil, err
}
// If present, unmarshal second optional parameter as the block details
// JSON object.
var block *btcjson.BlockDetails
if len(params) > 1 {
err = json.Unmarshal(params[1], &block)
if err != nil {
return nil, nil, err
}
}
// Hex decode and deserialize the transaction.
serializedTx, err := hex.DecodeString(txHex)
if err != nil {
return nil, nil, err
}
var msgTx wire.MsgTx
err = msgTx.Deserialize(bytes.NewReader(serializedTx))
if err != nil {
return nil, nil, err
}
// TODO: Change recvtx and redeemingtx callback signatures to use
// nicer types for details about the block (block hash as a
// chainhash.Hash, block time as a time.Time, etc.).
return btcutil.NewTx(&msgTx), block, nil
} | go | func parseChainTxNtfnParams(params []json.RawMessage) (*btcutil.Tx,
*btcjson.BlockDetails, error) {
if len(params) == 0 || len(params) > 2 {
return nil, nil, wrongNumParams(len(params))
}
// Unmarshal first parameter as a string.
var txHex string
err := json.Unmarshal(params[0], &txHex)
if err != nil {
return nil, nil, err
}
// If present, unmarshal second optional parameter as the block details
// JSON object.
var block *btcjson.BlockDetails
if len(params) > 1 {
err = json.Unmarshal(params[1], &block)
if err != nil {
return nil, nil, err
}
}
// Hex decode and deserialize the transaction.
serializedTx, err := hex.DecodeString(txHex)
if err != nil {
return nil, nil, err
}
var msgTx wire.MsgTx
err = msgTx.Deserialize(bytes.NewReader(serializedTx))
if err != nil {
return nil, nil, err
}
// TODO: Change recvtx and redeemingtx callback signatures to use
// nicer types for details about the block (block hash as a
// chainhash.Hash, block time as a time.Time, etc.).
return btcutil.NewTx(&msgTx), block, nil
} | [
"func",
"parseChainTxNtfnParams",
"(",
"params",
"[",
"]",
"json",
".",
"RawMessage",
")",
"(",
"*",
"btcutil",
".",
"Tx",
",",
"*",
"btcjson",
".",
"BlockDetails",
",",
"error",
")",
"{",
"if",
"len",
"(",
"params",
")",
"==",
"0",
"||",
"len",
"(",
"params",
")",
">",
"2",
"{",
"return",
"nil",
",",
"nil",
",",
"wrongNumParams",
"(",
"len",
"(",
"params",
")",
")",
"\n",
"}",
"\n\n",
"// Unmarshal first parameter as a string.",
"var",
"txHex",
"string",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"params",
"[",
"0",
"]",
",",
"&",
"txHex",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// If present, unmarshal second optional parameter as the block details",
"// JSON object.",
"var",
"block",
"*",
"btcjson",
".",
"BlockDetails",
"\n",
"if",
"len",
"(",
"params",
")",
">",
"1",
"{",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"params",
"[",
"1",
"]",
",",
"&",
"block",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Hex decode and deserialize the transaction.",
"serializedTx",
",",
"err",
":=",
"hex",
".",
"DecodeString",
"(",
"txHex",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"var",
"msgTx",
"wire",
".",
"MsgTx",
"\n",
"err",
"=",
"msgTx",
".",
"Deserialize",
"(",
"bytes",
".",
"NewReader",
"(",
"serializedTx",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// TODO: Change recvtx and redeemingtx callback signatures to use",
"// nicer types for details about the block (block hash as a",
"// chainhash.Hash, block time as a time.Time, etc.).",
"return",
"btcutil",
".",
"NewTx",
"(",
"&",
"msgTx",
")",
",",
"block",
",",
"nil",
"\n",
"}"
] | // parseChainTxNtfnParams parses out the transaction and optional details about
// the block it's mined in from the parameters of recvtx and redeemingtx
// notifications. | [
"parseChainTxNtfnParams",
"parses",
"out",
"the",
"transaction",
"and",
"optional",
"details",
"about",
"the",
"block",
"it",
"s",
"mined",
"in",
"from",
"the",
"parameters",
"of",
"recvtx",
"and",
"redeemingtx",
"notifications",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/notify.go#L640-L679 | train |
btcsuite/btcd | rpcclient/notify.go | parseRescanProgressParams | func parseRescanProgressParams(params []json.RawMessage) (*chainhash.Hash, int32, time.Time, error) {
if len(params) != 3 {
return nil, 0, time.Time{}, wrongNumParams(len(params))
}
// Unmarshal first parameter as an string.
var hashStr string
err := json.Unmarshal(params[0], &hashStr)
if err != nil {
return nil, 0, time.Time{}, err
}
// Unmarshal second parameter as an integer.
var height int32
err = json.Unmarshal(params[1], &height)
if err != nil {
return nil, 0, time.Time{}, err
}
// Unmarshal third parameter as an integer.
var blkTime int64
err = json.Unmarshal(params[2], &blkTime)
if err != nil {
return nil, 0, time.Time{}, err
}
// Decode string encoding of block hash.
hash, err := chainhash.NewHashFromStr(hashStr)
if err != nil {
return nil, 0, time.Time{}, err
}
return hash, height, time.Unix(blkTime, 0), nil
} | go | func parseRescanProgressParams(params []json.RawMessage) (*chainhash.Hash, int32, time.Time, error) {
if len(params) != 3 {
return nil, 0, time.Time{}, wrongNumParams(len(params))
}
// Unmarshal first parameter as an string.
var hashStr string
err := json.Unmarshal(params[0], &hashStr)
if err != nil {
return nil, 0, time.Time{}, err
}
// Unmarshal second parameter as an integer.
var height int32
err = json.Unmarshal(params[1], &height)
if err != nil {
return nil, 0, time.Time{}, err
}
// Unmarshal third parameter as an integer.
var blkTime int64
err = json.Unmarshal(params[2], &blkTime)
if err != nil {
return nil, 0, time.Time{}, err
}
// Decode string encoding of block hash.
hash, err := chainhash.NewHashFromStr(hashStr)
if err != nil {
return nil, 0, time.Time{}, err
}
return hash, height, time.Unix(blkTime, 0), nil
} | [
"func",
"parseRescanProgressParams",
"(",
"params",
"[",
"]",
"json",
".",
"RawMessage",
")",
"(",
"*",
"chainhash",
".",
"Hash",
",",
"int32",
",",
"time",
".",
"Time",
",",
"error",
")",
"{",
"if",
"len",
"(",
"params",
")",
"!=",
"3",
"{",
"return",
"nil",
",",
"0",
",",
"time",
".",
"Time",
"{",
"}",
",",
"wrongNumParams",
"(",
"len",
"(",
"params",
")",
")",
"\n",
"}",
"\n\n",
"// Unmarshal first parameter as an string.",
"var",
"hashStr",
"string",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"params",
"[",
"0",
"]",
",",
"&",
"hashStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"0",
",",
"time",
".",
"Time",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"// Unmarshal second parameter as an integer.",
"var",
"height",
"int32",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"params",
"[",
"1",
"]",
",",
"&",
"height",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"0",
",",
"time",
".",
"Time",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"// Unmarshal third parameter as an integer.",
"var",
"blkTime",
"int64",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"params",
"[",
"2",
"]",
",",
"&",
"blkTime",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"0",
",",
"time",
".",
"Time",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"// Decode string encoding of block hash.",
"hash",
",",
"err",
":=",
"chainhash",
".",
"NewHashFromStr",
"(",
"hashStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"0",
",",
"time",
".",
"Time",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"hash",
",",
"height",
",",
"time",
".",
"Unix",
"(",
"blkTime",
",",
"0",
")",
",",
"nil",
"\n",
"}"
] | // parseRescanProgressParams parses out the height of the last rescanned block
// from the parameters of rescanfinished and rescanprogress notifications. | [
"parseRescanProgressParams",
"parses",
"out",
"the",
"height",
"of",
"the",
"last",
"rescanned",
"block",
"from",
"the",
"parameters",
"of",
"rescanfinished",
"and",
"rescanprogress",
"notifications",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/notify.go#L683-L716 | train |
btcsuite/btcd | rpcclient/notify.go | parseTxAcceptedNtfnParams | func parseTxAcceptedNtfnParams(params []json.RawMessage) (*chainhash.Hash,
btcutil.Amount, error) {
if len(params) != 2 {
return nil, 0, wrongNumParams(len(params))
}
// Unmarshal first parameter as a string.
var txHashStr string
err := json.Unmarshal(params[0], &txHashStr)
if err != nil {
return nil, 0, err
}
// Unmarshal second parameter as a floating point number.
var famt float64
err = json.Unmarshal(params[1], &famt)
if err != nil {
return nil, 0, err
}
// Bounds check amount.
amt, err := btcutil.NewAmount(famt)
if err != nil {
return nil, 0, err
}
// Decode string encoding of transaction sha.
txHash, err := chainhash.NewHashFromStr(txHashStr)
if err != nil {
return nil, 0, err
}
return txHash, amt, nil
} | go | func parseTxAcceptedNtfnParams(params []json.RawMessage) (*chainhash.Hash,
btcutil.Amount, error) {
if len(params) != 2 {
return nil, 0, wrongNumParams(len(params))
}
// Unmarshal first parameter as a string.
var txHashStr string
err := json.Unmarshal(params[0], &txHashStr)
if err != nil {
return nil, 0, err
}
// Unmarshal second parameter as a floating point number.
var famt float64
err = json.Unmarshal(params[1], &famt)
if err != nil {
return nil, 0, err
}
// Bounds check amount.
amt, err := btcutil.NewAmount(famt)
if err != nil {
return nil, 0, err
}
// Decode string encoding of transaction sha.
txHash, err := chainhash.NewHashFromStr(txHashStr)
if err != nil {
return nil, 0, err
}
return txHash, amt, nil
} | [
"func",
"parseTxAcceptedNtfnParams",
"(",
"params",
"[",
"]",
"json",
".",
"RawMessage",
")",
"(",
"*",
"chainhash",
".",
"Hash",
",",
"btcutil",
".",
"Amount",
",",
"error",
")",
"{",
"if",
"len",
"(",
"params",
")",
"!=",
"2",
"{",
"return",
"nil",
",",
"0",
",",
"wrongNumParams",
"(",
"len",
"(",
"params",
")",
")",
"\n",
"}",
"\n\n",
"// Unmarshal first parameter as a string.",
"var",
"txHashStr",
"string",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"params",
"[",
"0",
"]",
",",
"&",
"txHashStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"// Unmarshal second parameter as a floating point number.",
"var",
"famt",
"float64",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"params",
"[",
"1",
"]",
",",
"&",
"famt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"// Bounds check amount.",
"amt",
",",
"err",
":=",
"btcutil",
".",
"NewAmount",
"(",
"famt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"// Decode string encoding of transaction sha.",
"txHash",
",",
"err",
":=",
"chainhash",
".",
"NewHashFromStr",
"(",
"txHashStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"txHash",
",",
"amt",
",",
"nil",
"\n",
"}"
] | // parseTxAcceptedNtfnParams parses out the transaction hash and total amount
// from the parameters of a txaccepted notification. | [
"parseTxAcceptedNtfnParams",
"parses",
"out",
"the",
"transaction",
"hash",
"and",
"total",
"amount",
"from",
"the",
"parameters",
"of",
"a",
"txaccepted",
"notification",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/notify.go#L720-L754 | train |
btcsuite/btcd | rpcclient/notify.go | parseTxAcceptedVerboseNtfnParams | func parseTxAcceptedVerboseNtfnParams(params []json.RawMessage) (*btcjson.TxRawResult,
error) {
if len(params) != 1 {
return nil, wrongNumParams(len(params))
}
// Unmarshal first parameter as a raw transaction result object.
var rawTx btcjson.TxRawResult
err := json.Unmarshal(params[0], &rawTx)
if err != nil {
return nil, err
}
// TODO: change txacceptedverbose notification callbacks to use nicer
// types for all details about the transaction (i.e. decoding hashes
// from their string encoding).
return &rawTx, nil
} | go | func parseTxAcceptedVerboseNtfnParams(params []json.RawMessage) (*btcjson.TxRawResult,
error) {
if len(params) != 1 {
return nil, wrongNumParams(len(params))
}
// Unmarshal first parameter as a raw transaction result object.
var rawTx btcjson.TxRawResult
err := json.Unmarshal(params[0], &rawTx)
if err != nil {
return nil, err
}
// TODO: change txacceptedverbose notification callbacks to use nicer
// types for all details about the transaction (i.e. decoding hashes
// from their string encoding).
return &rawTx, nil
} | [
"func",
"parseTxAcceptedVerboseNtfnParams",
"(",
"params",
"[",
"]",
"json",
".",
"RawMessage",
")",
"(",
"*",
"btcjson",
".",
"TxRawResult",
",",
"error",
")",
"{",
"if",
"len",
"(",
"params",
")",
"!=",
"1",
"{",
"return",
"nil",
",",
"wrongNumParams",
"(",
"len",
"(",
"params",
")",
")",
"\n",
"}",
"\n\n",
"// Unmarshal first parameter as a raw transaction result object.",
"var",
"rawTx",
"btcjson",
".",
"TxRawResult",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"params",
"[",
"0",
"]",
",",
"&",
"rawTx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// TODO: change txacceptedverbose notification callbacks to use nicer",
"// types for all details about the transaction (i.e. decoding hashes",
"// from their string encoding).",
"return",
"&",
"rawTx",
",",
"nil",
"\n",
"}"
] | // parseTxAcceptedVerboseNtfnParams parses out details about a raw transaction
// from the parameters of a txacceptedverbose notification. | [
"parseTxAcceptedVerboseNtfnParams",
"parses",
"out",
"details",
"about",
"a",
"raw",
"transaction",
"from",
"the",
"parameters",
"of",
"a",
"txacceptedverbose",
"notification",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/notify.go#L758-L776 | train |
btcsuite/btcd | rpcclient/notify.go | parseBtcdConnectedNtfnParams | func parseBtcdConnectedNtfnParams(params []json.RawMessage) (bool, error) {
if len(params) != 1 {
return false, wrongNumParams(len(params))
}
// Unmarshal first parameter as a boolean.
var connected bool
err := json.Unmarshal(params[0], &connected)
if err != nil {
return false, err
}
return connected, nil
} | go | func parseBtcdConnectedNtfnParams(params []json.RawMessage) (bool, error) {
if len(params) != 1 {
return false, wrongNumParams(len(params))
}
// Unmarshal first parameter as a boolean.
var connected bool
err := json.Unmarshal(params[0], &connected)
if err != nil {
return false, err
}
return connected, nil
} | [
"func",
"parseBtcdConnectedNtfnParams",
"(",
"params",
"[",
"]",
"json",
".",
"RawMessage",
")",
"(",
"bool",
",",
"error",
")",
"{",
"if",
"len",
"(",
"params",
")",
"!=",
"1",
"{",
"return",
"false",
",",
"wrongNumParams",
"(",
"len",
"(",
"params",
")",
")",
"\n",
"}",
"\n\n",
"// Unmarshal first parameter as a boolean.",
"var",
"connected",
"bool",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"params",
"[",
"0",
"]",
",",
"&",
"connected",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"connected",
",",
"nil",
"\n",
"}"
] | // parseBtcdConnectedNtfnParams parses out the connection status of btcd
// and btcwallet from the parameters of a btcdconnected notification. | [
"parseBtcdConnectedNtfnParams",
"parses",
"out",
"the",
"connection",
"status",
"of",
"btcd",
"and",
"btcwallet",
"from",
"the",
"parameters",
"of",
"a",
"btcdconnected",
"notification",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/notify.go#L780-L793 | train |
btcsuite/btcd | rpcclient/notify.go | parseAccountBalanceNtfnParams | func parseAccountBalanceNtfnParams(params []json.RawMessage) (account string,
balance btcutil.Amount, confirmed bool, err error) {
if len(params) != 3 {
return "", 0, false, wrongNumParams(len(params))
}
// Unmarshal first parameter as a string.
err = json.Unmarshal(params[0], &account)
if err != nil {
return "", 0, false, err
}
// Unmarshal second parameter as a floating point number.
var fbal float64
err = json.Unmarshal(params[1], &fbal)
if err != nil {
return "", 0, false, err
}
// Unmarshal third parameter as a boolean.
err = json.Unmarshal(params[2], &confirmed)
if err != nil {
return "", 0, false, err
}
// Bounds check amount.
bal, err := btcutil.NewAmount(fbal)
if err != nil {
return "", 0, false, err
}
return account, bal, confirmed, nil
} | go | func parseAccountBalanceNtfnParams(params []json.RawMessage) (account string,
balance btcutil.Amount, confirmed bool, err error) {
if len(params) != 3 {
return "", 0, false, wrongNumParams(len(params))
}
// Unmarshal first parameter as a string.
err = json.Unmarshal(params[0], &account)
if err != nil {
return "", 0, false, err
}
// Unmarshal second parameter as a floating point number.
var fbal float64
err = json.Unmarshal(params[1], &fbal)
if err != nil {
return "", 0, false, err
}
// Unmarshal third parameter as a boolean.
err = json.Unmarshal(params[2], &confirmed)
if err != nil {
return "", 0, false, err
}
// Bounds check amount.
bal, err := btcutil.NewAmount(fbal)
if err != nil {
return "", 0, false, err
}
return account, bal, confirmed, nil
} | [
"func",
"parseAccountBalanceNtfnParams",
"(",
"params",
"[",
"]",
"json",
".",
"RawMessage",
")",
"(",
"account",
"string",
",",
"balance",
"btcutil",
".",
"Amount",
",",
"confirmed",
"bool",
",",
"err",
"error",
")",
"{",
"if",
"len",
"(",
"params",
")",
"!=",
"3",
"{",
"return",
"\"",
"\"",
",",
"0",
",",
"false",
",",
"wrongNumParams",
"(",
"len",
"(",
"params",
")",
")",
"\n",
"}",
"\n\n",
"// Unmarshal first parameter as a string.",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"params",
"[",
"0",
"]",
",",
"&",
"account",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"0",
",",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"// Unmarshal second parameter as a floating point number.",
"var",
"fbal",
"float64",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"params",
"[",
"1",
"]",
",",
"&",
"fbal",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"0",
",",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"// Unmarshal third parameter as a boolean.",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"params",
"[",
"2",
"]",
",",
"&",
"confirmed",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"0",
",",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"// Bounds check amount.",
"bal",
",",
"err",
":=",
"btcutil",
".",
"NewAmount",
"(",
"fbal",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"0",
",",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"account",
",",
"bal",
",",
"confirmed",
",",
"nil",
"\n",
"}"
] | // parseAccountBalanceNtfnParams parses out the account name, total balance,
// and whether or not the balance is confirmed or unconfirmed from the
// parameters of an accountbalance notification. | [
"parseAccountBalanceNtfnParams",
"parses",
"out",
"the",
"account",
"name",
"total",
"balance",
"and",
"whether",
"or",
"not",
"the",
"balance",
"is",
"confirmed",
"or",
"unconfirmed",
"from",
"the",
"parameters",
"of",
"an",
"accountbalance",
"notification",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/notify.go#L798-L831 | train |
btcsuite/btcd | rpcclient/notify.go | parseWalletLockStateNtfnParams | func parseWalletLockStateNtfnParams(params []json.RawMessage) (account string,
locked bool, err error) {
if len(params) != 2 {
return "", false, wrongNumParams(len(params))
}
// Unmarshal first parameter as a string.
err = json.Unmarshal(params[0], &account)
if err != nil {
return "", false, err
}
// Unmarshal second parameter as a boolean.
err = json.Unmarshal(params[1], &locked)
if err != nil {
return "", false, err
}
return account, locked, nil
} | go | func parseWalletLockStateNtfnParams(params []json.RawMessage) (account string,
locked bool, err error) {
if len(params) != 2 {
return "", false, wrongNumParams(len(params))
}
// Unmarshal first parameter as a string.
err = json.Unmarshal(params[0], &account)
if err != nil {
return "", false, err
}
// Unmarshal second parameter as a boolean.
err = json.Unmarshal(params[1], &locked)
if err != nil {
return "", false, err
}
return account, locked, nil
} | [
"func",
"parseWalletLockStateNtfnParams",
"(",
"params",
"[",
"]",
"json",
".",
"RawMessage",
")",
"(",
"account",
"string",
",",
"locked",
"bool",
",",
"err",
"error",
")",
"{",
"if",
"len",
"(",
"params",
")",
"!=",
"2",
"{",
"return",
"\"",
"\"",
",",
"false",
",",
"wrongNumParams",
"(",
"len",
"(",
"params",
")",
")",
"\n",
"}",
"\n\n",
"// Unmarshal first parameter as a string.",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"params",
"[",
"0",
"]",
",",
"&",
"account",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"// Unmarshal second parameter as a boolean.",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"params",
"[",
"1",
"]",
",",
"&",
"locked",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"account",
",",
"locked",
",",
"nil",
"\n",
"}"
] | // parseWalletLockStateNtfnParams parses out the account name and locked
// state of an account from the parameters of a walletlockstate notification. | [
"parseWalletLockStateNtfnParams",
"parses",
"out",
"the",
"account",
"name",
"and",
"locked",
"state",
"of",
"an",
"account",
"from",
"the",
"parameters",
"of",
"a",
"walletlockstate",
"notification",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/notify.go#L835-L855 | train |
btcsuite/btcd | rpcclient/notify.go | notifySpentInternal | func (c *Client) notifySpentInternal(outpoints []btcjson.OutPoint) FutureNotifySpentResult {
// Not supported in HTTP POST mode.
if c.config.HTTPPostMode {
return newFutureError(ErrWebsocketsRequired)
}
// Ignore the notification if the client is not interested in
// notifications.
if c.ntfnHandlers == nil {
return newNilFutureResult()
}
cmd := btcjson.NewNotifySpentCmd(outpoints)
return c.sendCmd(cmd)
} | go | func (c *Client) notifySpentInternal(outpoints []btcjson.OutPoint) FutureNotifySpentResult {
// Not supported in HTTP POST mode.
if c.config.HTTPPostMode {
return newFutureError(ErrWebsocketsRequired)
}
// Ignore the notification if the client is not interested in
// notifications.
if c.ntfnHandlers == nil {
return newNilFutureResult()
}
cmd := btcjson.NewNotifySpentCmd(outpoints)
return c.sendCmd(cmd)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"notifySpentInternal",
"(",
"outpoints",
"[",
"]",
"btcjson",
".",
"OutPoint",
")",
"FutureNotifySpentResult",
"{",
"// Not supported in HTTP POST mode.",
"if",
"c",
".",
"config",
".",
"HTTPPostMode",
"{",
"return",
"newFutureError",
"(",
"ErrWebsocketsRequired",
")",
"\n",
"}",
"\n\n",
"// Ignore the notification if the client is not interested in",
"// notifications.",
"if",
"c",
".",
"ntfnHandlers",
"==",
"nil",
"{",
"return",
"newNilFutureResult",
"(",
")",
"\n",
"}",
"\n\n",
"cmd",
":=",
"btcjson",
".",
"NewNotifySpentCmd",
"(",
"outpoints",
")",
"\n",
"return",
"c",
".",
"sendCmd",
"(",
"cmd",
")",
"\n",
"}"
] | // notifySpentInternal is the same as notifySpentAsync except it accepts
// the converted outpoints as a parameter so the client can more efficiently
// recreate the previous notification state on reconnect. | [
"notifySpentInternal",
"is",
"the",
"same",
"as",
"notifySpentAsync",
"except",
"it",
"accepts",
"the",
"converted",
"outpoints",
"as",
"a",
"parameter",
"so",
"the",
"client",
"can",
"more",
"efficiently",
"recreate",
"the",
"previous",
"notification",
"state",
"on",
"reconnect",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/notify.go#L921-L935 | train |
btcsuite/btcd | rpcclient/notify.go | newOutPointFromWire | func newOutPointFromWire(op *wire.OutPoint) btcjson.OutPoint {
return btcjson.OutPoint{
Hash: op.Hash.String(),
Index: op.Index,
}
} | go | func newOutPointFromWire(op *wire.OutPoint) btcjson.OutPoint {
return btcjson.OutPoint{
Hash: op.Hash.String(),
Index: op.Index,
}
} | [
"func",
"newOutPointFromWire",
"(",
"op",
"*",
"wire",
".",
"OutPoint",
")",
"btcjson",
".",
"OutPoint",
"{",
"return",
"btcjson",
".",
"OutPoint",
"{",
"Hash",
":",
"op",
".",
"Hash",
".",
"String",
"(",
")",
",",
"Index",
":",
"op",
".",
"Index",
",",
"}",
"\n",
"}"
] | // newOutPointFromWire constructs the btcjson representation of a transaction
// outpoint from the wire type. | [
"newOutPointFromWire",
"constructs",
"the",
"btcjson",
"representation",
"of",
"a",
"transaction",
"outpoint",
"from",
"the",
"wire",
"type",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/notify.go#L939-L944 | train |
btcsuite/btcd | rpcclient/notify.go | notifyReceivedInternal | func (c *Client) notifyReceivedInternal(addresses []string) FutureNotifyReceivedResult {
// Not supported in HTTP POST mode.
if c.config.HTTPPostMode {
return newFutureError(ErrWebsocketsRequired)
}
// Ignore the notification if the client is not interested in
// notifications.
if c.ntfnHandlers == nil {
return newNilFutureResult()
}
// Convert addresses to strings.
cmd := btcjson.NewNotifyReceivedCmd(addresses)
return c.sendCmd(cmd)
} | go | func (c *Client) notifyReceivedInternal(addresses []string) FutureNotifyReceivedResult {
// Not supported in HTTP POST mode.
if c.config.HTTPPostMode {
return newFutureError(ErrWebsocketsRequired)
}
// Ignore the notification if the client is not interested in
// notifications.
if c.ntfnHandlers == nil {
return newNilFutureResult()
}
// Convert addresses to strings.
cmd := btcjson.NewNotifyReceivedCmd(addresses)
return c.sendCmd(cmd)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"notifyReceivedInternal",
"(",
"addresses",
"[",
"]",
"string",
")",
"FutureNotifyReceivedResult",
"{",
"// Not supported in HTTP POST mode.",
"if",
"c",
".",
"config",
".",
"HTTPPostMode",
"{",
"return",
"newFutureError",
"(",
"ErrWebsocketsRequired",
")",
"\n",
"}",
"\n\n",
"// Ignore the notification if the client is not interested in",
"// notifications.",
"if",
"c",
".",
"ntfnHandlers",
"==",
"nil",
"{",
"return",
"newNilFutureResult",
"(",
")",
"\n",
"}",
"\n\n",
"// Convert addresses to strings.",
"cmd",
":=",
"btcjson",
".",
"NewNotifyReceivedCmd",
"(",
"addresses",
")",
"\n",
"return",
"c",
".",
"sendCmd",
"(",
"cmd",
")",
"\n",
"}"
] | // notifyReceivedInternal is the same as notifyReceivedAsync except it accepts
// the converted addresses as a parameter so the client can more efficiently
// recreate the previous notification state on reconnect. | [
"notifyReceivedInternal",
"is",
"the",
"same",
"as",
"notifyReceivedAsync",
"except",
"it",
"accepts",
"the",
"converted",
"addresses",
"as",
"a",
"parameter",
"so",
"the",
"client",
"can",
"more",
"efficiently",
"recreate",
"the",
"previous",
"notification",
"state",
"on",
"reconnect",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/notify.go#L1056-L1071 | train |
btcsuite/btcd | mempool/policy.go | calcMinRequiredTxRelayFee | func calcMinRequiredTxRelayFee(serializedSize int64, minRelayTxFee btcutil.Amount) int64 {
// Calculate the minimum fee for a transaction to be allowed into the
// mempool and relayed by scaling the base fee (which is the minimum
// free transaction relay fee). minTxRelayFee is in Satoshi/kB so
// multiply by serializedSize (which is in bytes) and divide by 1000 to
// get minimum Satoshis.
minFee := (serializedSize * int64(minRelayTxFee)) / 1000
if minFee == 0 && minRelayTxFee > 0 {
minFee = int64(minRelayTxFee)
}
// Set the minimum fee to the maximum possible value if the calculated
// fee is not in the valid range for monetary amounts.
if minFee < 0 || minFee > btcutil.MaxSatoshi {
minFee = btcutil.MaxSatoshi
}
return minFee
} | go | func calcMinRequiredTxRelayFee(serializedSize int64, minRelayTxFee btcutil.Amount) int64 {
// Calculate the minimum fee for a transaction to be allowed into the
// mempool and relayed by scaling the base fee (which is the minimum
// free transaction relay fee). minTxRelayFee is in Satoshi/kB so
// multiply by serializedSize (which is in bytes) and divide by 1000 to
// get minimum Satoshis.
minFee := (serializedSize * int64(minRelayTxFee)) / 1000
if minFee == 0 && minRelayTxFee > 0 {
minFee = int64(minRelayTxFee)
}
// Set the minimum fee to the maximum possible value if the calculated
// fee is not in the valid range for monetary amounts.
if minFee < 0 || minFee > btcutil.MaxSatoshi {
minFee = btcutil.MaxSatoshi
}
return minFee
} | [
"func",
"calcMinRequiredTxRelayFee",
"(",
"serializedSize",
"int64",
",",
"minRelayTxFee",
"btcutil",
".",
"Amount",
")",
"int64",
"{",
"// Calculate the minimum fee for a transaction to be allowed into the",
"// mempool and relayed by scaling the base fee (which is the minimum",
"// free transaction relay fee). minTxRelayFee is in Satoshi/kB so",
"// multiply by serializedSize (which is in bytes) and divide by 1000 to",
"// get minimum Satoshis.",
"minFee",
":=",
"(",
"serializedSize",
"*",
"int64",
"(",
"minRelayTxFee",
")",
")",
"/",
"1000",
"\n\n",
"if",
"minFee",
"==",
"0",
"&&",
"minRelayTxFee",
">",
"0",
"{",
"minFee",
"=",
"int64",
"(",
"minRelayTxFee",
")",
"\n",
"}",
"\n\n",
"// Set the minimum fee to the maximum possible value if the calculated",
"// fee is not in the valid range for monetary amounts.",
"if",
"minFee",
"<",
"0",
"||",
"minFee",
">",
"btcutil",
".",
"MaxSatoshi",
"{",
"minFee",
"=",
"btcutil",
".",
"MaxSatoshi",
"\n",
"}",
"\n\n",
"return",
"minFee",
"\n",
"}"
] | // calcMinRequiredTxRelayFee returns the minimum transaction fee required for a
// transaction with the passed serialized size to be accepted into the memory
// pool and relayed. | [
"calcMinRequiredTxRelayFee",
"returns",
"the",
"minimum",
"transaction",
"fee",
"required",
"for",
"a",
"transaction",
"with",
"the",
"passed",
"serialized",
"size",
"to",
"be",
"accepted",
"into",
"the",
"memory",
"pool",
"and",
"relayed",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/policy.go#L61-L80 | train |
btcsuite/btcd | mempool/policy.go | checkInputsStandard | func checkInputsStandard(tx *btcutil.Tx, utxoView *blockchain.UtxoViewpoint) error {
// NOTE: The reference implementation also does a coinbase check here,
// but coinbases have already been rejected prior to calling this
// function so no need to recheck.
for i, txIn := range tx.MsgTx().TxIn {
// It is safe to elide existence and index checks here since
// they have already been checked prior to calling this
// function.
entry := utxoView.LookupEntry(txIn.PreviousOutPoint)
originPkScript := entry.PkScript()
switch txscript.GetScriptClass(originPkScript) {
case txscript.ScriptHashTy:
numSigOps := txscript.GetPreciseSigOpCount(
txIn.SignatureScript, originPkScript, true)
if numSigOps > maxStandardP2SHSigOps {
str := fmt.Sprintf("transaction input #%d has "+
"%d signature operations which is more "+
"than the allowed max amount of %d",
i, numSigOps, maxStandardP2SHSigOps)
return txRuleError(wire.RejectNonstandard, str)
}
case txscript.NonStandardTy:
str := fmt.Sprintf("transaction input #%d has a "+
"non-standard script form", i)
return txRuleError(wire.RejectNonstandard, str)
}
}
return nil
} | go | func checkInputsStandard(tx *btcutil.Tx, utxoView *blockchain.UtxoViewpoint) error {
// NOTE: The reference implementation also does a coinbase check here,
// but coinbases have already been rejected prior to calling this
// function so no need to recheck.
for i, txIn := range tx.MsgTx().TxIn {
// It is safe to elide existence and index checks here since
// they have already been checked prior to calling this
// function.
entry := utxoView.LookupEntry(txIn.PreviousOutPoint)
originPkScript := entry.PkScript()
switch txscript.GetScriptClass(originPkScript) {
case txscript.ScriptHashTy:
numSigOps := txscript.GetPreciseSigOpCount(
txIn.SignatureScript, originPkScript, true)
if numSigOps > maxStandardP2SHSigOps {
str := fmt.Sprintf("transaction input #%d has "+
"%d signature operations which is more "+
"than the allowed max amount of %d",
i, numSigOps, maxStandardP2SHSigOps)
return txRuleError(wire.RejectNonstandard, str)
}
case txscript.NonStandardTy:
str := fmt.Sprintf("transaction input #%d has a "+
"non-standard script form", i)
return txRuleError(wire.RejectNonstandard, str)
}
}
return nil
} | [
"func",
"checkInputsStandard",
"(",
"tx",
"*",
"btcutil",
".",
"Tx",
",",
"utxoView",
"*",
"blockchain",
".",
"UtxoViewpoint",
")",
"error",
"{",
"// NOTE: The reference implementation also does a coinbase check here,",
"// but coinbases have already been rejected prior to calling this",
"// function so no need to recheck.",
"for",
"i",
",",
"txIn",
":=",
"range",
"tx",
".",
"MsgTx",
"(",
")",
".",
"TxIn",
"{",
"// It is safe to elide existence and index checks here since",
"// they have already been checked prior to calling this",
"// function.",
"entry",
":=",
"utxoView",
".",
"LookupEntry",
"(",
"txIn",
".",
"PreviousOutPoint",
")",
"\n",
"originPkScript",
":=",
"entry",
".",
"PkScript",
"(",
")",
"\n",
"switch",
"txscript",
".",
"GetScriptClass",
"(",
"originPkScript",
")",
"{",
"case",
"txscript",
".",
"ScriptHashTy",
":",
"numSigOps",
":=",
"txscript",
".",
"GetPreciseSigOpCount",
"(",
"txIn",
".",
"SignatureScript",
",",
"originPkScript",
",",
"true",
")",
"\n",
"if",
"numSigOps",
">",
"maxStandardP2SHSigOps",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"i",
",",
"numSigOps",
",",
"maxStandardP2SHSigOps",
")",
"\n",
"return",
"txRuleError",
"(",
"wire",
".",
"RejectNonstandard",
",",
"str",
")",
"\n",
"}",
"\n\n",
"case",
"txscript",
".",
"NonStandardTy",
":",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"i",
")",
"\n",
"return",
"txRuleError",
"(",
"wire",
".",
"RejectNonstandard",
",",
"str",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // checkInputsStandard performs a series of checks on a transaction's inputs
// to ensure they are "standard". A standard transaction input within the
// context of this function is one whose referenced public key script is of a
// standard form and, for pay-to-script-hash, does not have more than
// maxStandardP2SHSigOps signature operations. However, it should also be noted
// that standard inputs also are those which have a clean stack after execution
// and only contain pushed data in their signature scripts. This function does
// not perform those checks because the script engine already does this more
// accurately and concisely via the txscript.ScriptVerifyCleanStack and
// txscript.ScriptVerifySigPushOnly flags. | [
"checkInputsStandard",
"performs",
"a",
"series",
"of",
"checks",
"on",
"a",
"transaction",
"s",
"inputs",
"to",
"ensure",
"they",
"are",
"standard",
".",
"A",
"standard",
"transaction",
"input",
"within",
"the",
"context",
"of",
"this",
"function",
"is",
"one",
"whose",
"referenced",
"public",
"key",
"script",
"is",
"of",
"a",
"standard",
"form",
"and",
"for",
"pay",
"-",
"to",
"-",
"script",
"-",
"hash",
"does",
"not",
"have",
"more",
"than",
"maxStandardP2SHSigOps",
"signature",
"operations",
".",
"However",
"it",
"should",
"also",
"be",
"noted",
"that",
"standard",
"inputs",
"also",
"are",
"those",
"which",
"have",
"a",
"clean",
"stack",
"after",
"execution",
"and",
"only",
"contain",
"pushed",
"data",
"in",
"their",
"signature",
"scripts",
".",
"This",
"function",
"does",
"not",
"perform",
"those",
"checks",
"because",
"the",
"script",
"engine",
"already",
"does",
"this",
"more",
"accurately",
"and",
"concisely",
"via",
"the",
"txscript",
".",
"ScriptVerifyCleanStack",
"and",
"txscript",
".",
"ScriptVerifySigPushOnly",
"flags",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/policy.go#L92-L123 | train |
btcsuite/btcd | mempool/policy.go | GetTxVirtualSize | func GetTxVirtualSize(tx *btcutil.Tx) int64 {
// vSize := (weight(tx) + 3) / 4
// := (((baseSize * 3) + totalSize) + 3) / 4
// We add 3 here as a way to compute the ceiling of the prior arithmetic
// to 4. The division by 4 creates a discount for wit witness data.
return (blockchain.GetTransactionWeight(tx) + (blockchain.WitnessScaleFactor - 1)) /
blockchain.WitnessScaleFactor
} | go | func GetTxVirtualSize(tx *btcutil.Tx) int64 {
// vSize := (weight(tx) + 3) / 4
// := (((baseSize * 3) + totalSize) + 3) / 4
// We add 3 here as a way to compute the ceiling of the prior arithmetic
// to 4. The division by 4 creates a discount for wit witness data.
return (blockchain.GetTransactionWeight(tx) + (blockchain.WitnessScaleFactor - 1)) /
blockchain.WitnessScaleFactor
} | [
"func",
"GetTxVirtualSize",
"(",
"tx",
"*",
"btcutil",
".",
"Tx",
")",
"int64",
"{",
"// vSize := (weight(tx) + 3) / 4",
"// := (((baseSize * 3) + totalSize) + 3) / 4",
"// We add 3 here as a way to compute the ceiling of the prior arithmetic",
"// to 4. The division by 4 creates a discount for wit witness data.",
"return",
"(",
"blockchain",
".",
"GetTransactionWeight",
"(",
"tx",
")",
"+",
"(",
"blockchain",
".",
"WitnessScaleFactor",
"-",
"1",
")",
")",
"/",
"blockchain",
".",
"WitnessScaleFactor",
"\n",
"}"
] | // GetTxVirtualSize computes the virtual size of a given transaction. A
// transaction's virtual size is based off its weight, creating a discount for
// any witness data it contains, proportional to the current
// blockchain.WitnessScaleFactor value. | [
"GetTxVirtualSize",
"computes",
"the",
"virtual",
"size",
"of",
"a",
"given",
"transaction",
".",
"A",
"transaction",
"s",
"virtual",
"size",
"is",
"based",
"off",
"its",
"weight",
"creating",
"a",
"discount",
"for",
"any",
"witness",
"data",
"it",
"contains",
"proportional",
"to",
"the",
"current",
"blockchain",
".",
"WitnessScaleFactor",
"value",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/policy.go#L375-L382 | train |
btcsuite/btcd | btcjson/walletsvrwsntfns.go | NewAccountBalanceNtfn | func NewAccountBalanceNtfn(account string, balance float64, confirmed bool) *AccountBalanceNtfn {
return &AccountBalanceNtfn{
Account: account,
Balance: balance,
Confirmed: confirmed,
}
} | go | func NewAccountBalanceNtfn(account string, balance float64, confirmed bool) *AccountBalanceNtfn {
return &AccountBalanceNtfn{
Account: account,
Balance: balance,
Confirmed: confirmed,
}
} | [
"func",
"NewAccountBalanceNtfn",
"(",
"account",
"string",
",",
"balance",
"float64",
",",
"confirmed",
"bool",
")",
"*",
"AccountBalanceNtfn",
"{",
"return",
"&",
"AccountBalanceNtfn",
"{",
"Account",
":",
"account",
",",
"Balance",
":",
"balance",
",",
"Confirmed",
":",
"confirmed",
",",
"}",
"\n",
"}"
] | // NewAccountBalanceNtfn returns a new instance which can be used to issue an
// accountbalance JSON-RPC notification. | [
"NewAccountBalanceNtfn",
"returns",
"a",
"new",
"instance",
"which",
"can",
"be",
"used",
"to",
"issue",
"an",
"accountbalance",
"JSON",
"-",
"RPC",
"notification",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/walletsvrwsntfns.go#L37-L43 | train |
btcsuite/btcd | btcjson/walletsvrwsntfns.go | NewNewTxNtfn | func NewNewTxNtfn(account string, details ListTransactionsResult) *NewTxNtfn {
return &NewTxNtfn{
Account: account,
Details: details,
}
} | go | func NewNewTxNtfn(account string, details ListTransactionsResult) *NewTxNtfn {
return &NewTxNtfn{
Account: account,
Details: details,
}
} | [
"func",
"NewNewTxNtfn",
"(",
"account",
"string",
",",
"details",
"ListTransactionsResult",
")",
"*",
"NewTxNtfn",
"{",
"return",
"&",
"NewTxNtfn",
"{",
"Account",
":",
"account",
",",
"Details",
":",
"details",
",",
"}",
"\n",
"}"
] | // NewNewTxNtfn returns a new instance which can be used to issue a newtx
// JSON-RPC notification. | [
"NewNewTxNtfn",
"returns",
"a",
"new",
"instance",
"which",
"can",
"be",
"used",
"to",
"issue",
"a",
"newtx",
"JSON",
"-",
"RPC",
"notification",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/walletsvrwsntfns.go#L79-L84 | train |
btcsuite/btcd | blockchain/indexers/txindex.go | dbRemoveBlockIDIndexEntry | func dbRemoveBlockIDIndexEntry(dbTx database.Tx, hash *chainhash.Hash) error {
// Remove the block hash to ID mapping.
meta := dbTx.Metadata()
hashIndex := meta.Bucket(idByHashIndexBucketName)
serializedID := hashIndex.Get(hash[:])
if serializedID == nil {
return nil
}
if err := hashIndex.Delete(hash[:]); err != nil {
return err
}
// Remove the block ID to hash mapping.
idIndex := meta.Bucket(hashByIDIndexBucketName)
return idIndex.Delete(serializedID)
} | go | func dbRemoveBlockIDIndexEntry(dbTx database.Tx, hash *chainhash.Hash) error {
// Remove the block hash to ID mapping.
meta := dbTx.Metadata()
hashIndex := meta.Bucket(idByHashIndexBucketName)
serializedID := hashIndex.Get(hash[:])
if serializedID == nil {
return nil
}
if err := hashIndex.Delete(hash[:]); err != nil {
return err
}
// Remove the block ID to hash mapping.
idIndex := meta.Bucket(hashByIDIndexBucketName)
return idIndex.Delete(serializedID)
} | [
"func",
"dbRemoveBlockIDIndexEntry",
"(",
"dbTx",
"database",
".",
"Tx",
",",
"hash",
"*",
"chainhash",
".",
"Hash",
")",
"error",
"{",
"// Remove the block hash to ID mapping.",
"meta",
":=",
"dbTx",
".",
"Metadata",
"(",
")",
"\n",
"hashIndex",
":=",
"meta",
".",
"Bucket",
"(",
"idByHashIndexBucketName",
")",
"\n",
"serializedID",
":=",
"hashIndex",
".",
"Get",
"(",
"hash",
"[",
":",
"]",
")",
"\n",
"if",
"serializedID",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
":=",
"hashIndex",
".",
"Delete",
"(",
"hash",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Remove the block ID to hash mapping.",
"idIndex",
":=",
"meta",
".",
"Bucket",
"(",
"hashByIDIndexBucketName",
")",
"\n",
"return",
"idIndex",
".",
"Delete",
"(",
"serializedID",
")",
"\n",
"}"
] | // dbRemoveBlockIDIndexEntry uses an existing database transaction remove index
// entries from the hash to id and id to hash mappings for the provided hash. | [
"dbRemoveBlockIDIndexEntry",
"uses",
"an",
"existing",
"database",
"transaction",
"remove",
"index",
"entries",
"from",
"the",
"hash",
"to",
"id",
"and",
"id",
"to",
"hash",
"mappings",
"for",
"the",
"provided",
"hash",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/txindex.go#L116-L131 | train |
btcsuite/btcd | blockchain/indexers/txindex.go | dbFetchBlockIDByHash | func dbFetchBlockIDByHash(dbTx database.Tx, hash *chainhash.Hash) (uint32, error) {
hashIndex := dbTx.Metadata().Bucket(idByHashIndexBucketName)
serializedID := hashIndex.Get(hash[:])
if serializedID == nil {
return 0, errNoBlockIDEntry
}
return byteOrder.Uint32(serializedID), nil
} | go | func dbFetchBlockIDByHash(dbTx database.Tx, hash *chainhash.Hash) (uint32, error) {
hashIndex := dbTx.Metadata().Bucket(idByHashIndexBucketName)
serializedID := hashIndex.Get(hash[:])
if serializedID == nil {
return 0, errNoBlockIDEntry
}
return byteOrder.Uint32(serializedID), nil
} | [
"func",
"dbFetchBlockIDByHash",
"(",
"dbTx",
"database",
".",
"Tx",
",",
"hash",
"*",
"chainhash",
".",
"Hash",
")",
"(",
"uint32",
",",
"error",
")",
"{",
"hashIndex",
":=",
"dbTx",
".",
"Metadata",
"(",
")",
".",
"Bucket",
"(",
"idByHashIndexBucketName",
")",
"\n",
"serializedID",
":=",
"hashIndex",
".",
"Get",
"(",
"hash",
"[",
":",
"]",
")",
"\n",
"if",
"serializedID",
"==",
"nil",
"{",
"return",
"0",
",",
"errNoBlockIDEntry",
"\n",
"}",
"\n\n",
"return",
"byteOrder",
".",
"Uint32",
"(",
"serializedID",
")",
",",
"nil",
"\n",
"}"
] | // dbFetchBlockIDByHash uses an existing database transaction to retrieve the
// block id for the provided hash from the index. | [
"dbFetchBlockIDByHash",
"uses",
"an",
"existing",
"database",
"transaction",
"to",
"retrieve",
"the",
"block",
"id",
"for",
"the",
"provided",
"hash",
"from",
"the",
"index",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/txindex.go#L135-L143 | train |
btcsuite/btcd | blockchain/indexers/txindex.go | dbFetchBlockHashBySerializedID | func dbFetchBlockHashBySerializedID(dbTx database.Tx, serializedID []byte) (*chainhash.Hash, error) {
idIndex := dbTx.Metadata().Bucket(hashByIDIndexBucketName)
hashBytes := idIndex.Get(serializedID)
if hashBytes == nil {
return nil, errNoBlockIDEntry
}
var hash chainhash.Hash
copy(hash[:], hashBytes)
return &hash, nil
} | go | func dbFetchBlockHashBySerializedID(dbTx database.Tx, serializedID []byte) (*chainhash.Hash, error) {
idIndex := dbTx.Metadata().Bucket(hashByIDIndexBucketName)
hashBytes := idIndex.Get(serializedID)
if hashBytes == nil {
return nil, errNoBlockIDEntry
}
var hash chainhash.Hash
copy(hash[:], hashBytes)
return &hash, nil
} | [
"func",
"dbFetchBlockHashBySerializedID",
"(",
"dbTx",
"database",
".",
"Tx",
",",
"serializedID",
"[",
"]",
"byte",
")",
"(",
"*",
"chainhash",
".",
"Hash",
",",
"error",
")",
"{",
"idIndex",
":=",
"dbTx",
".",
"Metadata",
"(",
")",
".",
"Bucket",
"(",
"hashByIDIndexBucketName",
")",
"\n",
"hashBytes",
":=",
"idIndex",
".",
"Get",
"(",
"serializedID",
")",
"\n",
"if",
"hashBytes",
"==",
"nil",
"{",
"return",
"nil",
",",
"errNoBlockIDEntry",
"\n",
"}",
"\n\n",
"var",
"hash",
"chainhash",
".",
"Hash",
"\n",
"copy",
"(",
"hash",
"[",
":",
"]",
",",
"hashBytes",
")",
"\n",
"return",
"&",
"hash",
",",
"nil",
"\n",
"}"
] | // dbFetchBlockHashBySerializedID uses an existing database transaction to
// retrieve the hash for the provided serialized block id from the index. | [
"dbFetchBlockHashBySerializedID",
"uses",
"an",
"existing",
"database",
"transaction",
"to",
"retrieve",
"the",
"hash",
"for",
"the",
"provided",
"serialized",
"block",
"id",
"from",
"the",
"index",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/txindex.go#L147-L157 | train |
btcsuite/btcd | blockchain/indexers/txindex.go | dbFetchBlockHashByID | func dbFetchBlockHashByID(dbTx database.Tx, id uint32) (*chainhash.Hash, error) {
var serializedID [4]byte
byteOrder.PutUint32(serializedID[:], id)
return dbFetchBlockHashBySerializedID(dbTx, serializedID[:])
} | go | func dbFetchBlockHashByID(dbTx database.Tx, id uint32) (*chainhash.Hash, error) {
var serializedID [4]byte
byteOrder.PutUint32(serializedID[:], id)
return dbFetchBlockHashBySerializedID(dbTx, serializedID[:])
} | [
"func",
"dbFetchBlockHashByID",
"(",
"dbTx",
"database",
".",
"Tx",
",",
"id",
"uint32",
")",
"(",
"*",
"chainhash",
".",
"Hash",
",",
"error",
")",
"{",
"var",
"serializedID",
"[",
"4",
"]",
"byte",
"\n",
"byteOrder",
".",
"PutUint32",
"(",
"serializedID",
"[",
":",
"]",
",",
"id",
")",
"\n",
"return",
"dbFetchBlockHashBySerializedID",
"(",
"dbTx",
",",
"serializedID",
"[",
":",
"]",
")",
"\n",
"}"
] | // dbFetchBlockHashByID uses an existing database transaction to retrieve the
// hash for the provided block id from the index. | [
"dbFetchBlockHashByID",
"uses",
"an",
"existing",
"database",
"transaction",
"to",
"retrieve",
"the",
"hash",
"for",
"the",
"provided",
"block",
"id",
"from",
"the",
"index",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/txindex.go#L161-L165 | train |
btcsuite/btcd | blockchain/indexers/txindex.go | putTxIndexEntry | func putTxIndexEntry(target []byte, blockID uint32, txLoc wire.TxLoc) {
byteOrder.PutUint32(target, blockID)
byteOrder.PutUint32(target[4:], uint32(txLoc.TxStart))
byteOrder.PutUint32(target[8:], uint32(txLoc.TxLen))
} | go | func putTxIndexEntry(target []byte, blockID uint32, txLoc wire.TxLoc) {
byteOrder.PutUint32(target, blockID)
byteOrder.PutUint32(target[4:], uint32(txLoc.TxStart))
byteOrder.PutUint32(target[8:], uint32(txLoc.TxLen))
} | [
"func",
"putTxIndexEntry",
"(",
"target",
"[",
"]",
"byte",
",",
"blockID",
"uint32",
",",
"txLoc",
"wire",
".",
"TxLoc",
")",
"{",
"byteOrder",
".",
"PutUint32",
"(",
"target",
",",
"blockID",
")",
"\n",
"byteOrder",
".",
"PutUint32",
"(",
"target",
"[",
"4",
":",
"]",
",",
"uint32",
"(",
"txLoc",
".",
"TxStart",
")",
")",
"\n",
"byteOrder",
".",
"PutUint32",
"(",
"target",
"[",
"8",
":",
"]",
",",
"uint32",
"(",
"txLoc",
".",
"TxLen",
")",
")",
"\n",
"}"
] | // putTxIndexEntry serializes the provided values according to the format
// described about for a transaction index entry. The target byte slice must
// be at least large enough to handle the number of bytes defined by the
// txEntrySize constant or it will panic. | [
"putTxIndexEntry",
"serializes",
"the",
"provided",
"values",
"according",
"to",
"the",
"format",
"described",
"about",
"for",
"a",
"transaction",
"index",
"entry",
".",
"The",
"target",
"byte",
"slice",
"must",
"be",
"at",
"least",
"large",
"enough",
"to",
"handle",
"the",
"number",
"of",
"bytes",
"defined",
"by",
"the",
"txEntrySize",
"constant",
"or",
"it",
"will",
"panic",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/txindex.go#L171-L175 | train |
btcsuite/btcd | blockchain/indexers/txindex.go | dbPutTxIndexEntry | func dbPutTxIndexEntry(dbTx database.Tx, txHash *chainhash.Hash, serializedData []byte) error {
txIndex := dbTx.Metadata().Bucket(txIndexKey)
return txIndex.Put(txHash[:], serializedData)
} | go | func dbPutTxIndexEntry(dbTx database.Tx, txHash *chainhash.Hash, serializedData []byte) error {
txIndex := dbTx.Metadata().Bucket(txIndexKey)
return txIndex.Put(txHash[:], serializedData)
} | [
"func",
"dbPutTxIndexEntry",
"(",
"dbTx",
"database",
".",
"Tx",
",",
"txHash",
"*",
"chainhash",
".",
"Hash",
",",
"serializedData",
"[",
"]",
"byte",
")",
"error",
"{",
"txIndex",
":=",
"dbTx",
".",
"Metadata",
"(",
")",
".",
"Bucket",
"(",
"txIndexKey",
")",
"\n",
"return",
"txIndex",
".",
"Put",
"(",
"txHash",
"[",
":",
"]",
",",
"serializedData",
")",
"\n",
"}"
] | // dbPutTxIndexEntry uses an existing database transaction to update the
// transaction index given the provided serialized data that is expected to have
// been serialized putTxIndexEntry. | [
"dbPutTxIndexEntry",
"uses",
"an",
"existing",
"database",
"transaction",
"to",
"update",
"the",
"transaction",
"index",
"given",
"the",
"provided",
"serialized",
"data",
"that",
"is",
"expected",
"to",
"have",
"been",
"serialized",
"putTxIndexEntry",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/txindex.go#L180-L183 | train |
btcsuite/btcd | blockchain/indexers/txindex.go | dbFetchTxIndexEntry | func dbFetchTxIndexEntry(dbTx database.Tx, txHash *chainhash.Hash) (*database.BlockRegion, error) {
// Load the record from the database and return now if it doesn't exist.
txIndex := dbTx.Metadata().Bucket(txIndexKey)
serializedData := txIndex.Get(txHash[:])
if len(serializedData) == 0 {
return nil, nil
}
// Ensure the serialized data has enough bytes to properly deserialize.
if len(serializedData) < 12 {
return nil, database.Error{
ErrorCode: database.ErrCorruption,
Description: fmt.Sprintf("corrupt transaction index "+
"entry for %s", txHash),
}
}
// Load the block hash associated with the block ID.
hash, err := dbFetchBlockHashBySerializedID(dbTx, serializedData[0:4])
if err != nil {
return nil, database.Error{
ErrorCode: database.ErrCorruption,
Description: fmt.Sprintf("corrupt transaction index "+
"entry for %s: %v", txHash, err),
}
}
// Deserialize the final entry.
region := database.BlockRegion{Hash: &chainhash.Hash{}}
copy(region.Hash[:], hash[:])
region.Offset = byteOrder.Uint32(serializedData[4:8])
region.Len = byteOrder.Uint32(serializedData[8:12])
return ®ion, nil
} | go | func dbFetchTxIndexEntry(dbTx database.Tx, txHash *chainhash.Hash) (*database.BlockRegion, error) {
// Load the record from the database and return now if it doesn't exist.
txIndex := dbTx.Metadata().Bucket(txIndexKey)
serializedData := txIndex.Get(txHash[:])
if len(serializedData) == 0 {
return nil, nil
}
// Ensure the serialized data has enough bytes to properly deserialize.
if len(serializedData) < 12 {
return nil, database.Error{
ErrorCode: database.ErrCorruption,
Description: fmt.Sprintf("corrupt transaction index "+
"entry for %s", txHash),
}
}
// Load the block hash associated with the block ID.
hash, err := dbFetchBlockHashBySerializedID(dbTx, serializedData[0:4])
if err != nil {
return nil, database.Error{
ErrorCode: database.ErrCorruption,
Description: fmt.Sprintf("corrupt transaction index "+
"entry for %s: %v", txHash, err),
}
}
// Deserialize the final entry.
region := database.BlockRegion{Hash: &chainhash.Hash{}}
copy(region.Hash[:], hash[:])
region.Offset = byteOrder.Uint32(serializedData[4:8])
region.Len = byteOrder.Uint32(serializedData[8:12])
return ®ion, nil
} | [
"func",
"dbFetchTxIndexEntry",
"(",
"dbTx",
"database",
".",
"Tx",
",",
"txHash",
"*",
"chainhash",
".",
"Hash",
")",
"(",
"*",
"database",
".",
"BlockRegion",
",",
"error",
")",
"{",
"// Load the record from the database and return now if it doesn't exist.",
"txIndex",
":=",
"dbTx",
".",
"Metadata",
"(",
")",
".",
"Bucket",
"(",
"txIndexKey",
")",
"\n",
"serializedData",
":=",
"txIndex",
".",
"Get",
"(",
"txHash",
"[",
":",
"]",
")",
"\n",
"if",
"len",
"(",
"serializedData",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"// Ensure the serialized data has enough bytes to properly deserialize.",
"if",
"len",
"(",
"serializedData",
")",
"<",
"12",
"{",
"return",
"nil",
",",
"database",
".",
"Error",
"{",
"ErrorCode",
":",
"database",
".",
"ErrCorruption",
",",
"Description",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"txHash",
")",
",",
"}",
"\n",
"}",
"\n\n",
"// Load the block hash associated with the block ID.",
"hash",
",",
"err",
":=",
"dbFetchBlockHashBySerializedID",
"(",
"dbTx",
",",
"serializedData",
"[",
"0",
":",
"4",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"database",
".",
"Error",
"{",
"ErrorCode",
":",
"database",
".",
"ErrCorruption",
",",
"Description",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"txHash",
",",
"err",
")",
",",
"}",
"\n",
"}",
"\n\n",
"// Deserialize the final entry.",
"region",
":=",
"database",
".",
"BlockRegion",
"{",
"Hash",
":",
"&",
"chainhash",
".",
"Hash",
"{",
"}",
"}",
"\n",
"copy",
"(",
"region",
".",
"Hash",
"[",
":",
"]",
",",
"hash",
"[",
":",
"]",
")",
"\n",
"region",
".",
"Offset",
"=",
"byteOrder",
".",
"Uint32",
"(",
"serializedData",
"[",
"4",
":",
"8",
"]",
")",
"\n",
"region",
".",
"Len",
"=",
"byteOrder",
".",
"Uint32",
"(",
"serializedData",
"[",
"8",
":",
"12",
"]",
")",
"\n\n",
"return",
"&",
"region",
",",
"nil",
"\n",
"}"
] | // dbFetchTxIndexEntry uses an existing database transaction to fetch the block
// region for the provided transaction hash from the transaction index. When
// there is no entry for the provided hash, nil will be returned for the both
// the region and the error. | [
"dbFetchTxIndexEntry",
"uses",
"an",
"existing",
"database",
"transaction",
"to",
"fetch",
"the",
"block",
"region",
"for",
"the",
"provided",
"transaction",
"hash",
"from",
"the",
"transaction",
"index",
".",
"When",
"there",
"is",
"no",
"entry",
"for",
"the",
"provided",
"hash",
"nil",
"will",
"be",
"returned",
"for",
"the",
"both",
"the",
"region",
"and",
"the",
"error",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/txindex.go#L189-L223 | train |
btcsuite/btcd | blockchain/indexers/txindex.go | dbAddTxIndexEntries | func dbAddTxIndexEntries(dbTx database.Tx, block *btcutil.Block, blockID uint32) error {
// The offset and length of the transactions within the serialized
// block.
txLocs, err := block.TxLoc()
if err != nil {
return err
}
// As an optimization, allocate a single slice big enough to hold all
// of the serialized transaction index entries for the block and
// serialize them directly into the slice. Then, pass the appropriate
// subslice to the database to be written. This approach significantly
// cuts down on the number of required allocations.
offset := 0
serializedValues := make([]byte, len(block.Transactions())*txEntrySize)
for i, tx := range block.Transactions() {
putTxIndexEntry(serializedValues[offset:], blockID, txLocs[i])
endOffset := offset + txEntrySize
err := dbPutTxIndexEntry(dbTx, tx.Hash(),
serializedValues[offset:endOffset:endOffset])
if err != nil {
return err
}
offset += txEntrySize
}
return nil
} | go | func dbAddTxIndexEntries(dbTx database.Tx, block *btcutil.Block, blockID uint32) error {
// The offset and length of the transactions within the serialized
// block.
txLocs, err := block.TxLoc()
if err != nil {
return err
}
// As an optimization, allocate a single slice big enough to hold all
// of the serialized transaction index entries for the block and
// serialize them directly into the slice. Then, pass the appropriate
// subslice to the database to be written. This approach significantly
// cuts down on the number of required allocations.
offset := 0
serializedValues := make([]byte, len(block.Transactions())*txEntrySize)
for i, tx := range block.Transactions() {
putTxIndexEntry(serializedValues[offset:], blockID, txLocs[i])
endOffset := offset + txEntrySize
err := dbPutTxIndexEntry(dbTx, tx.Hash(),
serializedValues[offset:endOffset:endOffset])
if err != nil {
return err
}
offset += txEntrySize
}
return nil
} | [
"func",
"dbAddTxIndexEntries",
"(",
"dbTx",
"database",
".",
"Tx",
",",
"block",
"*",
"btcutil",
".",
"Block",
",",
"blockID",
"uint32",
")",
"error",
"{",
"// The offset and length of the transactions within the serialized",
"// block.",
"txLocs",
",",
"err",
":=",
"block",
".",
"TxLoc",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// As an optimization, allocate a single slice big enough to hold all",
"// of the serialized transaction index entries for the block and",
"// serialize them directly into the slice. Then, pass the appropriate",
"// subslice to the database to be written. This approach significantly",
"// cuts down on the number of required allocations.",
"offset",
":=",
"0",
"\n",
"serializedValues",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"block",
".",
"Transactions",
"(",
")",
")",
"*",
"txEntrySize",
")",
"\n",
"for",
"i",
",",
"tx",
":=",
"range",
"block",
".",
"Transactions",
"(",
")",
"{",
"putTxIndexEntry",
"(",
"serializedValues",
"[",
"offset",
":",
"]",
",",
"blockID",
",",
"txLocs",
"[",
"i",
"]",
")",
"\n",
"endOffset",
":=",
"offset",
"+",
"txEntrySize",
"\n",
"err",
":=",
"dbPutTxIndexEntry",
"(",
"dbTx",
",",
"tx",
".",
"Hash",
"(",
")",
",",
"serializedValues",
"[",
"offset",
":",
"endOffset",
":",
"endOffset",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"offset",
"+=",
"txEntrySize",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // dbAddTxIndexEntries uses an existing database transaction to add a
// transaction index entry for every transaction in the passed block. | [
"dbAddTxIndexEntries",
"uses",
"an",
"existing",
"database",
"transaction",
"to",
"add",
"a",
"transaction",
"index",
"entry",
"for",
"every",
"transaction",
"in",
"the",
"passed",
"block",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/txindex.go#L227-L254 | train |
btcsuite/btcd | blockchain/indexers/txindex.go | dbRemoveTxIndexEntry | func dbRemoveTxIndexEntry(dbTx database.Tx, txHash *chainhash.Hash) error {
txIndex := dbTx.Metadata().Bucket(txIndexKey)
serializedData := txIndex.Get(txHash[:])
if len(serializedData) == 0 {
return fmt.Errorf("can't remove non-existent transaction %s "+
"from the transaction index", txHash)
}
return txIndex.Delete(txHash[:])
} | go | func dbRemoveTxIndexEntry(dbTx database.Tx, txHash *chainhash.Hash) error {
txIndex := dbTx.Metadata().Bucket(txIndexKey)
serializedData := txIndex.Get(txHash[:])
if len(serializedData) == 0 {
return fmt.Errorf("can't remove non-existent transaction %s "+
"from the transaction index", txHash)
}
return txIndex.Delete(txHash[:])
} | [
"func",
"dbRemoveTxIndexEntry",
"(",
"dbTx",
"database",
".",
"Tx",
",",
"txHash",
"*",
"chainhash",
".",
"Hash",
")",
"error",
"{",
"txIndex",
":=",
"dbTx",
".",
"Metadata",
"(",
")",
".",
"Bucket",
"(",
"txIndexKey",
")",
"\n",
"serializedData",
":=",
"txIndex",
".",
"Get",
"(",
"txHash",
"[",
":",
"]",
")",
"\n",
"if",
"len",
"(",
"serializedData",
")",
"==",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"txHash",
")",
"\n",
"}",
"\n\n",
"return",
"txIndex",
".",
"Delete",
"(",
"txHash",
"[",
":",
"]",
")",
"\n",
"}"
] | // dbRemoveTxIndexEntry uses an existing database transaction to remove the most
// recent transaction index entry for the given hash. | [
"dbRemoveTxIndexEntry",
"uses",
"an",
"existing",
"database",
"transaction",
"to",
"remove",
"the",
"most",
"recent",
"transaction",
"index",
"entry",
"for",
"the",
"given",
"hash",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/txindex.go#L258-L267 | train |
btcsuite/btcd | blockchain/indexers/txindex.go | dbRemoveTxIndexEntries | func dbRemoveTxIndexEntries(dbTx database.Tx, block *btcutil.Block) error {
for _, tx := range block.Transactions() {
err := dbRemoveTxIndexEntry(dbTx, tx.Hash())
if err != nil {
return err
}
}
return nil
} | go | func dbRemoveTxIndexEntries(dbTx database.Tx, block *btcutil.Block) error {
for _, tx := range block.Transactions() {
err := dbRemoveTxIndexEntry(dbTx, tx.Hash())
if err != nil {
return err
}
}
return nil
} | [
"func",
"dbRemoveTxIndexEntries",
"(",
"dbTx",
"database",
".",
"Tx",
",",
"block",
"*",
"btcutil",
".",
"Block",
")",
"error",
"{",
"for",
"_",
",",
"tx",
":=",
"range",
"block",
".",
"Transactions",
"(",
")",
"{",
"err",
":=",
"dbRemoveTxIndexEntry",
"(",
"dbTx",
",",
"tx",
".",
"Hash",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // dbRemoveTxIndexEntries uses an existing database transaction to remove the
// latest transaction entry for every transaction in the passed block. | [
"dbRemoveTxIndexEntries",
"uses",
"an",
"existing",
"database",
"transaction",
"to",
"remove",
"the",
"latest",
"transaction",
"entry",
"for",
"every",
"transaction",
"in",
"the",
"passed",
"block",
"."
] | 96897255fd17525dd12426345d279533780bc4e1 | https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/txindex.go#L271-L280 | train |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.