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/blockindex.go
Header
func (node *blockNode) Header() wire.BlockHeader { // No lock is needed because all accessed fields are immutable. prevHash := &zeroHash if node.parent != nil { prevHash = &node.parent.hash } return wire.BlockHeader{ Version: node.version, PrevBlock: *prevHash, MerkleRoot: node.merkleRoot, Timestamp: time.Unix(node.timestamp, 0), Bits: node.bits, Nonce: node.nonce, } }
go
func (node *blockNode) Header() wire.BlockHeader { // No lock is needed because all accessed fields are immutable. prevHash := &zeroHash if node.parent != nil { prevHash = &node.parent.hash } return wire.BlockHeader{ Version: node.version, PrevBlock: *prevHash, MerkleRoot: node.merkleRoot, Timestamp: time.Unix(node.timestamp, 0), Bits: node.bits, Nonce: node.nonce, } }
[ "func", "(", "node", "*", "blockNode", ")", "Header", "(", ")", "wire", ".", "BlockHeader", "{", "// No lock is needed because all accessed fields are immutable.", "prevHash", ":=", "&", "zeroHash", "\n", "if", "node", ".", "parent", "!=", "nil", "{", "prevHash", "=", "&", "node", ".", "parent", ".", "hash", "\n", "}", "\n", "return", "wire", ".", "BlockHeader", "{", "Version", ":", "node", ".", "version", ",", "PrevBlock", ":", "*", "prevHash", ",", "MerkleRoot", ":", "node", ".", "merkleRoot", ",", "Timestamp", ":", "time", ".", "Unix", "(", "node", ".", "timestamp", ",", "0", ")", ",", "Bits", ":", "node", ".", "bits", ",", "Nonce", ":", "node", ".", "nonce", ",", "}", "\n", "}" ]
// Header constructs a block header from the node and returns it. // // This function is safe for concurrent access.
[ "Header", "constructs", "a", "block", "header", "from", "the", "node", "and", "returns", "it", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/blockindex.go#L137-L151
train
btcsuite/btcd
blockchain/blockindex.go
Ancestor
func (node *blockNode) Ancestor(height int32) *blockNode { if height < 0 || height > node.height { return nil } n := node for ; n != nil && n.height != height; n = n.parent { // Intentionally left blank } return n }
go
func (node *blockNode) Ancestor(height int32) *blockNode { if height < 0 || height > node.height { return nil } n := node for ; n != nil && n.height != height; n = n.parent { // Intentionally left blank } return n }
[ "func", "(", "node", "*", "blockNode", ")", "Ancestor", "(", "height", "int32", ")", "*", "blockNode", "{", "if", "height", "<", "0", "||", "height", ">", "node", ".", "height", "{", "return", "nil", "\n", "}", "\n\n", "n", ":=", "node", "\n", "for", ";", "n", "!=", "nil", "&&", "n", ".", "height", "!=", "height", ";", "n", "=", "n", ".", "parent", "{", "// Intentionally left blank", "}", "\n\n", "return", "n", "\n", "}" ]
// Ancestor returns the ancestor block node at the provided height by following // the chain backwards from this node. The returned block will be nil when a // height is requested that is after the height of the passed node or is less // than zero. // // This function is safe for concurrent access.
[ "Ancestor", "returns", "the", "ancestor", "block", "node", "at", "the", "provided", "height", "by", "following", "the", "chain", "backwards", "from", "this", "node", ".", "The", "returned", "block", "will", "be", "nil", "when", "a", "height", "is", "requested", "that", "is", "after", "the", "height", "of", "the", "passed", "node", "or", "is", "less", "than", "zero", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/blockindex.go#L159-L170
train
btcsuite/btcd
blockchain/blockindex.go
RelativeAncestor
func (node *blockNode) RelativeAncestor(distance int32) *blockNode { return node.Ancestor(node.height - distance) }
go
func (node *blockNode) RelativeAncestor(distance int32) *blockNode { return node.Ancestor(node.height - distance) }
[ "func", "(", "node", "*", "blockNode", ")", "RelativeAncestor", "(", "distance", "int32", ")", "*", "blockNode", "{", "return", "node", ".", "Ancestor", "(", "node", ".", "height", "-", "distance", ")", "\n", "}" ]
// RelativeAncestor returns the ancestor block node a relative 'distance' blocks // before this node. This is equivalent to calling Ancestor with the node's // height minus provided distance. // // This function is safe for concurrent access.
[ "RelativeAncestor", "returns", "the", "ancestor", "block", "node", "a", "relative", "distance", "blocks", "before", "this", "node", ".", "This", "is", "equivalent", "to", "calling", "Ancestor", "with", "the", "node", "s", "height", "minus", "provided", "distance", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/blockindex.go#L177-L179
train
btcsuite/btcd
blockchain/blockindex.go
CalcPastMedianTime
func (node *blockNode) CalcPastMedianTime() time.Time { // Create a slice of the previous few block timestamps used to calculate // the median per the number defined by the constant medianTimeBlocks. timestamps := make([]int64, medianTimeBlocks) numNodes := 0 iterNode := node for i := 0; i < medianTimeBlocks && iterNode != nil; i++ { timestamps[i] = iterNode.timestamp numNodes++ iterNode = iterNode.parent } // Prune the slice to the actual number of available timestamps which // will be fewer than desired near the beginning of the block chain // and sort them. timestamps = timestamps[:numNodes] sort.Sort(timeSorter(timestamps)) // NOTE: The consensus rules incorrectly calculate the median for even // numbers of blocks. A true median averages the middle two elements // for a set with an even number of elements in it. Since the constant // for the previous number of blocks to be used is odd, this is only an // issue for a few blocks near the beginning of the chain. I suspect // this is an optimization even though the result is slightly wrong for // a few of the first blocks since after the first few blocks, there // will always be an odd number of blocks in the set per the constant. // // This code follows suit to ensure the same rules are used, however, be // aware that should the medianTimeBlocks constant ever be changed to an // even number, this code will be wrong. medianTimestamp := timestamps[numNodes/2] return time.Unix(medianTimestamp, 0) }
go
func (node *blockNode) CalcPastMedianTime() time.Time { // Create a slice of the previous few block timestamps used to calculate // the median per the number defined by the constant medianTimeBlocks. timestamps := make([]int64, medianTimeBlocks) numNodes := 0 iterNode := node for i := 0; i < medianTimeBlocks && iterNode != nil; i++ { timestamps[i] = iterNode.timestamp numNodes++ iterNode = iterNode.parent } // Prune the slice to the actual number of available timestamps which // will be fewer than desired near the beginning of the block chain // and sort them. timestamps = timestamps[:numNodes] sort.Sort(timeSorter(timestamps)) // NOTE: The consensus rules incorrectly calculate the median for even // numbers of blocks. A true median averages the middle two elements // for a set with an even number of elements in it. Since the constant // for the previous number of blocks to be used is odd, this is only an // issue for a few blocks near the beginning of the chain. I suspect // this is an optimization even though the result is slightly wrong for // a few of the first blocks since after the first few blocks, there // will always be an odd number of blocks in the set per the constant. // // This code follows suit to ensure the same rules are used, however, be // aware that should the medianTimeBlocks constant ever be changed to an // even number, this code will be wrong. medianTimestamp := timestamps[numNodes/2] return time.Unix(medianTimestamp, 0) }
[ "func", "(", "node", "*", "blockNode", ")", "CalcPastMedianTime", "(", ")", "time", ".", "Time", "{", "// Create a slice of the previous few block timestamps used to calculate", "// the median per the number defined by the constant medianTimeBlocks.", "timestamps", ":=", "make", "(", "[", "]", "int64", ",", "medianTimeBlocks", ")", "\n", "numNodes", ":=", "0", "\n", "iterNode", ":=", "node", "\n", "for", "i", ":=", "0", ";", "i", "<", "medianTimeBlocks", "&&", "iterNode", "!=", "nil", ";", "i", "++", "{", "timestamps", "[", "i", "]", "=", "iterNode", ".", "timestamp", "\n", "numNodes", "++", "\n\n", "iterNode", "=", "iterNode", ".", "parent", "\n", "}", "\n\n", "// Prune the slice to the actual number of available timestamps which", "// will be fewer than desired near the beginning of the block chain", "// and sort them.", "timestamps", "=", "timestamps", "[", ":", "numNodes", "]", "\n", "sort", ".", "Sort", "(", "timeSorter", "(", "timestamps", ")", ")", "\n\n", "// NOTE: The consensus rules incorrectly calculate the median for even", "// numbers of blocks. A true median averages the middle two elements", "// for a set with an even number of elements in it. Since the constant", "// for the previous number of blocks to be used is odd, this is only an", "// issue for a few blocks near the beginning of the chain. I suspect", "// this is an optimization even though the result is slightly wrong for", "// a few of the first blocks since after the first few blocks, there", "// will always be an odd number of blocks in the set per the constant.", "//", "// This code follows suit to ensure the same rules are used, however, be", "// aware that should the medianTimeBlocks constant ever be changed to an", "// even number, this code will be wrong.", "medianTimestamp", ":=", "timestamps", "[", "numNodes", "/", "2", "]", "\n", "return", "time", ".", "Unix", "(", "medianTimestamp", ",", "0", ")", "\n", "}" ]
// CalcPastMedianTime calculates the median time of the previous few blocks // prior to, and including, the block node. // // This function is safe for concurrent access.
[ "CalcPastMedianTime", "calculates", "the", "median", "time", "of", "the", "previous", "few", "blocks", "prior", "to", "and", "including", "the", "block", "node", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/blockindex.go#L185-L218
train
btcsuite/btcd
blockchain/blockindex.go
newBlockIndex
func newBlockIndex(db database.DB, chainParams *chaincfg.Params) *blockIndex { return &blockIndex{ db: db, chainParams: chainParams, index: make(map[chainhash.Hash]*blockNode), dirty: make(map[*blockNode]struct{}), } }
go
func newBlockIndex(db database.DB, chainParams *chaincfg.Params) *blockIndex { return &blockIndex{ db: db, chainParams: chainParams, index: make(map[chainhash.Hash]*blockNode), dirty: make(map[*blockNode]struct{}), } }
[ "func", "newBlockIndex", "(", "db", "database", ".", "DB", ",", "chainParams", "*", "chaincfg", ".", "Params", ")", "*", "blockIndex", "{", "return", "&", "blockIndex", "{", "db", ":", "db", ",", "chainParams", ":", "chainParams", ",", "index", ":", "make", "(", "map", "[", "chainhash", ".", "Hash", "]", "*", "blockNode", ")", ",", "dirty", ":", "make", "(", "map", "[", "*", "blockNode", "]", "struct", "{", "}", ")", ",", "}", "\n", "}" ]
// newBlockIndex returns a new empty instance of a block index. The index will // be dynamically populated as block nodes are loaded from the database and // manually added.
[ "newBlockIndex", "returns", "a", "new", "empty", "instance", "of", "a", "block", "index", ".", "The", "index", "will", "be", "dynamically", "populated", "as", "block", "nodes", "are", "loaded", "from", "the", "database", "and", "manually", "added", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/blockindex.go#L240-L247
train
btcsuite/btcd
blockchain/blockindex.go
HaveBlock
func (bi *blockIndex) HaveBlock(hash *chainhash.Hash) bool { bi.RLock() _, hasBlock := bi.index[*hash] bi.RUnlock() return hasBlock }
go
func (bi *blockIndex) HaveBlock(hash *chainhash.Hash) bool { bi.RLock() _, hasBlock := bi.index[*hash] bi.RUnlock() return hasBlock }
[ "func", "(", "bi", "*", "blockIndex", ")", "HaveBlock", "(", "hash", "*", "chainhash", ".", "Hash", ")", "bool", "{", "bi", ".", "RLock", "(", ")", "\n", "_", ",", "hasBlock", ":=", "bi", ".", "index", "[", "*", "hash", "]", "\n", "bi", ".", "RUnlock", "(", ")", "\n", "return", "hasBlock", "\n", "}" ]
// HaveBlock returns whether or not the block index contains the provided hash. // // This function is safe for concurrent access.
[ "HaveBlock", "returns", "whether", "or", "not", "the", "block", "index", "contains", "the", "provided", "hash", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/blockindex.go#L252-L257
train
btcsuite/btcd
blockchain/blockindex.go
LookupNode
func (bi *blockIndex) LookupNode(hash *chainhash.Hash) *blockNode { bi.RLock() node := bi.index[*hash] bi.RUnlock() return node }
go
func (bi *blockIndex) LookupNode(hash *chainhash.Hash) *blockNode { bi.RLock() node := bi.index[*hash] bi.RUnlock() return node }
[ "func", "(", "bi", "*", "blockIndex", ")", "LookupNode", "(", "hash", "*", "chainhash", ".", "Hash", ")", "*", "blockNode", "{", "bi", ".", "RLock", "(", ")", "\n", "node", ":=", "bi", ".", "index", "[", "*", "hash", "]", "\n", "bi", ".", "RUnlock", "(", ")", "\n", "return", "node", "\n", "}" ]
// LookupNode returns the block node identified by the provided hash. It will // return nil if there is no entry for the hash. // // This function is safe for concurrent access.
[ "LookupNode", "returns", "the", "block", "node", "identified", "by", "the", "provided", "hash", ".", "It", "will", "return", "nil", "if", "there", "is", "no", "entry", "for", "the", "hash", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/blockindex.go#L263-L268
train
btcsuite/btcd
blockchain/blockindex.go
AddNode
func (bi *blockIndex) AddNode(node *blockNode) { bi.Lock() bi.addNode(node) bi.dirty[node] = struct{}{} bi.Unlock() }
go
func (bi *blockIndex) AddNode(node *blockNode) { bi.Lock() bi.addNode(node) bi.dirty[node] = struct{}{} bi.Unlock() }
[ "func", "(", "bi", "*", "blockIndex", ")", "AddNode", "(", "node", "*", "blockNode", ")", "{", "bi", ".", "Lock", "(", ")", "\n", "bi", ".", "addNode", "(", "node", ")", "\n", "bi", ".", "dirty", "[", "node", "]", "=", "struct", "{", "}", "{", "}", "\n", "bi", ".", "Unlock", "(", ")", "\n", "}" ]
// AddNode adds the provided node to the block index and marks it as dirty. // Duplicate entries are not checked so it is up to caller to avoid adding them. // // This function is safe for concurrent access.
[ "AddNode", "adds", "the", "provided", "node", "to", "the", "block", "index", "and", "marks", "it", "as", "dirty", ".", "Duplicate", "entries", "are", "not", "checked", "so", "it", "is", "up", "to", "caller", "to", "avoid", "adding", "them", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/blockindex.go#L274-L279
train
btcsuite/btcd
blockchain/blockindex.go
addNode
func (bi *blockIndex) addNode(node *blockNode) { bi.index[node.hash] = node }
go
func (bi *blockIndex) addNode(node *blockNode) { bi.index[node.hash] = node }
[ "func", "(", "bi", "*", "blockIndex", ")", "addNode", "(", "node", "*", "blockNode", ")", "{", "bi", ".", "index", "[", "node", ".", "hash", "]", "=", "node", "\n", "}" ]
// addNode adds the provided node to the block index, but does not mark it as // dirty. This can be used while initializing the block index. // // This function is NOT safe for concurrent access.
[ "addNode", "adds", "the", "provided", "node", "to", "the", "block", "index", "but", "does", "not", "mark", "it", "as", "dirty", ".", "This", "can", "be", "used", "while", "initializing", "the", "block", "index", ".", "This", "function", "is", "NOT", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/blockindex.go#L285-L287
train
btcsuite/btcd
blockchain/blockindex.go
NodeStatus
func (bi *blockIndex) NodeStatus(node *blockNode) blockStatus { bi.RLock() status := node.status bi.RUnlock() return status }
go
func (bi *blockIndex) NodeStatus(node *blockNode) blockStatus { bi.RLock() status := node.status bi.RUnlock() return status }
[ "func", "(", "bi", "*", "blockIndex", ")", "NodeStatus", "(", "node", "*", "blockNode", ")", "blockStatus", "{", "bi", ".", "RLock", "(", ")", "\n", "status", ":=", "node", ".", "status", "\n", "bi", ".", "RUnlock", "(", ")", "\n", "return", "status", "\n", "}" ]
// NodeStatus provides concurrent-safe access to the status field of a node. // // This function is safe for concurrent access.
[ "NodeStatus", "provides", "concurrent", "-", "safe", "access", "to", "the", "status", "field", "of", "a", "node", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/blockindex.go#L292-L297
train
btcsuite/btcd
blockchain/blockindex.go
SetStatusFlags
func (bi *blockIndex) SetStatusFlags(node *blockNode, flags blockStatus) { bi.Lock() node.status |= flags bi.dirty[node] = struct{}{} bi.Unlock() }
go
func (bi *blockIndex) SetStatusFlags(node *blockNode, flags blockStatus) { bi.Lock() node.status |= flags bi.dirty[node] = struct{}{} bi.Unlock() }
[ "func", "(", "bi", "*", "blockIndex", ")", "SetStatusFlags", "(", "node", "*", "blockNode", ",", "flags", "blockStatus", ")", "{", "bi", ".", "Lock", "(", ")", "\n", "node", ".", "status", "|=", "flags", "\n", "bi", ".", "dirty", "[", "node", "]", "=", "struct", "{", "}", "{", "}", "\n", "bi", ".", "Unlock", "(", ")", "\n", "}" ]
// SetStatusFlags flips the provided status flags on the block node to on, // regardless of whether they were on or off previously. This does not unset any // flags currently on. // // This function is safe for concurrent access.
[ "SetStatusFlags", "flips", "the", "provided", "status", "flags", "on", "the", "block", "node", "to", "on", "regardless", "of", "whether", "they", "were", "on", "or", "off", "previously", ".", "This", "does", "not", "unset", "any", "flags", "currently", "on", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/blockindex.go#L304-L309
train
btcsuite/btcd
blockchain/blockindex.go
flushToDB
func (bi *blockIndex) flushToDB() error { bi.Lock() if len(bi.dirty) == 0 { bi.Unlock() return nil } err := bi.db.Update(func(dbTx database.Tx) error { for node := range bi.dirty { err := dbStoreBlockNode(dbTx, node) if err != nil { return err } } return nil }) // If write was successful, clear the dirty set. if err == nil { bi.dirty = make(map[*blockNode]struct{}) } bi.Unlock() return err }
go
func (bi *blockIndex) flushToDB() error { bi.Lock() if len(bi.dirty) == 0 { bi.Unlock() return nil } err := bi.db.Update(func(dbTx database.Tx) error { for node := range bi.dirty { err := dbStoreBlockNode(dbTx, node) if err != nil { return err } } return nil }) // If write was successful, clear the dirty set. if err == nil { bi.dirty = make(map[*blockNode]struct{}) } bi.Unlock() return err }
[ "func", "(", "bi", "*", "blockIndex", ")", "flushToDB", "(", ")", "error", "{", "bi", ".", "Lock", "(", ")", "\n", "if", "len", "(", "bi", ".", "dirty", ")", "==", "0", "{", "bi", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}", "\n\n", "err", ":=", "bi", ".", "db", ".", "Update", "(", "func", "(", "dbTx", "database", ".", "Tx", ")", "error", "{", "for", "node", ":=", "range", "bi", ".", "dirty", "{", "err", ":=", "dbStoreBlockNode", "(", "dbTx", ",", "node", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n\n", "// If write was successful, clear the dirty set.", "if", "err", "==", "nil", "{", "bi", ".", "dirty", "=", "make", "(", "map", "[", "*", "blockNode", "]", "struct", "{", "}", ")", "\n", "}", "\n\n", "bi", ".", "Unlock", "(", ")", "\n", "return", "err", "\n", "}" ]
// flushToDB writes all dirty block nodes to the database. If all writes // succeed, this clears the dirty set.
[ "flushToDB", "writes", "all", "dirty", "block", "nodes", "to", "the", "database", ".", "If", "all", "writes", "succeed", "this", "clears", "the", "dirty", "set", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/blockindex.go#L324-L348
train
btcsuite/btcd
txscript/engine.go
hasFlag
func (vm *Engine) hasFlag(flag ScriptFlags) bool { return vm.flags&flag == flag }
go
func (vm *Engine) hasFlag(flag ScriptFlags) bool { return vm.flags&flag == flag }
[ "func", "(", "vm", "*", "Engine", ")", "hasFlag", "(", "flag", "ScriptFlags", ")", "bool", "{", "return", "vm", ".", "flags", "&", "flag", "==", "flag", "\n", "}" ]
// hasFlag returns whether the script engine instance has the passed flag set.
[ "hasFlag", "returns", "whether", "the", "script", "engine", "instance", "has", "the", "passed", "flag", "set", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/engine.go#L142-L144
train
btcsuite/btcd
txscript/engine.go
isBranchExecuting
func (vm *Engine) isBranchExecuting() bool { if len(vm.condStack) == 0 { return true } return vm.condStack[len(vm.condStack)-1] == OpCondTrue }
go
func (vm *Engine) isBranchExecuting() bool { if len(vm.condStack) == 0 { return true } return vm.condStack[len(vm.condStack)-1] == OpCondTrue }
[ "func", "(", "vm", "*", "Engine", ")", "isBranchExecuting", "(", ")", "bool", "{", "if", "len", "(", "vm", ".", "condStack", ")", "==", "0", "{", "return", "true", "\n", "}", "\n", "return", "vm", ".", "condStack", "[", "len", "(", "vm", ".", "condStack", ")", "-", "1", "]", "==", "OpCondTrue", "\n", "}" ]
// isBranchExecuting returns whether or not the current conditional branch is // actively executing. For example, when the data stack has an OP_FALSE on it // and an OP_IF is encountered, the branch is inactive until an OP_ELSE or // OP_ENDIF is encountered. It properly handles nested conditionals.
[ "isBranchExecuting", "returns", "whether", "or", "not", "the", "current", "conditional", "branch", "is", "actively", "executing", ".", "For", "example", "when", "the", "data", "stack", "has", "an", "OP_FALSE", "on", "it", "and", "an", "OP_IF", "is", "encountered", "the", "branch", "is", "inactive", "until", "an", "OP_ELSE", "or", "OP_ENDIF", "is", "encountered", ".", "It", "properly", "handles", "nested", "conditionals", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/engine.go#L150-L155
train
btcsuite/btcd
txscript/engine.go
executeOpcode
func (vm *Engine) executeOpcode(pop *parsedOpcode) error { // Disabled opcodes are fail on program counter. if pop.isDisabled() { str := fmt.Sprintf("attempt to execute disabled opcode %s", pop.opcode.name) return scriptError(ErrDisabledOpcode, str) } // Always-illegal opcodes are fail on program counter. if pop.alwaysIllegal() { str := fmt.Sprintf("attempt to execute reserved opcode %s", pop.opcode.name) return scriptError(ErrReservedOpcode, str) } // Note that this includes OP_RESERVED which counts as a push operation. if pop.opcode.value > OP_16 { vm.numOps++ if vm.numOps > MaxOpsPerScript { str := fmt.Sprintf("exceeded max operation limit of %d", MaxOpsPerScript) return scriptError(ErrTooManyOperations, str) } } else if len(pop.data) > MaxScriptElementSize { str := fmt.Sprintf("element size %d exceeds max allowed size %d", len(pop.data), MaxScriptElementSize) return scriptError(ErrElementTooBig, str) } // Nothing left to do when this is not a conditional opcode and it is // not in an executing branch. if !vm.isBranchExecuting() && !pop.isConditional() { return nil } // Ensure all executed data push opcodes use the minimal encoding when // the minimal data verification flag is set. if vm.dstack.verifyMinimalData && vm.isBranchExecuting() && pop.opcode.value >= 0 && pop.opcode.value <= OP_PUSHDATA4 { if err := pop.checkMinimalDataPush(); err != nil { return err } } return pop.opcode.opfunc(pop, vm) }
go
func (vm *Engine) executeOpcode(pop *parsedOpcode) error { // Disabled opcodes are fail on program counter. if pop.isDisabled() { str := fmt.Sprintf("attempt to execute disabled opcode %s", pop.opcode.name) return scriptError(ErrDisabledOpcode, str) } // Always-illegal opcodes are fail on program counter. if pop.alwaysIllegal() { str := fmt.Sprintf("attempt to execute reserved opcode %s", pop.opcode.name) return scriptError(ErrReservedOpcode, str) } // Note that this includes OP_RESERVED which counts as a push operation. if pop.opcode.value > OP_16 { vm.numOps++ if vm.numOps > MaxOpsPerScript { str := fmt.Sprintf("exceeded max operation limit of %d", MaxOpsPerScript) return scriptError(ErrTooManyOperations, str) } } else if len(pop.data) > MaxScriptElementSize { str := fmt.Sprintf("element size %d exceeds max allowed size %d", len(pop.data), MaxScriptElementSize) return scriptError(ErrElementTooBig, str) } // Nothing left to do when this is not a conditional opcode and it is // not in an executing branch. if !vm.isBranchExecuting() && !pop.isConditional() { return nil } // Ensure all executed data push opcodes use the minimal encoding when // the minimal data verification flag is set. if vm.dstack.verifyMinimalData && vm.isBranchExecuting() && pop.opcode.value >= 0 && pop.opcode.value <= OP_PUSHDATA4 { if err := pop.checkMinimalDataPush(); err != nil { return err } } return pop.opcode.opfunc(pop, vm) }
[ "func", "(", "vm", "*", "Engine", ")", "executeOpcode", "(", "pop", "*", "parsedOpcode", ")", "error", "{", "// Disabled opcodes are fail on program counter.", "if", "pop", ".", "isDisabled", "(", ")", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "pop", ".", "opcode", ".", "name", ")", "\n", "return", "scriptError", "(", "ErrDisabledOpcode", ",", "str", ")", "\n", "}", "\n\n", "// Always-illegal opcodes are fail on program counter.", "if", "pop", ".", "alwaysIllegal", "(", ")", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "pop", ".", "opcode", ".", "name", ")", "\n", "return", "scriptError", "(", "ErrReservedOpcode", ",", "str", ")", "\n", "}", "\n\n", "// Note that this includes OP_RESERVED which counts as a push operation.", "if", "pop", ".", "opcode", ".", "value", ">", "OP_16", "{", "vm", ".", "numOps", "++", "\n", "if", "vm", ".", "numOps", ">", "MaxOpsPerScript", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "MaxOpsPerScript", ")", "\n", "return", "scriptError", "(", "ErrTooManyOperations", ",", "str", ")", "\n", "}", "\n\n", "}", "else", "if", "len", "(", "pop", ".", "data", ")", ">", "MaxScriptElementSize", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "len", "(", "pop", ".", "data", ")", ",", "MaxScriptElementSize", ")", "\n", "return", "scriptError", "(", "ErrElementTooBig", ",", "str", ")", "\n", "}", "\n\n", "// Nothing left to do when this is not a conditional opcode and it is", "// not in an executing branch.", "if", "!", "vm", ".", "isBranchExecuting", "(", ")", "&&", "!", "pop", ".", "isConditional", "(", ")", "{", "return", "nil", "\n", "}", "\n\n", "// Ensure all executed data push opcodes use the minimal encoding when", "// the minimal data verification flag is set.", "if", "vm", ".", "dstack", ".", "verifyMinimalData", "&&", "vm", ".", "isBranchExecuting", "(", ")", "&&", "pop", ".", "opcode", ".", "value", ">=", "0", "&&", "pop", ".", "opcode", ".", "value", "<=", "OP_PUSHDATA4", "{", "if", "err", ":=", "pop", ".", "checkMinimalDataPush", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "pop", ".", "opcode", ".", "opfunc", "(", "pop", ",", "vm", ")", "\n", "}" ]
// executeOpcode peforms execution on the passed opcode. It takes into account // whether or not it is hidden by conditionals, but some rules still must be // tested in this case.
[ "executeOpcode", "peforms", "execution", "on", "the", "passed", "opcode", ".", "It", "takes", "into", "account", "whether", "or", "not", "it", "is", "hidden", "by", "conditionals", "but", "some", "rules", "still", "must", "be", "tested", "in", "this", "case", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/engine.go#L160-L207
train
btcsuite/btcd
txscript/engine.go
disasm
func (vm *Engine) disasm(scriptIdx int, scriptOff int) string { return fmt.Sprintf("%02x:%04x: %s", scriptIdx, scriptOff, vm.scripts[scriptIdx][scriptOff].print(false)) }
go
func (vm *Engine) disasm(scriptIdx int, scriptOff int) string { return fmt.Sprintf("%02x:%04x: %s", scriptIdx, scriptOff, vm.scripts[scriptIdx][scriptOff].print(false)) }
[ "func", "(", "vm", "*", "Engine", ")", "disasm", "(", "scriptIdx", "int", ",", "scriptOff", "int", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "scriptIdx", ",", "scriptOff", ",", "vm", ".", "scripts", "[", "scriptIdx", "]", "[", "scriptOff", "]", ".", "print", "(", "false", ")", ")", "\n", "}" ]
// disasm is a helper function to produce the output for DisasmPC and // DisasmScript. It produces the opcode prefixed by the program counter at the // provided position in the script. It does no error checking and leaves that // to the caller to provide a valid offset.
[ "disasm", "is", "a", "helper", "function", "to", "produce", "the", "output", "for", "DisasmPC", "and", "DisasmScript", ".", "It", "produces", "the", "opcode", "prefixed", "by", "the", "program", "counter", "at", "the", "provided", "position", "in", "the", "script", ".", "It", "does", "no", "error", "checking", "and", "leaves", "that", "to", "the", "caller", "to", "provide", "a", "valid", "offset", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/engine.go#L213-L216
train
btcsuite/btcd
txscript/engine.go
validPC
func (vm *Engine) validPC() error { if vm.scriptIdx >= len(vm.scripts) { str := fmt.Sprintf("past input scripts %v:%v %v:xxxx", vm.scriptIdx, vm.scriptOff, len(vm.scripts)) return scriptError(ErrInvalidProgramCounter, str) } if vm.scriptOff >= len(vm.scripts[vm.scriptIdx]) { str := fmt.Sprintf("past input scripts %v:%v %v:%04d", vm.scriptIdx, vm.scriptOff, vm.scriptIdx, len(vm.scripts[vm.scriptIdx])) return scriptError(ErrInvalidProgramCounter, str) } return nil }
go
func (vm *Engine) validPC() error { if vm.scriptIdx >= len(vm.scripts) { str := fmt.Sprintf("past input scripts %v:%v %v:xxxx", vm.scriptIdx, vm.scriptOff, len(vm.scripts)) return scriptError(ErrInvalidProgramCounter, str) } if vm.scriptOff >= len(vm.scripts[vm.scriptIdx]) { str := fmt.Sprintf("past input scripts %v:%v %v:%04d", vm.scriptIdx, vm.scriptOff, vm.scriptIdx, len(vm.scripts[vm.scriptIdx])) return scriptError(ErrInvalidProgramCounter, str) } return nil }
[ "func", "(", "vm", "*", "Engine", ")", "validPC", "(", ")", "error", "{", "if", "vm", ".", "scriptIdx", ">=", "len", "(", "vm", ".", "scripts", ")", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "vm", ".", "scriptIdx", ",", "vm", ".", "scriptOff", ",", "len", "(", "vm", ".", "scripts", ")", ")", "\n", "return", "scriptError", "(", "ErrInvalidProgramCounter", ",", "str", ")", "\n", "}", "\n", "if", "vm", ".", "scriptOff", ">=", "len", "(", "vm", ".", "scripts", "[", "vm", ".", "scriptIdx", "]", ")", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "vm", ".", "scriptIdx", ",", "vm", ".", "scriptOff", ",", "vm", ".", "scriptIdx", ",", "len", "(", "vm", ".", "scripts", "[", "vm", ".", "scriptIdx", "]", ")", ")", "\n", "return", "scriptError", "(", "ErrInvalidProgramCounter", ",", "str", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// validPC returns an error if the current script position is valid for // execution, nil otherwise.
[ "validPC", "returns", "an", "error", "if", "the", "current", "script", "position", "is", "valid", "for", "execution", "nil", "otherwise", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/engine.go#L220-L233
train
btcsuite/btcd
txscript/engine.go
curPC
func (vm *Engine) curPC() (script int, off int, err error) { err = vm.validPC() if err != nil { return 0, 0, err } return vm.scriptIdx, vm.scriptOff, nil }
go
func (vm *Engine) curPC() (script int, off int, err error) { err = vm.validPC() if err != nil { return 0, 0, err } return vm.scriptIdx, vm.scriptOff, nil }
[ "func", "(", "vm", "*", "Engine", ")", "curPC", "(", ")", "(", "script", "int", ",", "off", "int", ",", "err", "error", ")", "{", "err", "=", "vm", ".", "validPC", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "0", ",", "err", "\n", "}", "\n", "return", "vm", ".", "scriptIdx", ",", "vm", ".", "scriptOff", ",", "nil", "\n", "}" ]
// curPC returns either the current script and offset, or an error if the // position isn't valid.
[ "curPC", "returns", "either", "the", "current", "script", "and", "offset", "or", "an", "error", "if", "the", "position", "isn", "t", "valid", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/engine.go#L237-L243
train
btcsuite/btcd
txscript/engine.go
isWitnessVersionActive
func (vm *Engine) isWitnessVersionActive(version uint) bool { return vm.witnessProgram != nil && uint(vm.witnessVersion) == version }
go
func (vm *Engine) isWitnessVersionActive(version uint) bool { return vm.witnessProgram != nil && uint(vm.witnessVersion) == version }
[ "func", "(", "vm", "*", "Engine", ")", "isWitnessVersionActive", "(", "version", "uint", ")", "bool", "{", "return", "vm", ".", "witnessProgram", "!=", "nil", "&&", "uint", "(", "vm", ".", "witnessVersion", ")", "==", "version", "\n", "}" ]
// isWitnessVersionActive returns true if a witness program was extracted // during the initialization of the Engine, and the program's version matches // the specified version.
[ "isWitnessVersionActive", "returns", "true", "if", "a", "witness", "program", "was", "extracted", "during", "the", "initialization", "of", "the", "Engine", "and", "the", "program", "s", "version", "matches", "the", "specified", "version", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/engine.go#L248-L250
train
btcsuite/btcd
txscript/engine.go
verifyWitnessProgram
func (vm *Engine) verifyWitnessProgram(witness [][]byte) error { if vm.isWitnessVersionActive(0) { switch len(vm.witnessProgram) { case payToWitnessPubKeyHashDataSize: // P2WKH // The witness stack should consist of exactly two // items: the signature, and the pubkey. if len(witness) != 2 { err := fmt.Sprintf("should have exactly two "+ "items in witness, instead have %v", len(witness)) return scriptError(ErrWitnessProgramMismatch, err) } // Now we'll resume execution as if it were a regular // p2pkh transaction. pkScript, err := payToPubKeyHashScript(vm.witnessProgram) if err != nil { return err } pops, err := parseScript(pkScript) if err != nil { return err } // Set the stack to the provided witness stack, then // append the pkScript generated above as the next // script to execute. vm.scripts = append(vm.scripts, pops) vm.SetStack(witness) case payToWitnessScriptHashDataSize: // P2WSH // Additionally, The witness stack MUST NOT be empty at // this point. if len(witness) == 0 { return scriptError(ErrWitnessProgramEmpty, "witness "+ "program empty passed empty witness") } // Obtain the witness script which should be the last // element in the passed stack. The size of the script // MUST NOT exceed the max script size. witnessScript := witness[len(witness)-1] if len(witnessScript) > MaxScriptSize { str := fmt.Sprintf("witnessScript size %d "+ "is larger than max allowed size %d", len(witnessScript), MaxScriptSize) return scriptError(ErrScriptTooBig, str) } // Ensure that the serialized pkScript at the end of // the witness stack matches the witness program. witnessHash := sha256.Sum256(witnessScript) if !bytes.Equal(witnessHash[:], vm.witnessProgram) { return scriptError(ErrWitnessProgramMismatch, "witness program hash mismatch") } // With all the validity checks passed, parse the // script into individual op-codes so w can execute it // as the next script. pops, err := parseScript(witnessScript) if err != nil { return err } // The hash matched successfully, so use the witness as // the stack, and set the witnessScript to be the next // script executed. vm.scripts = append(vm.scripts, pops) vm.SetStack(witness[:len(witness)-1]) default: errStr := fmt.Sprintf("length of witness program "+ "must either be %v or %v bytes, instead is %v bytes", payToWitnessPubKeyHashDataSize, payToWitnessScriptHashDataSize, len(vm.witnessProgram)) return scriptError(ErrWitnessProgramWrongLength, errStr) } } else if vm.hasFlag(ScriptVerifyDiscourageUpgradeableWitnessProgram) { errStr := fmt.Sprintf("new witness program versions "+ "invalid: %v", vm.witnessProgram) return scriptError(ErrDiscourageUpgradableWitnessProgram, errStr) } else { // If we encounter an unknown witness program version and we // aren't discouraging future unknown witness based soft-forks, // then we de-activate the segwit behavior within the VM for // the remainder of execution. vm.witnessProgram = nil } if vm.isWitnessVersionActive(0) { // All elements within the witness stack must not be greater // than the maximum bytes which are allowed to be pushed onto // the stack. for _, witElement := range vm.GetStack() { if len(witElement) > MaxScriptElementSize { str := fmt.Sprintf("element size %d exceeds "+ "max allowed size %d", len(witElement), MaxScriptElementSize) return scriptError(ErrElementTooBig, str) } } } return nil }
go
func (vm *Engine) verifyWitnessProgram(witness [][]byte) error { if vm.isWitnessVersionActive(0) { switch len(vm.witnessProgram) { case payToWitnessPubKeyHashDataSize: // P2WKH // The witness stack should consist of exactly two // items: the signature, and the pubkey. if len(witness) != 2 { err := fmt.Sprintf("should have exactly two "+ "items in witness, instead have %v", len(witness)) return scriptError(ErrWitnessProgramMismatch, err) } // Now we'll resume execution as if it were a regular // p2pkh transaction. pkScript, err := payToPubKeyHashScript(vm.witnessProgram) if err != nil { return err } pops, err := parseScript(pkScript) if err != nil { return err } // Set the stack to the provided witness stack, then // append the pkScript generated above as the next // script to execute. vm.scripts = append(vm.scripts, pops) vm.SetStack(witness) case payToWitnessScriptHashDataSize: // P2WSH // Additionally, The witness stack MUST NOT be empty at // this point. if len(witness) == 0 { return scriptError(ErrWitnessProgramEmpty, "witness "+ "program empty passed empty witness") } // Obtain the witness script which should be the last // element in the passed stack. The size of the script // MUST NOT exceed the max script size. witnessScript := witness[len(witness)-1] if len(witnessScript) > MaxScriptSize { str := fmt.Sprintf("witnessScript size %d "+ "is larger than max allowed size %d", len(witnessScript), MaxScriptSize) return scriptError(ErrScriptTooBig, str) } // Ensure that the serialized pkScript at the end of // the witness stack matches the witness program. witnessHash := sha256.Sum256(witnessScript) if !bytes.Equal(witnessHash[:], vm.witnessProgram) { return scriptError(ErrWitnessProgramMismatch, "witness program hash mismatch") } // With all the validity checks passed, parse the // script into individual op-codes so w can execute it // as the next script. pops, err := parseScript(witnessScript) if err != nil { return err } // The hash matched successfully, so use the witness as // the stack, and set the witnessScript to be the next // script executed. vm.scripts = append(vm.scripts, pops) vm.SetStack(witness[:len(witness)-1]) default: errStr := fmt.Sprintf("length of witness program "+ "must either be %v or %v bytes, instead is %v bytes", payToWitnessPubKeyHashDataSize, payToWitnessScriptHashDataSize, len(vm.witnessProgram)) return scriptError(ErrWitnessProgramWrongLength, errStr) } } else if vm.hasFlag(ScriptVerifyDiscourageUpgradeableWitnessProgram) { errStr := fmt.Sprintf("new witness program versions "+ "invalid: %v", vm.witnessProgram) return scriptError(ErrDiscourageUpgradableWitnessProgram, errStr) } else { // If we encounter an unknown witness program version and we // aren't discouraging future unknown witness based soft-forks, // then we de-activate the segwit behavior within the VM for // the remainder of execution. vm.witnessProgram = nil } if vm.isWitnessVersionActive(0) { // All elements within the witness stack must not be greater // than the maximum bytes which are allowed to be pushed onto // the stack. for _, witElement := range vm.GetStack() { if len(witElement) > MaxScriptElementSize { str := fmt.Sprintf("element size %d exceeds "+ "max allowed size %d", len(witElement), MaxScriptElementSize) return scriptError(ErrElementTooBig, str) } } } return nil }
[ "func", "(", "vm", "*", "Engine", ")", "verifyWitnessProgram", "(", "witness", "[", "]", "[", "]", "byte", ")", "error", "{", "if", "vm", ".", "isWitnessVersionActive", "(", "0", ")", "{", "switch", "len", "(", "vm", ".", "witnessProgram", ")", "{", "case", "payToWitnessPubKeyHashDataSize", ":", "// P2WKH", "// The witness stack should consist of exactly two", "// items: the signature, and the pubkey.", "if", "len", "(", "witness", ")", "!=", "2", "{", "err", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "len", "(", "witness", ")", ")", "\n", "return", "scriptError", "(", "ErrWitnessProgramMismatch", ",", "err", ")", "\n", "}", "\n\n", "// Now we'll resume execution as if it were a regular", "// p2pkh transaction.", "pkScript", ",", "err", ":=", "payToPubKeyHashScript", "(", "vm", ".", "witnessProgram", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "pops", ",", "err", ":=", "parseScript", "(", "pkScript", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Set the stack to the provided witness stack, then", "// append the pkScript generated above as the next", "// script to execute.", "vm", ".", "scripts", "=", "append", "(", "vm", ".", "scripts", ",", "pops", ")", "\n", "vm", ".", "SetStack", "(", "witness", ")", "\n\n", "case", "payToWitnessScriptHashDataSize", ":", "// P2WSH", "// Additionally, The witness stack MUST NOT be empty at", "// this point.", "if", "len", "(", "witness", ")", "==", "0", "{", "return", "scriptError", "(", "ErrWitnessProgramEmpty", ",", "\"", "\"", "+", "\"", "\"", ")", "\n", "}", "\n\n", "// Obtain the witness script which should be the last", "// element in the passed stack. The size of the script", "// MUST NOT exceed the max script size.", "witnessScript", ":=", "witness", "[", "len", "(", "witness", ")", "-", "1", "]", "\n", "if", "len", "(", "witnessScript", ")", ">", "MaxScriptSize", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "len", "(", "witnessScript", ")", ",", "MaxScriptSize", ")", "\n", "return", "scriptError", "(", "ErrScriptTooBig", ",", "str", ")", "\n", "}", "\n\n", "// Ensure that the serialized pkScript at the end of", "// the witness stack matches the witness program.", "witnessHash", ":=", "sha256", ".", "Sum256", "(", "witnessScript", ")", "\n", "if", "!", "bytes", ".", "Equal", "(", "witnessHash", "[", ":", "]", ",", "vm", ".", "witnessProgram", ")", "{", "return", "scriptError", "(", "ErrWitnessProgramMismatch", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// With all the validity checks passed, parse the", "// script into individual op-codes so w can execute it", "// as the next script.", "pops", ",", "err", ":=", "parseScript", "(", "witnessScript", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// The hash matched successfully, so use the witness as", "// the stack, and set the witnessScript to be the next", "// script executed.", "vm", ".", "scripts", "=", "append", "(", "vm", ".", "scripts", ",", "pops", ")", "\n", "vm", ".", "SetStack", "(", "witness", "[", ":", "len", "(", "witness", ")", "-", "1", "]", ")", "\n\n", "default", ":", "errStr", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "payToWitnessPubKeyHashDataSize", ",", "payToWitnessScriptHashDataSize", ",", "len", "(", "vm", ".", "witnessProgram", ")", ")", "\n", "return", "scriptError", "(", "ErrWitnessProgramWrongLength", ",", "errStr", ")", "\n", "}", "\n", "}", "else", "if", "vm", ".", "hasFlag", "(", "ScriptVerifyDiscourageUpgradeableWitnessProgram", ")", "{", "errStr", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "vm", ".", "witnessProgram", ")", "\n", "return", "scriptError", "(", "ErrDiscourageUpgradableWitnessProgram", ",", "errStr", ")", "\n", "}", "else", "{", "// If we encounter an unknown witness program version and we", "// aren't discouraging future unknown witness based soft-forks,", "// then we de-activate the segwit behavior within the VM for", "// the remainder of execution.", "vm", ".", "witnessProgram", "=", "nil", "\n", "}", "\n\n", "if", "vm", ".", "isWitnessVersionActive", "(", "0", ")", "{", "// All elements within the witness stack must not be greater", "// than the maximum bytes which are allowed to be pushed onto", "// the stack.", "for", "_", ",", "witElement", ":=", "range", "vm", ".", "GetStack", "(", ")", "{", "if", "len", "(", "witElement", ")", ">", "MaxScriptElementSize", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "len", "(", "witElement", ")", ",", "MaxScriptElementSize", ")", "\n", "return", "scriptError", "(", "ErrElementTooBig", ",", "str", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// verifyWitnessProgram validates the stored witness program using the passed // witness as input.
[ "verifyWitnessProgram", "validates", "the", "stored", "witness", "program", "using", "the", "passed", "witness", "as", "input", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/engine.go#L254-L359
train
btcsuite/btcd
txscript/engine.go
DisasmScript
func (vm *Engine) DisasmScript(idx int) (string, error) { if idx >= len(vm.scripts) { str := fmt.Sprintf("script index %d >= total scripts %d", idx, len(vm.scripts)) return "", scriptError(ErrInvalidIndex, str) } var disstr string for i := range vm.scripts[idx] { disstr = disstr + vm.disasm(idx, i) + "\n" } return disstr, nil }
go
func (vm *Engine) DisasmScript(idx int) (string, error) { if idx >= len(vm.scripts) { str := fmt.Sprintf("script index %d >= total scripts %d", idx, len(vm.scripts)) return "", scriptError(ErrInvalidIndex, str) } var disstr string for i := range vm.scripts[idx] { disstr = disstr + vm.disasm(idx, i) + "\n" } return disstr, nil }
[ "func", "(", "vm", "*", "Engine", ")", "DisasmScript", "(", "idx", "int", ")", "(", "string", ",", "error", ")", "{", "if", "idx", ">=", "len", "(", "vm", ".", "scripts", ")", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "idx", ",", "len", "(", "vm", ".", "scripts", ")", ")", "\n", "return", "\"", "\"", ",", "scriptError", "(", "ErrInvalidIndex", ",", "str", ")", "\n", "}", "\n\n", "var", "disstr", "string", "\n", "for", "i", ":=", "range", "vm", ".", "scripts", "[", "idx", "]", "{", "disstr", "=", "disstr", "+", "vm", ".", "disasm", "(", "idx", ",", "i", ")", "+", "\"", "\\n", "\"", "\n", "}", "\n", "return", "disstr", ",", "nil", "\n", "}" ]
// DisasmScript returns the disassembly string for the script at the requested // offset index. Index 0 is the signature script and 1 is the public key // script.
[ "DisasmScript", "returns", "the", "disassembly", "string", "for", "the", "script", "at", "the", "requested", "offset", "index", ".", "Index", "0", "is", "the", "signature", "script", "and", "1", "is", "the", "public", "key", "script", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/engine.go#L374-L386
train
btcsuite/btcd
txscript/engine.go
CheckErrorCondition
func (vm *Engine) CheckErrorCondition(finalScript bool) error { // Check execution is actually done. When pc is past the end of script // array there are no more scripts to run. if vm.scriptIdx < len(vm.scripts) { return scriptError(ErrScriptUnfinished, "error check when script unfinished") } // If we're in version zero witness execution mode, and this was the // final script, then the stack MUST be clean in order to maintain // compatibility with BIP16. if finalScript && vm.isWitnessVersionActive(0) && vm.dstack.Depth() != 1 { return scriptError(ErrEvalFalse, "witness program must "+ "have clean stack") } if finalScript && vm.hasFlag(ScriptVerifyCleanStack) && vm.dstack.Depth() != 1 { str := fmt.Sprintf("stack contains %d unexpected items", vm.dstack.Depth()-1) return scriptError(ErrCleanStack, str) } else if vm.dstack.Depth() < 1 { return scriptError(ErrEmptyStack, "stack empty at end of script execution") } v, err := vm.dstack.PopBool() if err != nil { return err } if !v { // Log interesting data. log.Tracef("%v", newLogClosure(func() string { dis0, _ := vm.DisasmScript(0) dis1, _ := vm.DisasmScript(1) return fmt.Sprintf("scripts failed: script0: %s\n"+ "script1: %s", dis0, dis1) })) return scriptError(ErrEvalFalse, "false stack entry at end of script execution") } return nil }
go
func (vm *Engine) CheckErrorCondition(finalScript bool) error { // Check execution is actually done. When pc is past the end of script // array there are no more scripts to run. if vm.scriptIdx < len(vm.scripts) { return scriptError(ErrScriptUnfinished, "error check when script unfinished") } // If we're in version zero witness execution mode, and this was the // final script, then the stack MUST be clean in order to maintain // compatibility with BIP16. if finalScript && vm.isWitnessVersionActive(0) && vm.dstack.Depth() != 1 { return scriptError(ErrEvalFalse, "witness program must "+ "have clean stack") } if finalScript && vm.hasFlag(ScriptVerifyCleanStack) && vm.dstack.Depth() != 1 { str := fmt.Sprintf("stack contains %d unexpected items", vm.dstack.Depth()-1) return scriptError(ErrCleanStack, str) } else if vm.dstack.Depth() < 1 { return scriptError(ErrEmptyStack, "stack empty at end of script execution") } v, err := vm.dstack.PopBool() if err != nil { return err } if !v { // Log interesting data. log.Tracef("%v", newLogClosure(func() string { dis0, _ := vm.DisasmScript(0) dis1, _ := vm.DisasmScript(1) return fmt.Sprintf("scripts failed: script0: %s\n"+ "script1: %s", dis0, dis1) })) return scriptError(ErrEvalFalse, "false stack entry at end of script execution") } return nil }
[ "func", "(", "vm", "*", "Engine", ")", "CheckErrorCondition", "(", "finalScript", "bool", ")", "error", "{", "// Check execution is actually done. When pc is past the end of script", "// array there are no more scripts to run.", "if", "vm", ".", "scriptIdx", "<", "len", "(", "vm", ".", "scripts", ")", "{", "return", "scriptError", "(", "ErrScriptUnfinished", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// If we're in version zero witness execution mode, and this was the", "// final script, then the stack MUST be clean in order to maintain", "// compatibility with BIP16.", "if", "finalScript", "&&", "vm", ".", "isWitnessVersionActive", "(", "0", ")", "&&", "vm", ".", "dstack", ".", "Depth", "(", ")", "!=", "1", "{", "return", "scriptError", "(", "ErrEvalFalse", ",", "\"", "\"", "+", "\"", "\"", ")", "\n", "}", "\n\n", "if", "finalScript", "&&", "vm", ".", "hasFlag", "(", "ScriptVerifyCleanStack", ")", "&&", "vm", ".", "dstack", ".", "Depth", "(", ")", "!=", "1", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "vm", ".", "dstack", ".", "Depth", "(", ")", "-", "1", ")", "\n", "return", "scriptError", "(", "ErrCleanStack", ",", "str", ")", "\n", "}", "else", "if", "vm", ".", "dstack", ".", "Depth", "(", ")", "<", "1", "{", "return", "scriptError", "(", "ErrEmptyStack", ",", "\"", "\"", ")", "\n", "}", "\n\n", "v", ",", "err", ":=", "vm", ".", "dstack", ".", "PopBool", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "!", "v", "{", "// Log interesting data.", "log", ".", "Tracef", "(", "\"", "\"", ",", "newLogClosure", "(", "func", "(", ")", "string", "{", "dis0", ",", "_", ":=", "vm", ".", "DisasmScript", "(", "0", ")", "\n", "dis1", ",", "_", ":=", "vm", ".", "DisasmScript", "(", "1", ")", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", "+", "\"", "\"", ",", "dis0", ",", "dis1", ")", "\n", "}", ")", ")", "\n", "return", "scriptError", "(", "ErrEvalFalse", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CheckErrorCondition returns nil if the running script has ended and was // successful, leaving a a true boolean on the stack. An error otherwise, // including if the script has not finished.
[ "CheckErrorCondition", "returns", "nil", "if", "the", "running", "script", "has", "ended", "and", "was", "successful", "leaving", "a", "a", "true", "boolean", "on", "the", "stack", ".", "An", "error", "otherwise", "including", "if", "the", "script", "has", "not", "finished", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/engine.go#L391-L434
train
btcsuite/btcd
txscript/engine.go
Step
func (vm *Engine) Step() (done bool, err error) { // Verify that it is pointing to a valid script address. err = vm.validPC() if err != nil { return true, err } opcode := &vm.scripts[vm.scriptIdx][vm.scriptOff] vm.scriptOff++ // Execute the opcode while taking into account several things such as // disabled opcodes, illegal opcodes, maximum allowed operations per // script, maximum script element sizes, and conditionals. err = vm.executeOpcode(opcode) if err != nil { return true, err } // The number of elements in the combination of the data and alt stacks // must not exceed the maximum number of stack elements allowed. combinedStackSize := vm.dstack.Depth() + vm.astack.Depth() if combinedStackSize > MaxStackSize { str := fmt.Sprintf("combined stack size %d > max allowed %d", combinedStackSize, MaxStackSize) return false, scriptError(ErrStackOverflow, str) } // Prepare for next instruction. if vm.scriptOff >= len(vm.scripts[vm.scriptIdx]) { // Illegal to have an `if' that straddles two scripts. if err == nil && len(vm.condStack) != 0 { return false, scriptError(ErrUnbalancedConditional, "end of script reached in conditional execution") } // Alt stack doesn't persist. _ = vm.astack.DropN(vm.astack.Depth()) vm.numOps = 0 // number of ops is per script. vm.scriptOff = 0 if vm.scriptIdx == 0 && vm.bip16 { vm.scriptIdx++ vm.savedFirstStack = vm.GetStack() } else if vm.scriptIdx == 1 && vm.bip16 { // Put us past the end for CheckErrorCondition() vm.scriptIdx++ // Check script ran successfully and pull the script // out of the first stack and execute that. err := vm.CheckErrorCondition(false) if err != nil { return false, err } script := vm.savedFirstStack[len(vm.savedFirstStack)-1] pops, err := parseScript(script) if err != nil { return false, err } vm.scripts = append(vm.scripts, pops) // Set stack to be the stack from first script minus the // script itself vm.SetStack(vm.savedFirstStack[:len(vm.savedFirstStack)-1]) } else if (vm.scriptIdx == 1 && vm.witnessProgram != nil) || (vm.scriptIdx == 2 && vm.witnessProgram != nil && vm.bip16) { // Nested P2SH. vm.scriptIdx++ witness := vm.tx.TxIn[vm.txIdx].Witness if err := vm.verifyWitnessProgram(witness); err != nil { return false, err } } else { vm.scriptIdx++ } // there are zero length scripts in the wild if vm.scriptIdx < len(vm.scripts) && vm.scriptOff >= len(vm.scripts[vm.scriptIdx]) { vm.scriptIdx++ } vm.lastCodeSep = 0 if vm.scriptIdx >= len(vm.scripts) { return true, nil } } return false, nil }
go
func (vm *Engine) Step() (done bool, err error) { // Verify that it is pointing to a valid script address. err = vm.validPC() if err != nil { return true, err } opcode := &vm.scripts[vm.scriptIdx][vm.scriptOff] vm.scriptOff++ // Execute the opcode while taking into account several things such as // disabled opcodes, illegal opcodes, maximum allowed operations per // script, maximum script element sizes, and conditionals. err = vm.executeOpcode(opcode) if err != nil { return true, err } // The number of elements in the combination of the data and alt stacks // must not exceed the maximum number of stack elements allowed. combinedStackSize := vm.dstack.Depth() + vm.astack.Depth() if combinedStackSize > MaxStackSize { str := fmt.Sprintf("combined stack size %d > max allowed %d", combinedStackSize, MaxStackSize) return false, scriptError(ErrStackOverflow, str) } // Prepare for next instruction. if vm.scriptOff >= len(vm.scripts[vm.scriptIdx]) { // Illegal to have an `if' that straddles two scripts. if err == nil && len(vm.condStack) != 0 { return false, scriptError(ErrUnbalancedConditional, "end of script reached in conditional execution") } // Alt stack doesn't persist. _ = vm.astack.DropN(vm.astack.Depth()) vm.numOps = 0 // number of ops is per script. vm.scriptOff = 0 if vm.scriptIdx == 0 && vm.bip16 { vm.scriptIdx++ vm.savedFirstStack = vm.GetStack() } else if vm.scriptIdx == 1 && vm.bip16 { // Put us past the end for CheckErrorCondition() vm.scriptIdx++ // Check script ran successfully and pull the script // out of the first stack and execute that. err := vm.CheckErrorCondition(false) if err != nil { return false, err } script := vm.savedFirstStack[len(vm.savedFirstStack)-1] pops, err := parseScript(script) if err != nil { return false, err } vm.scripts = append(vm.scripts, pops) // Set stack to be the stack from first script minus the // script itself vm.SetStack(vm.savedFirstStack[:len(vm.savedFirstStack)-1]) } else if (vm.scriptIdx == 1 && vm.witnessProgram != nil) || (vm.scriptIdx == 2 && vm.witnessProgram != nil && vm.bip16) { // Nested P2SH. vm.scriptIdx++ witness := vm.tx.TxIn[vm.txIdx].Witness if err := vm.verifyWitnessProgram(witness); err != nil { return false, err } } else { vm.scriptIdx++ } // there are zero length scripts in the wild if vm.scriptIdx < len(vm.scripts) && vm.scriptOff >= len(vm.scripts[vm.scriptIdx]) { vm.scriptIdx++ } vm.lastCodeSep = 0 if vm.scriptIdx >= len(vm.scripts) { return true, nil } } return false, nil }
[ "func", "(", "vm", "*", "Engine", ")", "Step", "(", ")", "(", "done", "bool", ",", "err", "error", ")", "{", "// Verify that it is pointing to a valid script address.", "err", "=", "vm", ".", "validPC", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "true", ",", "err", "\n", "}", "\n", "opcode", ":=", "&", "vm", ".", "scripts", "[", "vm", ".", "scriptIdx", "]", "[", "vm", ".", "scriptOff", "]", "\n", "vm", ".", "scriptOff", "++", "\n\n", "// Execute the opcode while taking into account several things such as", "// disabled opcodes, illegal opcodes, maximum allowed operations per", "// script, maximum script element sizes, and conditionals.", "err", "=", "vm", ".", "executeOpcode", "(", "opcode", ")", "\n", "if", "err", "!=", "nil", "{", "return", "true", ",", "err", "\n", "}", "\n\n", "// The number of elements in the combination of the data and alt stacks", "// must not exceed the maximum number of stack elements allowed.", "combinedStackSize", ":=", "vm", ".", "dstack", ".", "Depth", "(", ")", "+", "vm", ".", "astack", ".", "Depth", "(", ")", "\n", "if", "combinedStackSize", ">", "MaxStackSize", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "combinedStackSize", ",", "MaxStackSize", ")", "\n", "return", "false", ",", "scriptError", "(", "ErrStackOverflow", ",", "str", ")", "\n", "}", "\n\n", "// Prepare for next instruction.", "if", "vm", ".", "scriptOff", ">=", "len", "(", "vm", ".", "scripts", "[", "vm", ".", "scriptIdx", "]", ")", "{", "// Illegal to have an `if' that straddles two scripts.", "if", "err", "==", "nil", "&&", "len", "(", "vm", ".", "condStack", ")", "!=", "0", "{", "return", "false", ",", "scriptError", "(", "ErrUnbalancedConditional", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Alt stack doesn't persist.", "_", "=", "vm", ".", "astack", ".", "DropN", "(", "vm", ".", "astack", ".", "Depth", "(", ")", ")", "\n\n", "vm", ".", "numOps", "=", "0", "// number of ops is per script.", "\n", "vm", ".", "scriptOff", "=", "0", "\n", "if", "vm", ".", "scriptIdx", "==", "0", "&&", "vm", ".", "bip16", "{", "vm", ".", "scriptIdx", "++", "\n", "vm", ".", "savedFirstStack", "=", "vm", ".", "GetStack", "(", ")", "\n", "}", "else", "if", "vm", ".", "scriptIdx", "==", "1", "&&", "vm", ".", "bip16", "{", "// Put us past the end for CheckErrorCondition()", "vm", ".", "scriptIdx", "++", "\n", "// Check script ran successfully and pull the script", "// out of the first stack and execute that.", "err", ":=", "vm", ".", "CheckErrorCondition", "(", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n\n", "script", ":=", "vm", ".", "savedFirstStack", "[", "len", "(", "vm", ".", "savedFirstStack", ")", "-", "1", "]", "\n", "pops", ",", "err", ":=", "parseScript", "(", "script", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "vm", ".", "scripts", "=", "append", "(", "vm", ".", "scripts", ",", "pops", ")", "\n\n", "// Set stack to be the stack from first script minus the", "// script itself", "vm", ".", "SetStack", "(", "vm", ".", "savedFirstStack", "[", ":", "len", "(", "vm", ".", "savedFirstStack", ")", "-", "1", "]", ")", "\n", "}", "else", "if", "(", "vm", ".", "scriptIdx", "==", "1", "&&", "vm", ".", "witnessProgram", "!=", "nil", ")", "||", "(", "vm", ".", "scriptIdx", "==", "2", "&&", "vm", ".", "witnessProgram", "!=", "nil", "&&", "vm", ".", "bip16", ")", "{", "// Nested P2SH.", "vm", ".", "scriptIdx", "++", "\n\n", "witness", ":=", "vm", ".", "tx", ".", "TxIn", "[", "vm", ".", "txIdx", "]", ".", "Witness", "\n", "if", "err", ":=", "vm", ".", "verifyWitnessProgram", "(", "witness", ")", ";", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "}", "else", "{", "vm", ".", "scriptIdx", "++", "\n", "}", "\n", "// there are zero length scripts in the wild", "if", "vm", ".", "scriptIdx", "<", "len", "(", "vm", ".", "scripts", ")", "&&", "vm", ".", "scriptOff", ">=", "len", "(", "vm", ".", "scripts", "[", "vm", ".", "scriptIdx", "]", ")", "{", "vm", ".", "scriptIdx", "++", "\n", "}", "\n", "vm", ".", "lastCodeSep", "=", "0", "\n", "if", "vm", ".", "scriptIdx", ">=", "len", "(", "vm", ".", "scripts", ")", "{", "return", "true", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "false", ",", "nil", "\n", "}" ]
// Step will execute the next instruction and move the program counter to the // next opcode in the script, or the next script if the current has ended. Step // will return true in the case that the last opcode was successfully executed. // // The result of calling Step or any other method is undefined if an error is // returned.
[ "Step", "will", "execute", "the", "next", "instruction", "and", "move", "the", "program", "counter", "to", "the", "next", "opcode", "in", "the", "script", "or", "the", "next", "script", "if", "the", "current", "has", "ended", ".", "Step", "will", "return", "true", "in", "the", "case", "that", "the", "last", "opcode", "was", "successfully", "executed", ".", "The", "result", "of", "calling", "Step", "or", "any", "other", "method", "is", "undefined", "if", "an", "error", "is", "returned", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/engine.go#L442-L526
train
btcsuite/btcd
txscript/engine.go
Execute
func (vm *Engine) Execute() (err error) { done := false for !done { log.Tracef("%v", newLogClosure(func() string { dis, err := vm.DisasmPC() if err != nil { return fmt.Sprintf("stepping (%v)", err) } return fmt.Sprintf("stepping %v", dis) })) done, err = vm.Step() if err != nil { return err } log.Tracef("%v", newLogClosure(func() string { var dstr, astr string // if we're tracing, dump the stacks. if vm.dstack.Depth() != 0 { dstr = "Stack:\n" + vm.dstack.String() } if vm.astack.Depth() != 0 { astr = "AltStack:\n" + vm.astack.String() } return dstr + astr })) } return vm.CheckErrorCondition(true) }
go
func (vm *Engine) Execute() (err error) { done := false for !done { log.Tracef("%v", newLogClosure(func() string { dis, err := vm.DisasmPC() if err != nil { return fmt.Sprintf("stepping (%v)", err) } return fmt.Sprintf("stepping %v", dis) })) done, err = vm.Step() if err != nil { return err } log.Tracef("%v", newLogClosure(func() string { var dstr, astr string // if we're tracing, dump the stacks. if vm.dstack.Depth() != 0 { dstr = "Stack:\n" + vm.dstack.String() } if vm.astack.Depth() != 0 { astr = "AltStack:\n" + vm.astack.String() } return dstr + astr })) } return vm.CheckErrorCondition(true) }
[ "func", "(", "vm", "*", "Engine", ")", "Execute", "(", ")", "(", "err", "error", ")", "{", "done", ":=", "false", "\n", "for", "!", "done", "{", "log", ".", "Tracef", "(", "\"", "\"", ",", "newLogClosure", "(", "func", "(", ")", "string", "{", "dis", ",", "err", ":=", "vm", ".", "DisasmPC", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "dis", ")", "\n", "}", ")", ")", "\n\n", "done", ",", "err", "=", "vm", ".", "Step", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "log", ".", "Tracef", "(", "\"", "\"", ",", "newLogClosure", "(", "func", "(", ")", "string", "{", "var", "dstr", ",", "astr", "string", "\n\n", "// if we're tracing, dump the stacks.", "if", "vm", ".", "dstack", ".", "Depth", "(", ")", "!=", "0", "{", "dstr", "=", "\"", "\\n", "\"", "+", "vm", ".", "dstack", ".", "String", "(", ")", "\n", "}", "\n", "if", "vm", ".", "astack", ".", "Depth", "(", ")", "!=", "0", "{", "astr", "=", "\"", "\\n", "\"", "+", "vm", ".", "astack", ".", "String", "(", ")", "\n", "}", "\n\n", "return", "dstr", "+", "astr", "\n", "}", ")", ")", "\n", "}", "\n\n", "return", "vm", ".", "CheckErrorCondition", "(", "true", ")", "\n", "}" ]
// Execute will execute all scripts in the script engine and return either nil // for successful validation or an error if one occurred.
[ "Execute", "will", "execute", "all", "scripts", "in", "the", "script", "engine", "and", "return", "either", "nil", "for", "successful", "validation", "or", "an", "error", "if", "one", "occurred", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/engine.go#L530-L561
train
btcsuite/btcd
txscript/engine.go
subScript
func (vm *Engine) subScript() []parsedOpcode { return vm.scripts[vm.scriptIdx][vm.lastCodeSep:] }
go
func (vm *Engine) subScript() []parsedOpcode { return vm.scripts[vm.scriptIdx][vm.lastCodeSep:] }
[ "func", "(", "vm", "*", "Engine", ")", "subScript", "(", ")", "[", "]", "parsedOpcode", "{", "return", "vm", ".", "scripts", "[", "vm", ".", "scriptIdx", "]", "[", "vm", ".", "lastCodeSep", ":", "]", "\n", "}" ]
// subScript returns the script since the last OP_CODESEPARATOR.
[ "subScript", "returns", "the", "script", "since", "the", "last", "OP_CODESEPARATOR", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/engine.go#L564-L566
train
btcsuite/btcd
txscript/engine.go
checkHashTypeEncoding
func (vm *Engine) checkHashTypeEncoding(hashType SigHashType) error { if !vm.hasFlag(ScriptVerifyStrictEncoding) { return nil } sigHashType := hashType & ^SigHashAnyOneCanPay if sigHashType < SigHashAll || sigHashType > SigHashSingle { str := fmt.Sprintf("invalid hash type 0x%x", hashType) return scriptError(ErrInvalidSigHashType, str) } return nil }
go
func (vm *Engine) checkHashTypeEncoding(hashType SigHashType) error { if !vm.hasFlag(ScriptVerifyStrictEncoding) { return nil } sigHashType := hashType & ^SigHashAnyOneCanPay if sigHashType < SigHashAll || sigHashType > SigHashSingle { str := fmt.Sprintf("invalid hash type 0x%x", hashType) return scriptError(ErrInvalidSigHashType, str) } return nil }
[ "func", "(", "vm", "*", "Engine", ")", "checkHashTypeEncoding", "(", "hashType", "SigHashType", ")", "error", "{", "if", "!", "vm", ".", "hasFlag", "(", "ScriptVerifyStrictEncoding", ")", "{", "return", "nil", "\n", "}", "\n\n", "sigHashType", ":=", "hashType", "&", "^", "SigHashAnyOneCanPay", "\n", "if", "sigHashType", "<", "SigHashAll", "||", "sigHashType", ">", "SigHashSingle", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "hashType", ")", "\n", "return", "scriptError", "(", "ErrInvalidSigHashType", ",", "str", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// checkHashTypeEncoding returns whether or not the passed hashtype adheres to // the strict encoding requirements if enabled.
[ "checkHashTypeEncoding", "returns", "whether", "or", "not", "the", "passed", "hashtype", "adheres", "to", "the", "strict", "encoding", "requirements", "if", "enabled", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/engine.go#L570-L581
train
btcsuite/btcd
txscript/engine.go
checkPubKeyEncoding
func (vm *Engine) checkPubKeyEncoding(pubKey []byte) error { if vm.hasFlag(ScriptVerifyWitnessPubKeyType) && vm.isWitnessVersionActive(0) && !btcec.IsCompressedPubKey(pubKey) { str := "only uncompressed keys are accepted post-segwit" return scriptError(ErrWitnessPubKeyType, str) } if !vm.hasFlag(ScriptVerifyStrictEncoding) { return nil } if len(pubKey) == 33 && (pubKey[0] == 0x02 || pubKey[0] == 0x03) { // Compressed return nil } if len(pubKey) == 65 && pubKey[0] == 0x04 { // Uncompressed return nil } return scriptError(ErrPubKeyType, "unsupported public key type") }
go
func (vm *Engine) checkPubKeyEncoding(pubKey []byte) error { if vm.hasFlag(ScriptVerifyWitnessPubKeyType) && vm.isWitnessVersionActive(0) && !btcec.IsCompressedPubKey(pubKey) { str := "only uncompressed keys are accepted post-segwit" return scriptError(ErrWitnessPubKeyType, str) } if !vm.hasFlag(ScriptVerifyStrictEncoding) { return nil } if len(pubKey) == 33 && (pubKey[0] == 0x02 || pubKey[0] == 0x03) { // Compressed return nil } if len(pubKey) == 65 && pubKey[0] == 0x04 { // Uncompressed return nil } return scriptError(ErrPubKeyType, "unsupported public key type") }
[ "func", "(", "vm", "*", "Engine", ")", "checkPubKeyEncoding", "(", "pubKey", "[", "]", "byte", ")", "error", "{", "if", "vm", ".", "hasFlag", "(", "ScriptVerifyWitnessPubKeyType", ")", "&&", "vm", ".", "isWitnessVersionActive", "(", "0", ")", "&&", "!", "btcec", ".", "IsCompressedPubKey", "(", "pubKey", ")", "{", "str", ":=", "\"", "\"", "\n", "return", "scriptError", "(", "ErrWitnessPubKeyType", ",", "str", ")", "\n", "}", "\n\n", "if", "!", "vm", ".", "hasFlag", "(", "ScriptVerifyStrictEncoding", ")", "{", "return", "nil", "\n", "}", "\n\n", "if", "len", "(", "pubKey", ")", "==", "33", "&&", "(", "pubKey", "[", "0", "]", "==", "0x02", "||", "pubKey", "[", "0", "]", "==", "0x03", ")", "{", "// Compressed", "return", "nil", "\n", "}", "\n", "if", "len", "(", "pubKey", ")", "==", "65", "&&", "pubKey", "[", "0", "]", "==", "0x04", "{", "// Uncompressed", "return", "nil", "\n", "}", "\n\n", "return", "scriptError", "(", "ErrPubKeyType", ",", "\"", "\"", ")", "\n", "}" ]
// checkPubKeyEncoding returns whether or not the passed public key adheres to // the strict encoding requirements if enabled.
[ "checkPubKeyEncoding", "returns", "whether", "or", "not", "the", "passed", "public", "key", "adheres", "to", "the", "strict", "encoding", "requirements", "if", "enabled", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/engine.go#L585-L607
train
btcsuite/btcd
txscript/engine.go
getStack
func getStack(stack *stack) [][]byte { array := make([][]byte, stack.Depth()) for i := range array { // PeekByteArry can't fail due to overflow, already checked array[len(array)-i-1], _ = stack.PeekByteArray(int32(i)) } return array }
go
func getStack(stack *stack) [][]byte { array := make([][]byte, stack.Depth()) for i := range array { // PeekByteArry can't fail due to overflow, already checked array[len(array)-i-1], _ = stack.PeekByteArray(int32(i)) } return array }
[ "func", "getStack", "(", "stack", "*", "stack", ")", "[", "]", "[", "]", "byte", "{", "array", ":=", "make", "(", "[", "]", "[", "]", "byte", ",", "stack", ".", "Depth", "(", ")", ")", "\n", "for", "i", ":=", "range", "array", "{", "// PeekByteArry can't fail due to overflow, already checked", "array", "[", "len", "(", "array", ")", "-", "i", "-", "1", "]", ",", "_", "=", "stack", ".", "PeekByteArray", "(", "int32", "(", "i", ")", ")", "\n", "}", "\n", "return", "array", "\n", "}" ]
// getStack returns the contents of stack as a byte array bottom up
[ "getStack", "returns", "the", "contents", "of", "stack", "as", "a", "byte", "array", "bottom", "up" ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/engine.go#L808-L815
train
btcsuite/btcd
txscript/engine.go
setStack
func setStack(stack *stack, data [][]byte) { // This can not error. Only errors are for invalid arguments. _ = stack.DropN(stack.Depth()) for i := range data { stack.PushByteArray(data[i]) } }
go
func setStack(stack *stack, data [][]byte) { // This can not error. Only errors are for invalid arguments. _ = stack.DropN(stack.Depth()) for i := range data { stack.PushByteArray(data[i]) } }
[ "func", "setStack", "(", "stack", "*", "stack", ",", "data", "[", "]", "[", "]", "byte", ")", "{", "// This can not error. Only errors are for invalid arguments.", "_", "=", "stack", ".", "DropN", "(", "stack", ".", "Depth", "(", ")", ")", "\n\n", "for", "i", ":=", "range", "data", "{", "stack", ".", "PushByteArray", "(", "data", "[", "i", "]", ")", "\n", "}", "\n", "}" ]
// setStack sets the stack to the contents of the array where the last item in // the array is the top item in the stack.
[ "setStack", "sets", "the", "stack", "to", "the", "contents", "of", "the", "array", "where", "the", "last", "item", "in", "the", "array", "is", "the", "top", "item", "in", "the", "stack", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/engine.go#L819-L826
train
btcsuite/btcd
database/cmd/dbtool/globalconfig.go
setupGlobalConfig
func setupGlobalConfig() error { // Multiple networks can't be selected simultaneously. // Count number of network flags passed; assign active network params // while we're at it numNets := 0 if cfg.TestNet3 { numNets++ activeNetParams = &chaincfg.TestNet3Params } if cfg.RegressionTest { numNets++ activeNetParams = &chaincfg.RegressionNetParams } if cfg.SimNet { numNets++ activeNetParams = &chaincfg.SimNetParams } if numNets > 1 { return errors.New("The testnet, regtest, and simnet params " + "can't be used together -- choose one of the three") } // Validate database type. if !validDbType(cfg.DbType) { str := "The specified database type [%v] is invalid -- " + "supported types %v" return fmt.Errorf(str, cfg.DbType, knownDbTypes) } // Append the network type to the data directory so it is "namespaced" // per network. In addition to the block database, there are other // pieces of data that are saved to disk such as address manager state. // All data is specific to a network, so namespacing the data directory // means each individual piece of serialized data does not have to // worry about changing names per network and such. cfg.DataDir = filepath.Join(cfg.DataDir, netName(activeNetParams)) return nil }
go
func setupGlobalConfig() error { // Multiple networks can't be selected simultaneously. // Count number of network flags passed; assign active network params // while we're at it numNets := 0 if cfg.TestNet3 { numNets++ activeNetParams = &chaincfg.TestNet3Params } if cfg.RegressionTest { numNets++ activeNetParams = &chaincfg.RegressionNetParams } if cfg.SimNet { numNets++ activeNetParams = &chaincfg.SimNetParams } if numNets > 1 { return errors.New("The testnet, regtest, and simnet params " + "can't be used together -- choose one of the three") } // Validate database type. if !validDbType(cfg.DbType) { str := "The specified database type [%v] is invalid -- " + "supported types %v" return fmt.Errorf(str, cfg.DbType, knownDbTypes) } // Append the network type to the data directory so it is "namespaced" // per network. In addition to the block database, there are other // pieces of data that are saved to disk such as address manager state. // All data is specific to a network, so namespacing the data directory // means each individual piece of serialized data does not have to // worry about changing names per network and such. cfg.DataDir = filepath.Join(cfg.DataDir, netName(activeNetParams)) return nil }
[ "func", "setupGlobalConfig", "(", ")", "error", "{", "// Multiple networks can't be selected simultaneously.", "// Count number of network flags passed; assign active network params", "// while we're at it", "numNets", ":=", "0", "\n", "if", "cfg", ".", "TestNet3", "{", "numNets", "++", "\n", "activeNetParams", "=", "&", "chaincfg", ".", "TestNet3Params", "\n", "}", "\n", "if", "cfg", ".", "RegressionTest", "{", "numNets", "++", "\n", "activeNetParams", "=", "&", "chaincfg", ".", "RegressionNetParams", "\n", "}", "\n", "if", "cfg", ".", "SimNet", "{", "numNets", "++", "\n", "activeNetParams", "=", "&", "chaincfg", ".", "SimNetParams", "\n", "}", "\n", "if", "numNets", ">", "1", "{", "return", "errors", ".", "New", "(", "\"", "\"", "+", "\"", "\"", ")", "\n", "}", "\n\n", "// Validate database type.", "if", "!", "validDbType", "(", "cfg", ".", "DbType", ")", "{", "str", ":=", "\"", "\"", "+", "\"", "\"", "\n", "return", "fmt", ".", "Errorf", "(", "str", ",", "cfg", ".", "DbType", ",", "knownDbTypes", ")", "\n", "}", "\n\n", "// Append the network type to the data directory so it is \"namespaced\"", "// per network. In addition to the block database, there are other", "// pieces of data that are saved to disk such as address manager state.", "// All data is specific to a network, so namespacing the data directory", "// means each individual piece of serialized data does not have to", "// worry about changing names per network and such.", "cfg", ".", "DataDir", "=", "filepath", ".", "Join", "(", "cfg", ".", "DataDir", ",", "netName", "(", "activeNetParams", ")", ")", "\n\n", "return", "nil", "\n", "}" ]
// setupGlobalConfig examine the global configuration options for any conditions // which are invalid as well as performs any addition setup necessary after the // initial parse.
[ "setupGlobalConfig", "examine", "the", "global", "configuration", "options", "for", "any", "conditions", "which", "are", "invalid", "as", "well", "as", "performs", "any", "addition", "setup", "necessary", "after", "the", "initial", "parse", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/cmd/dbtool/globalconfig.go#L83-L121
train
btcsuite/btcd
blockchain/scriptval.go
sendResult
func (v *txValidator) sendResult(result error) { select { case v.resultChan <- result: case <-v.quitChan: } }
go
func (v *txValidator) sendResult(result error) { select { case v.resultChan <- result: case <-v.quitChan: } }
[ "func", "(", "v", "*", "txValidator", ")", "sendResult", "(", "result", "error", ")", "{", "select", "{", "case", "v", ".", "resultChan", "<-", "result", ":", "case", "<-", "v", ".", "quitChan", ":", "}", "\n", "}" ]
// sendResult sends the result of a script pair validation on the internal // result channel while respecting the quit channel. This allows orderly // shutdown when the validation process is aborted early due to a validation // error in one of the other goroutines.
[ "sendResult", "sends", "the", "result", "of", "a", "script", "pair", "validation", "on", "the", "internal", "result", "channel", "while", "respecting", "the", "quit", "channel", ".", "This", "allows", "orderly", "shutdown", "when", "the", "validation", "process", "is", "aborted", "early", "due", "to", "a", "validation", "error", "in", "one", "of", "the", "other", "goroutines", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/scriptval.go#L43-L48
train
btcsuite/btcd
blockchain/scriptval.go
validateHandler
func (v *txValidator) validateHandler() { out: for { select { case txVI := <-v.validateChan: // Ensure the referenced input utxo is available. txIn := txVI.txIn utxo := v.utxoView.LookupEntry(txIn.PreviousOutPoint) if utxo == nil { str := fmt.Sprintf("unable to find unspent "+ "output %v referenced from "+ "transaction %s:%d", txIn.PreviousOutPoint, txVI.tx.Hash(), txVI.txInIndex) err := ruleError(ErrMissingTxOut, str) v.sendResult(err) break out } // Create a new script engine for the script pair. sigScript := txIn.SignatureScript witness := txIn.Witness pkScript := utxo.PkScript() inputAmount := utxo.Amount() vm, err := txscript.NewEngine(pkScript, txVI.tx.MsgTx(), txVI.txInIndex, v.flags, v.sigCache, txVI.sigHashes, inputAmount) if err != nil { str := fmt.Sprintf("failed to parse input "+ "%s:%d which references output %v - "+ "%v (input witness %x, input script "+ "bytes %x, prev output script bytes %x)", txVI.tx.Hash(), txVI.txInIndex, txIn.PreviousOutPoint, err, witness, sigScript, pkScript) err := ruleError(ErrScriptMalformed, str) v.sendResult(err) break out } // Execute the script pair. if err := vm.Execute(); err != nil { str := fmt.Sprintf("failed to validate input "+ "%s:%d which references output %v - "+ "%v (input witness %x, input script "+ "bytes %x, prev output script bytes %x)", txVI.tx.Hash(), txVI.txInIndex, txIn.PreviousOutPoint, err, witness, sigScript, pkScript) err := ruleError(ErrScriptValidation, str) v.sendResult(err) break out } // Validation succeeded. v.sendResult(nil) case <-v.quitChan: break out } } }
go
func (v *txValidator) validateHandler() { out: for { select { case txVI := <-v.validateChan: // Ensure the referenced input utxo is available. txIn := txVI.txIn utxo := v.utxoView.LookupEntry(txIn.PreviousOutPoint) if utxo == nil { str := fmt.Sprintf("unable to find unspent "+ "output %v referenced from "+ "transaction %s:%d", txIn.PreviousOutPoint, txVI.tx.Hash(), txVI.txInIndex) err := ruleError(ErrMissingTxOut, str) v.sendResult(err) break out } // Create a new script engine for the script pair. sigScript := txIn.SignatureScript witness := txIn.Witness pkScript := utxo.PkScript() inputAmount := utxo.Amount() vm, err := txscript.NewEngine(pkScript, txVI.tx.MsgTx(), txVI.txInIndex, v.flags, v.sigCache, txVI.sigHashes, inputAmount) if err != nil { str := fmt.Sprintf("failed to parse input "+ "%s:%d which references output %v - "+ "%v (input witness %x, input script "+ "bytes %x, prev output script bytes %x)", txVI.tx.Hash(), txVI.txInIndex, txIn.PreviousOutPoint, err, witness, sigScript, pkScript) err := ruleError(ErrScriptMalformed, str) v.sendResult(err) break out } // Execute the script pair. if err := vm.Execute(); err != nil { str := fmt.Sprintf("failed to validate input "+ "%s:%d which references output %v - "+ "%v (input witness %x, input script "+ "bytes %x, prev output script bytes %x)", txVI.tx.Hash(), txVI.txInIndex, txIn.PreviousOutPoint, err, witness, sigScript, pkScript) err := ruleError(ErrScriptValidation, str) v.sendResult(err) break out } // Validation succeeded. v.sendResult(nil) case <-v.quitChan: break out } } }
[ "func", "(", "v", "*", "txValidator", ")", "validateHandler", "(", ")", "{", "out", ":", "for", "{", "select", "{", "case", "txVI", ":=", "<-", "v", ".", "validateChan", ":", "// Ensure the referenced input utxo is available.", "txIn", ":=", "txVI", ".", "txIn", "\n", "utxo", ":=", "v", ".", "utxoView", ".", "LookupEntry", "(", "txIn", ".", "PreviousOutPoint", ")", "\n", "if", "utxo", "==", "nil", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ",", "txIn", ".", "PreviousOutPoint", ",", "txVI", ".", "tx", ".", "Hash", "(", ")", ",", "txVI", ".", "txInIndex", ")", "\n", "err", ":=", "ruleError", "(", "ErrMissingTxOut", ",", "str", ")", "\n", "v", ".", "sendResult", "(", "err", ")", "\n", "break", "out", "\n", "}", "\n\n", "// Create a new script engine for the script pair.", "sigScript", ":=", "txIn", ".", "SignatureScript", "\n", "witness", ":=", "txIn", ".", "Witness", "\n", "pkScript", ":=", "utxo", ".", "PkScript", "(", ")", "\n", "inputAmount", ":=", "utxo", ".", "Amount", "(", ")", "\n", "vm", ",", "err", ":=", "txscript", ".", "NewEngine", "(", "pkScript", ",", "txVI", ".", "tx", ".", "MsgTx", "(", ")", ",", "txVI", ".", "txInIndex", ",", "v", ".", "flags", ",", "v", ".", "sigCache", ",", "txVI", ".", "sigHashes", ",", "inputAmount", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ",", "txVI", ".", "tx", ".", "Hash", "(", ")", ",", "txVI", ".", "txInIndex", ",", "txIn", ".", "PreviousOutPoint", ",", "err", ",", "witness", ",", "sigScript", ",", "pkScript", ")", "\n", "err", ":=", "ruleError", "(", "ErrScriptMalformed", ",", "str", ")", "\n", "v", ".", "sendResult", "(", "err", ")", "\n", "break", "out", "\n", "}", "\n\n", "// Execute the script pair.", "if", "err", ":=", "vm", ".", "Execute", "(", ")", ";", "err", "!=", "nil", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ",", "txVI", ".", "tx", ".", "Hash", "(", ")", ",", "txVI", ".", "txInIndex", ",", "txIn", ".", "PreviousOutPoint", ",", "err", ",", "witness", ",", "sigScript", ",", "pkScript", ")", "\n", "err", ":=", "ruleError", "(", "ErrScriptValidation", ",", "str", ")", "\n", "v", ".", "sendResult", "(", "err", ")", "\n", "break", "out", "\n", "}", "\n\n", "// Validation succeeded.", "v", ".", "sendResult", "(", "nil", ")", "\n\n", "case", "<-", "v", ".", "quitChan", ":", "break", "out", "\n", "}", "\n", "}", "\n", "}" ]
// validateHandler consumes items to validate from the internal validate channel // and returns the result of the validation on the internal result channel. It // must be run as a goroutine.
[ "validateHandler", "consumes", "items", "to", "validate", "from", "the", "internal", "validate", "channel", "and", "returns", "the", "result", "of", "the", "validation", "on", "the", "internal", "result", "channel", ".", "It", "must", "be", "run", "as", "a", "goroutine", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/scriptval.go#L53-L114
train
btcsuite/btcd
blockchain/scriptval.go
Validate
func (v *txValidator) Validate(items []*txValidateItem) error { if len(items) == 0 { return nil } // Limit the number of goroutines to do script validation based on the // number of processor cores. This helps ensure the system stays // reasonably responsive under heavy load. maxGoRoutines := runtime.NumCPU() * 3 if maxGoRoutines <= 0 { maxGoRoutines = 1 } if maxGoRoutines > len(items) { maxGoRoutines = len(items) } // Start up validation handlers that are used to asynchronously // validate each transaction input. for i := 0; i < maxGoRoutines; i++ { go v.validateHandler() } // Validate each of the inputs. The quit channel is closed when any // errors occur so all processing goroutines exit regardless of which // input had the validation error. numInputs := len(items) currentItem := 0 processedItems := 0 for processedItems < numInputs { // Only send items while there are still items that need to // be processed. The select statement will never select a nil // channel. var validateChan chan *txValidateItem var item *txValidateItem if currentItem < numInputs { validateChan = v.validateChan item = items[currentItem] } select { case validateChan <- item: currentItem++ case err := <-v.resultChan: processedItems++ if err != nil { close(v.quitChan) return err } } } close(v.quitChan) return nil }
go
func (v *txValidator) Validate(items []*txValidateItem) error { if len(items) == 0 { return nil } // Limit the number of goroutines to do script validation based on the // number of processor cores. This helps ensure the system stays // reasonably responsive under heavy load. maxGoRoutines := runtime.NumCPU() * 3 if maxGoRoutines <= 0 { maxGoRoutines = 1 } if maxGoRoutines > len(items) { maxGoRoutines = len(items) } // Start up validation handlers that are used to asynchronously // validate each transaction input. for i := 0; i < maxGoRoutines; i++ { go v.validateHandler() } // Validate each of the inputs. The quit channel is closed when any // errors occur so all processing goroutines exit regardless of which // input had the validation error. numInputs := len(items) currentItem := 0 processedItems := 0 for processedItems < numInputs { // Only send items while there are still items that need to // be processed. The select statement will never select a nil // channel. var validateChan chan *txValidateItem var item *txValidateItem if currentItem < numInputs { validateChan = v.validateChan item = items[currentItem] } select { case validateChan <- item: currentItem++ case err := <-v.resultChan: processedItems++ if err != nil { close(v.quitChan) return err } } } close(v.quitChan) return nil }
[ "func", "(", "v", "*", "txValidator", ")", "Validate", "(", "items", "[", "]", "*", "txValidateItem", ")", "error", "{", "if", "len", "(", "items", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "// Limit the number of goroutines to do script validation based on the", "// number of processor cores. This helps ensure the system stays", "// reasonably responsive under heavy load.", "maxGoRoutines", ":=", "runtime", ".", "NumCPU", "(", ")", "*", "3", "\n", "if", "maxGoRoutines", "<=", "0", "{", "maxGoRoutines", "=", "1", "\n", "}", "\n", "if", "maxGoRoutines", ">", "len", "(", "items", ")", "{", "maxGoRoutines", "=", "len", "(", "items", ")", "\n", "}", "\n\n", "// Start up validation handlers that are used to asynchronously", "// validate each transaction input.", "for", "i", ":=", "0", ";", "i", "<", "maxGoRoutines", ";", "i", "++", "{", "go", "v", ".", "validateHandler", "(", ")", "\n", "}", "\n\n", "// Validate each of the inputs. The quit channel is closed when any", "// errors occur so all processing goroutines exit regardless of which", "// input had the validation error.", "numInputs", ":=", "len", "(", "items", ")", "\n", "currentItem", ":=", "0", "\n", "processedItems", ":=", "0", "\n", "for", "processedItems", "<", "numInputs", "{", "// Only send items while there are still items that need to", "// be processed. The select statement will never select a nil", "// channel.", "var", "validateChan", "chan", "*", "txValidateItem", "\n", "var", "item", "*", "txValidateItem", "\n", "if", "currentItem", "<", "numInputs", "{", "validateChan", "=", "v", ".", "validateChan", "\n", "item", "=", "items", "[", "currentItem", "]", "\n", "}", "\n\n", "select", "{", "case", "validateChan", "<-", "item", ":", "currentItem", "++", "\n\n", "case", "err", ":=", "<-", "v", ".", "resultChan", ":", "processedItems", "++", "\n", "if", "err", "!=", "nil", "{", "close", "(", "v", ".", "quitChan", ")", "\n", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n\n", "close", "(", "v", ".", "quitChan", ")", "\n", "return", "nil", "\n", "}" ]
// Validate validates the scripts for all of the passed transaction inputs using // multiple goroutines.
[ "Validate", "validates", "the", "scripts", "for", "all", "of", "the", "passed", "transaction", "inputs", "using", "multiple", "goroutines", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/scriptval.go#L118-L172
train
btcsuite/btcd
blockchain/scriptval.go
newTxValidator
func newTxValidator(utxoView *UtxoViewpoint, flags txscript.ScriptFlags, sigCache *txscript.SigCache, hashCache *txscript.HashCache) *txValidator { return &txValidator{ validateChan: make(chan *txValidateItem), quitChan: make(chan struct{}), resultChan: make(chan error), utxoView: utxoView, sigCache: sigCache, hashCache: hashCache, flags: flags, } }
go
func newTxValidator(utxoView *UtxoViewpoint, flags txscript.ScriptFlags, sigCache *txscript.SigCache, hashCache *txscript.HashCache) *txValidator { return &txValidator{ validateChan: make(chan *txValidateItem), quitChan: make(chan struct{}), resultChan: make(chan error), utxoView: utxoView, sigCache: sigCache, hashCache: hashCache, flags: flags, } }
[ "func", "newTxValidator", "(", "utxoView", "*", "UtxoViewpoint", ",", "flags", "txscript", ".", "ScriptFlags", ",", "sigCache", "*", "txscript", ".", "SigCache", ",", "hashCache", "*", "txscript", ".", "HashCache", ")", "*", "txValidator", "{", "return", "&", "txValidator", "{", "validateChan", ":", "make", "(", "chan", "*", "txValidateItem", ")", ",", "quitChan", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "resultChan", ":", "make", "(", "chan", "error", ")", ",", "utxoView", ":", "utxoView", ",", "sigCache", ":", "sigCache", ",", "hashCache", ":", "hashCache", ",", "flags", ":", "flags", ",", "}", "\n", "}" ]
// newTxValidator returns a new instance of txValidator to be used for // validating transaction scripts asynchronously.
[ "newTxValidator", "returns", "a", "new", "instance", "of", "txValidator", "to", "be", "used", "for", "validating", "transaction", "scripts", "asynchronously", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/scriptval.go#L176-L187
train
btcsuite/btcd
blockchain/scriptval.go
ValidateTransactionScripts
func ValidateTransactionScripts(tx *btcutil.Tx, utxoView *UtxoViewpoint, flags txscript.ScriptFlags, sigCache *txscript.SigCache, hashCache *txscript.HashCache) error { // First determine if segwit is active according to the scriptFlags. If // it isn't then we don't need to interact with the HashCache. segwitActive := flags&txscript.ScriptVerifyWitness == txscript.ScriptVerifyWitness // If the hashcache doesn't yet has the sighash midstate for this // transaction, then we'll compute them now so we can re-use them // amongst all worker validation goroutines. if segwitActive && tx.MsgTx().HasWitness() && !hashCache.ContainsHashes(tx.Hash()) { hashCache.AddSigHashes(tx.MsgTx()) } var cachedHashes *txscript.TxSigHashes if segwitActive && tx.MsgTx().HasWitness() { // The same pointer to the transaction's sighash midstate will // be re-used amongst all validation goroutines. By // pre-computing the sighash here instead of during validation, // we ensure the sighashes // are only computed once. cachedHashes, _ = hashCache.GetSigHashes(tx.Hash()) } // Collect all of the transaction inputs and required information for // validation. txIns := tx.MsgTx().TxIn txValItems := make([]*txValidateItem, 0, len(txIns)) for txInIdx, txIn := range txIns { // Skip coinbases. if txIn.PreviousOutPoint.Index == math.MaxUint32 { continue } txVI := &txValidateItem{ txInIndex: txInIdx, txIn: txIn, tx: tx, sigHashes: cachedHashes, } txValItems = append(txValItems, txVI) } // Validate all of the inputs. validator := newTxValidator(utxoView, flags, sigCache, hashCache) return validator.Validate(txValItems) }
go
func ValidateTransactionScripts(tx *btcutil.Tx, utxoView *UtxoViewpoint, flags txscript.ScriptFlags, sigCache *txscript.SigCache, hashCache *txscript.HashCache) error { // First determine if segwit is active according to the scriptFlags. If // it isn't then we don't need to interact with the HashCache. segwitActive := flags&txscript.ScriptVerifyWitness == txscript.ScriptVerifyWitness // If the hashcache doesn't yet has the sighash midstate for this // transaction, then we'll compute them now so we can re-use them // amongst all worker validation goroutines. if segwitActive && tx.MsgTx().HasWitness() && !hashCache.ContainsHashes(tx.Hash()) { hashCache.AddSigHashes(tx.MsgTx()) } var cachedHashes *txscript.TxSigHashes if segwitActive && tx.MsgTx().HasWitness() { // The same pointer to the transaction's sighash midstate will // be re-used amongst all validation goroutines. By // pre-computing the sighash here instead of during validation, // we ensure the sighashes // are only computed once. cachedHashes, _ = hashCache.GetSigHashes(tx.Hash()) } // Collect all of the transaction inputs and required information for // validation. txIns := tx.MsgTx().TxIn txValItems := make([]*txValidateItem, 0, len(txIns)) for txInIdx, txIn := range txIns { // Skip coinbases. if txIn.PreviousOutPoint.Index == math.MaxUint32 { continue } txVI := &txValidateItem{ txInIndex: txInIdx, txIn: txIn, tx: tx, sigHashes: cachedHashes, } txValItems = append(txValItems, txVI) } // Validate all of the inputs. validator := newTxValidator(utxoView, flags, sigCache, hashCache) return validator.Validate(txValItems) }
[ "func", "ValidateTransactionScripts", "(", "tx", "*", "btcutil", ".", "Tx", ",", "utxoView", "*", "UtxoViewpoint", ",", "flags", "txscript", ".", "ScriptFlags", ",", "sigCache", "*", "txscript", ".", "SigCache", ",", "hashCache", "*", "txscript", ".", "HashCache", ")", "error", "{", "// First determine if segwit is active according to the scriptFlags. If", "// it isn't then we don't need to interact with the HashCache.", "segwitActive", ":=", "flags", "&", "txscript", ".", "ScriptVerifyWitness", "==", "txscript", ".", "ScriptVerifyWitness", "\n\n", "// If the hashcache doesn't yet has the sighash midstate for this", "// transaction, then we'll compute them now so we can re-use them", "// amongst all worker validation goroutines.", "if", "segwitActive", "&&", "tx", ".", "MsgTx", "(", ")", ".", "HasWitness", "(", ")", "&&", "!", "hashCache", ".", "ContainsHashes", "(", "tx", ".", "Hash", "(", ")", ")", "{", "hashCache", ".", "AddSigHashes", "(", "tx", ".", "MsgTx", "(", ")", ")", "\n", "}", "\n\n", "var", "cachedHashes", "*", "txscript", ".", "TxSigHashes", "\n", "if", "segwitActive", "&&", "tx", ".", "MsgTx", "(", ")", ".", "HasWitness", "(", ")", "{", "// The same pointer to the transaction's sighash midstate will", "// be re-used amongst all validation goroutines. By", "// pre-computing the sighash here instead of during validation,", "// we ensure the sighashes", "// are only computed once.", "cachedHashes", ",", "_", "=", "hashCache", ".", "GetSigHashes", "(", "tx", ".", "Hash", "(", ")", ")", "\n", "}", "\n\n", "// Collect all of the transaction inputs and required information for", "// validation.", "txIns", ":=", "tx", ".", "MsgTx", "(", ")", ".", "TxIn", "\n", "txValItems", ":=", "make", "(", "[", "]", "*", "txValidateItem", ",", "0", ",", "len", "(", "txIns", ")", ")", "\n", "for", "txInIdx", ",", "txIn", ":=", "range", "txIns", "{", "// Skip coinbases.", "if", "txIn", ".", "PreviousOutPoint", ".", "Index", "==", "math", ".", "MaxUint32", "{", "continue", "\n", "}", "\n\n", "txVI", ":=", "&", "txValidateItem", "{", "txInIndex", ":", "txInIdx", ",", "txIn", ":", "txIn", ",", "tx", ":", "tx", ",", "sigHashes", ":", "cachedHashes", ",", "}", "\n", "txValItems", "=", "append", "(", "txValItems", ",", "txVI", ")", "\n", "}", "\n\n", "// Validate all of the inputs.", "validator", ":=", "newTxValidator", "(", "utxoView", ",", "flags", ",", "sigCache", ",", "hashCache", ")", "\n", "return", "validator", ".", "Validate", "(", "txValItems", ")", "\n", "}" ]
// ValidateTransactionScripts validates the scripts for the passed transaction // using multiple goroutines.
[ "ValidateTransactionScripts", "validates", "the", "scripts", "for", "the", "passed", "transaction", "using", "multiple", "goroutines", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/scriptval.go#L191-L239
train
btcsuite/btcd
blockchain/scriptval.go
checkBlockScripts
func checkBlockScripts(block *btcutil.Block, utxoView *UtxoViewpoint, scriptFlags txscript.ScriptFlags, sigCache *txscript.SigCache, hashCache *txscript.HashCache) error { // First determine if segwit is active according to the scriptFlags. If // it isn't then we don't need to interact with the HashCache. segwitActive := scriptFlags&txscript.ScriptVerifyWitness == txscript.ScriptVerifyWitness // Collect all of the transaction inputs and required information for // validation for all transactions in the block into a single slice. numInputs := 0 for _, tx := range block.Transactions() { numInputs += len(tx.MsgTx().TxIn) } txValItems := make([]*txValidateItem, 0, numInputs) for _, tx := range block.Transactions() { hash := tx.Hash() // If the HashCache is present, and it doesn't yet contain the // partial sighashes for this transaction, then we add the // sighashes for the transaction. This allows us to take // advantage of the potential speed savings due to the new // digest algorithm (BIP0143). if segwitActive && tx.HasWitness() && hashCache != nil && !hashCache.ContainsHashes(hash) { hashCache.AddSigHashes(tx.MsgTx()) } var cachedHashes *txscript.TxSigHashes if segwitActive && tx.HasWitness() { if hashCache != nil { cachedHashes, _ = hashCache.GetSigHashes(hash) } else { cachedHashes = txscript.NewTxSigHashes(tx.MsgTx()) } } for txInIdx, txIn := range tx.MsgTx().TxIn { // Skip coinbases. if txIn.PreviousOutPoint.Index == math.MaxUint32 { continue } txVI := &txValidateItem{ txInIndex: txInIdx, txIn: txIn, tx: tx, sigHashes: cachedHashes, } txValItems = append(txValItems, txVI) } } // Validate all of the inputs. validator := newTxValidator(utxoView, scriptFlags, sigCache, hashCache) start := time.Now() if err := validator.Validate(txValItems); err != nil { return err } elapsed := time.Since(start) log.Tracef("block %v took %v to verify", block.Hash(), elapsed) // If the HashCache is present, once we have validated the block, we no // longer need the cached hashes for these transactions, so we purge // them from the cache. if segwitActive && hashCache != nil { for _, tx := range block.Transactions() { if tx.MsgTx().HasWitness() { hashCache.PurgeSigHashes(tx.Hash()) } } } return nil }
go
func checkBlockScripts(block *btcutil.Block, utxoView *UtxoViewpoint, scriptFlags txscript.ScriptFlags, sigCache *txscript.SigCache, hashCache *txscript.HashCache) error { // First determine if segwit is active according to the scriptFlags. If // it isn't then we don't need to interact with the HashCache. segwitActive := scriptFlags&txscript.ScriptVerifyWitness == txscript.ScriptVerifyWitness // Collect all of the transaction inputs and required information for // validation for all transactions in the block into a single slice. numInputs := 0 for _, tx := range block.Transactions() { numInputs += len(tx.MsgTx().TxIn) } txValItems := make([]*txValidateItem, 0, numInputs) for _, tx := range block.Transactions() { hash := tx.Hash() // If the HashCache is present, and it doesn't yet contain the // partial sighashes for this transaction, then we add the // sighashes for the transaction. This allows us to take // advantage of the potential speed savings due to the new // digest algorithm (BIP0143). if segwitActive && tx.HasWitness() && hashCache != nil && !hashCache.ContainsHashes(hash) { hashCache.AddSigHashes(tx.MsgTx()) } var cachedHashes *txscript.TxSigHashes if segwitActive && tx.HasWitness() { if hashCache != nil { cachedHashes, _ = hashCache.GetSigHashes(hash) } else { cachedHashes = txscript.NewTxSigHashes(tx.MsgTx()) } } for txInIdx, txIn := range tx.MsgTx().TxIn { // Skip coinbases. if txIn.PreviousOutPoint.Index == math.MaxUint32 { continue } txVI := &txValidateItem{ txInIndex: txInIdx, txIn: txIn, tx: tx, sigHashes: cachedHashes, } txValItems = append(txValItems, txVI) } } // Validate all of the inputs. validator := newTxValidator(utxoView, scriptFlags, sigCache, hashCache) start := time.Now() if err := validator.Validate(txValItems); err != nil { return err } elapsed := time.Since(start) log.Tracef("block %v took %v to verify", block.Hash(), elapsed) // If the HashCache is present, once we have validated the block, we no // longer need the cached hashes for these transactions, so we purge // them from the cache. if segwitActive && hashCache != nil { for _, tx := range block.Transactions() { if tx.MsgTx().HasWitness() { hashCache.PurgeSigHashes(tx.Hash()) } } } return nil }
[ "func", "checkBlockScripts", "(", "block", "*", "btcutil", ".", "Block", ",", "utxoView", "*", "UtxoViewpoint", ",", "scriptFlags", "txscript", ".", "ScriptFlags", ",", "sigCache", "*", "txscript", ".", "SigCache", ",", "hashCache", "*", "txscript", ".", "HashCache", ")", "error", "{", "// First determine if segwit is active according to the scriptFlags. If", "// it isn't then we don't need to interact with the HashCache.", "segwitActive", ":=", "scriptFlags", "&", "txscript", ".", "ScriptVerifyWitness", "==", "txscript", ".", "ScriptVerifyWitness", "\n\n", "// Collect all of the transaction inputs and required information for", "// validation for all transactions in the block into a single slice.", "numInputs", ":=", "0", "\n", "for", "_", ",", "tx", ":=", "range", "block", ".", "Transactions", "(", ")", "{", "numInputs", "+=", "len", "(", "tx", ".", "MsgTx", "(", ")", ".", "TxIn", ")", "\n", "}", "\n", "txValItems", ":=", "make", "(", "[", "]", "*", "txValidateItem", ",", "0", ",", "numInputs", ")", "\n", "for", "_", ",", "tx", ":=", "range", "block", ".", "Transactions", "(", ")", "{", "hash", ":=", "tx", ".", "Hash", "(", ")", "\n\n", "// If the HashCache is present, and it doesn't yet contain the", "// partial sighashes for this transaction, then we add the", "// sighashes for the transaction. This allows us to take", "// advantage of the potential speed savings due to the new", "// digest algorithm (BIP0143).", "if", "segwitActive", "&&", "tx", ".", "HasWitness", "(", ")", "&&", "hashCache", "!=", "nil", "&&", "!", "hashCache", ".", "ContainsHashes", "(", "hash", ")", "{", "hashCache", ".", "AddSigHashes", "(", "tx", ".", "MsgTx", "(", ")", ")", "\n", "}", "\n\n", "var", "cachedHashes", "*", "txscript", ".", "TxSigHashes", "\n", "if", "segwitActive", "&&", "tx", ".", "HasWitness", "(", ")", "{", "if", "hashCache", "!=", "nil", "{", "cachedHashes", ",", "_", "=", "hashCache", ".", "GetSigHashes", "(", "hash", ")", "\n", "}", "else", "{", "cachedHashes", "=", "txscript", ".", "NewTxSigHashes", "(", "tx", ".", "MsgTx", "(", ")", ")", "\n", "}", "\n", "}", "\n\n", "for", "txInIdx", ",", "txIn", ":=", "range", "tx", ".", "MsgTx", "(", ")", ".", "TxIn", "{", "// Skip coinbases.", "if", "txIn", ".", "PreviousOutPoint", ".", "Index", "==", "math", ".", "MaxUint32", "{", "continue", "\n", "}", "\n\n", "txVI", ":=", "&", "txValidateItem", "{", "txInIndex", ":", "txInIdx", ",", "txIn", ":", "txIn", ",", "tx", ":", "tx", ",", "sigHashes", ":", "cachedHashes", ",", "}", "\n", "txValItems", "=", "append", "(", "txValItems", ",", "txVI", ")", "\n", "}", "\n", "}", "\n\n", "// Validate all of the inputs.", "validator", ":=", "newTxValidator", "(", "utxoView", ",", "scriptFlags", ",", "sigCache", ",", "hashCache", ")", "\n", "start", ":=", "time", ".", "Now", "(", ")", "\n", "if", "err", ":=", "validator", ".", "Validate", "(", "txValItems", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "elapsed", ":=", "time", ".", "Since", "(", "start", ")", "\n\n", "log", ".", "Tracef", "(", "\"", "\"", ",", "block", ".", "Hash", "(", ")", ",", "elapsed", ")", "\n\n", "// If the HashCache is present, once we have validated the block, we no", "// longer need the cached hashes for these transactions, so we purge", "// them from the cache.", "if", "segwitActive", "&&", "hashCache", "!=", "nil", "{", "for", "_", ",", "tx", ":=", "range", "block", ".", "Transactions", "(", ")", "{", "if", "tx", ".", "MsgTx", "(", ")", ".", "HasWitness", "(", ")", "{", "hashCache", ".", "PurgeSigHashes", "(", "tx", ".", "Hash", "(", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// checkBlockScripts executes and validates the scripts for all transactions in // the passed block using multiple goroutines.
[ "checkBlockScripts", "executes", "and", "validates", "the", "scripts", "for", "all", "transactions", "in", "the", "passed", "block", "using", "multiple", "goroutines", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/scriptval.go#L243-L319
train
btcsuite/btcd
blockchain/process.go
blockExists
func (b *BlockChain) blockExists(hash *chainhash.Hash) (bool, error) { // Check block index first (could be main chain or side chain blocks). if b.index.HaveBlock(hash) { return true, nil } // Check in the database. var exists bool err := b.db.View(func(dbTx database.Tx) error { var err error exists, err = dbTx.HasBlock(hash) if err != nil || !exists { return err } // Ignore side chain blocks in the database. This is necessary // because there is not currently any record of the associated // block index data such as its block height, so it's not yet // possible to efficiently load the block and do anything useful // with it. // // Ultimately the entire block index should be serialized // instead of only the current main chain so it can be consulted // directly. _, err = dbFetchHeightByHash(dbTx, hash) if isNotInMainChainErr(err) { exists = false return nil } return err }) return exists, err }
go
func (b *BlockChain) blockExists(hash *chainhash.Hash) (bool, error) { // Check block index first (could be main chain or side chain blocks). if b.index.HaveBlock(hash) { return true, nil } // Check in the database. var exists bool err := b.db.View(func(dbTx database.Tx) error { var err error exists, err = dbTx.HasBlock(hash) if err != nil || !exists { return err } // Ignore side chain blocks in the database. This is necessary // because there is not currently any record of the associated // block index data such as its block height, so it's not yet // possible to efficiently load the block and do anything useful // with it. // // Ultimately the entire block index should be serialized // instead of only the current main chain so it can be consulted // directly. _, err = dbFetchHeightByHash(dbTx, hash) if isNotInMainChainErr(err) { exists = false return nil } return err }) return exists, err }
[ "func", "(", "b", "*", "BlockChain", ")", "blockExists", "(", "hash", "*", "chainhash", ".", "Hash", ")", "(", "bool", ",", "error", ")", "{", "// Check block index first (could be main chain or side chain blocks).", "if", "b", ".", "index", ".", "HaveBlock", "(", "hash", ")", "{", "return", "true", ",", "nil", "\n", "}", "\n\n", "// Check in the database.", "var", "exists", "bool", "\n", "err", ":=", "b", ".", "db", ".", "View", "(", "func", "(", "dbTx", "database", ".", "Tx", ")", "error", "{", "var", "err", "error", "\n", "exists", ",", "err", "=", "dbTx", ".", "HasBlock", "(", "hash", ")", "\n", "if", "err", "!=", "nil", "||", "!", "exists", "{", "return", "err", "\n", "}", "\n\n", "// Ignore side chain blocks in the database. This is necessary", "// because there is not currently any record of the associated", "// block index data such as its block height, so it's not yet", "// possible to efficiently load the block and do anything useful", "// with it.", "//", "// Ultimately the entire block index should be serialized", "// instead of only the current main chain so it can be consulted", "// directly.", "_", ",", "err", "=", "dbFetchHeightByHash", "(", "dbTx", ",", "hash", ")", "\n", "if", "isNotInMainChainErr", "(", "err", ")", "{", "exists", "=", "false", "\n", "return", "nil", "\n", "}", "\n", "return", "err", "\n", "}", ")", "\n", "return", "exists", ",", "err", "\n", "}" ]
// blockExists determines whether a block with the given hash exists either in // the main chain or any side chains. // // This function is safe for concurrent access.
[ "blockExists", "determines", "whether", "a", "block", "with", "the", "given", "hash", "exists", "either", "in", "the", "main", "chain", "or", "any", "side", "chains", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/process.go#L40-L72
train
btcsuite/btcd
blockchain/process.go
ProcessBlock
func (b *BlockChain) ProcessBlock(block *btcutil.Block, flags BehaviorFlags) (bool, bool, error) { b.chainLock.Lock() defer b.chainLock.Unlock() fastAdd := flags&BFFastAdd == BFFastAdd blockHash := block.Hash() log.Tracef("Processing block %v", blockHash) // The block must not already exist in the main chain or side chains. exists, err := b.blockExists(blockHash) if err != nil { return false, false, err } if exists { str := fmt.Sprintf("already have block %v", blockHash) return false, false, ruleError(ErrDuplicateBlock, str) } // The block must not already exist as an orphan. if _, exists := b.orphans[*blockHash]; exists { str := fmt.Sprintf("already have block (orphan) %v", blockHash) return false, false, ruleError(ErrDuplicateBlock, str) } // Perform preliminary sanity checks on the block and its transactions. err = checkBlockSanity(block, b.chainParams.PowLimit, b.timeSource, flags) if err != nil { return false, false, err } // Find the previous checkpoint and perform some additional checks based // on the checkpoint. This provides a few nice properties such as // preventing old side chain blocks before the last checkpoint, // rejecting easy to mine, but otherwise bogus, blocks that could be // used to eat memory, and ensuring expected (versus claimed) proof of // work requirements since the previous checkpoint are met. blockHeader := &block.MsgBlock().Header checkpointNode, err := b.findPreviousCheckpoint() if err != nil { return false, false, err } if checkpointNode != nil { // Ensure the block timestamp is after the checkpoint timestamp. checkpointTime := time.Unix(checkpointNode.timestamp, 0) if blockHeader.Timestamp.Before(checkpointTime) { str := fmt.Sprintf("block %v has timestamp %v before "+ "last checkpoint timestamp %v", blockHash, blockHeader.Timestamp, checkpointTime) return false, false, ruleError(ErrCheckpointTimeTooOld, str) } if !fastAdd { // Even though the checks prior to now have already ensured the // proof of work exceeds the claimed amount, the claimed amount // is a field in the block header which could be forged. This // check ensures the proof of work is at least the minimum // expected based on elapsed time since the last checkpoint and // maximum adjustment allowed by the retarget rules. duration := blockHeader.Timestamp.Sub(checkpointTime) requiredTarget := CompactToBig(b.calcEasiestDifficulty( checkpointNode.bits, duration)) currentTarget := CompactToBig(blockHeader.Bits) if currentTarget.Cmp(requiredTarget) > 0 { str := fmt.Sprintf("block target difficulty of %064x "+ "is too low when compared to the previous "+ "checkpoint", currentTarget) return false, false, ruleError(ErrDifficultyTooLow, str) } } } // Handle orphan blocks. prevHash := &blockHeader.PrevBlock prevHashExists, err := b.blockExists(prevHash) if err != nil { return false, false, err } if !prevHashExists { log.Infof("Adding orphan block %v with parent %v", blockHash, prevHash) b.addOrphanBlock(block) return false, true, nil } // The block has passed all context independent checks and appears sane // enough to potentially accept it into the block chain. isMainChain, err := b.maybeAcceptBlock(block, flags) if err != nil { return false, false, err } // Accept any orphan blocks that depend on this block (they are // no longer orphans) and repeat for those accepted blocks until // there are no more. err = b.processOrphans(blockHash, flags) if err != nil { return false, false, err } log.Debugf("Accepted block %v", blockHash) return isMainChain, false, nil }
go
func (b *BlockChain) ProcessBlock(block *btcutil.Block, flags BehaviorFlags) (bool, bool, error) { b.chainLock.Lock() defer b.chainLock.Unlock() fastAdd := flags&BFFastAdd == BFFastAdd blockHash := block.Hash() log.Tracef("Processing block %v", blockHash) // The block must not already exist in the main chain or side chains. exists, err := b.blockExists(blockHash) if err != nil { return false, false, err } if exists { str := fmt.Sprintf("already have block %v", blockHash) return false, false, ruleError(ErrDuplicateBlock, str) } // The block must not already exist as an orphan. if _, exists := b.orphans[*blockHash]; exists { str := fmt.Sprintf("already have block (orphan) %v", blockHash) return false, false, ruleError(ErrDuplicateBlock, str) } // Perform preliminary sanity checks on the block and its transactions. err = checkBlockSanity(block, b.chainParams.PowLimit, b.timeSource, flags) if err != nil { return false, false, err } // Find the previous checkpoint and perform some additional checks based // on the checkpoint. This provides a few nice properties such as // preventing old side chain blocks before the last checkpoint, // rejecting easy to mine, but otherwise bogus, blocks that could be // used to eat memory, and ensuring expected (versus claimed) proof of // work requirements since the previous checkpoint are met. blockHeader := &block.MsgBlock().Header checkpointNode, err := b.findPreviousCheckpoint() if err != nil { return false, false, err } if checkpointNode != nil { // Ensure the block timestamp is after the checkpoint timestamp. checkpointTime := time.Unix(checkpointNode.timestamp, 0) if blockHeader.Timestamp.Before(checkpointTime) { str := fmt.Sprintf("block %v has timestamp %v before "+ "last checkpoint timestamp %v", blockHash, blockHeader.Timestamp, checkpointTime) return false, false, ruleError(ErrCheckpointTimeTooOld, str) } if !fastAdd { // Even though the checks prior to now have already ensured the // proof of work exceeds the claimed amount, the claimed amount // is a field in the block header which could be forged. This // check ensures the proof of work is at least the minimum // expected based on elapsed time since the last checkpoint and // maximum adjustment allowed by the retarget rules. duration := blockHeader.Timestamp.Sub(checkpointTime) requiredTarget := CompactToBig(b.calcEasiestDifficulty( checkpointNode.bits, duration)) currentTarget := CompactToBig(blockHeader.Bits) if currentTarget.Cmp(requiredTarget) > 0 { str := fmt.Sprintf("block target difficulty of %064x "+ "is too low when compared to the previous "+ "checkpoint", currentTarget) return false, false, ruleError(ErrDifficultyTooLow, str) } } } // Handle orphan blocks. prevHash := &blockHeader.PrevBlock prevHashExists, err := b.blockExists(prevHash) if err != nil { return false, false, err } if !prevHashExists { log.Infof("Adding orphan block %v with parent %v", blockHash, prevHash) b.addOrphanBlock(block) return false, true, nil } // The block has passed all context independent checks and appears sane // enough to potentially accept it into the block chain. isMainChain, err := b.maybeAcceptBlock(block, flags) if err != nil { return false, false, err } // Accept any orphan blocks that depend on this block (they are // no longer orphans) and repeat for those accepted blocks until // there are no more. err = b.processOrphans(blockHash, flags) if err != nil { return false, false, err } log.Debugf("Accepted block %v", blockHash) return isMainChain, false, nil }
[ "func", "(", "b", "*", "BlockChain", ")", "ProcessBlock", "(", "block", "*", "btcutil", ".", "Block", ",", "flags", "BehaviorFlags", ")", "(", "bool", ",", "bool", ",", "error", ")", "{", "b", ".", "chainLock", ".", "Lock", "(", ")", "\n", "defer", "b", ".", "chainLock", ".", "Unlock", "(", ")", "\n\n", "fastAdd", ":=", "flags", "&", "BFFastAdd", "==", "BFFastAdd", "\n\n", "blockHash", ":=", "block", ".", "Hash", "(", ")", "\n", "log", ".", "Tracef", "(", "\"", "\"", ",", "blockHash", ")", "\n\n", "// The block must not already exist in the main chain or side chains.", "exists", ",", "err", ":=", "b", ".", "blockExists", "(", "blockHash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "false", ",", "err", "\n", "}", "\n", "if", "exists", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "blockHash", ")", "\n", "return", "false", ",", "false", ",", "ruleError", "(", "ErrDuplicateBlock", ",", "str", ")", "\n", "}", "\n\n", "// The block must not already exist as an orphan.", "if", "_", ",", "exists", ":=", "b", ".", "orphans", "[", "*", "blockHash", "]", ";", "exists", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "blockHash", ")", "\n", "return", "false", ",", "false", ",", "ruleError", "(", "ErrDuplicateBlock", ",", "str", ")", "\n", "}", "\n\n", "// Perform preliminary sanity checks on the block and its transactions.", "err", "=", "checkBlockSanity", "(", "block", ",", "b", ".", "chainParams", ".", "PowLimit", ",", "b", ".", "timeSource", ",", "flags", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "false", ",", "err", "\n", "}", "\n\n", "// Find the previous checkpoint and perform some additional checks based", "// on the checkpoint. This provides a few nice properties such as", "// preventing old side chain blocks before the last checkpoint,", "// rejecting easy to mine, but otherwise bogus, blocks that could be", "// used to eat memory, and ensuring expected (versus claimed) proof of", "// work requirements since the previous checkpoint are met.", "blockHeader", ":=", "&", "block", ".", "MsgBlock", "(", ")", ".", "Header", "\n", "checkpointNode", ",", "err", ":=", "b", ".", "findPreviousCheckpoint", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "false", ",", "err", "\n", "}", "\n", "if", "checkpointNode", "!=", "nil", "{", "// Ensure the block timestamp is after the checkpoint timestamp.", "checkpointTime", ":=", "time", ".", "Unix", "(", "checkpointNode", ".", "timestamp", ",", "0", ")", "\n", "if", "blockHeader", ".", "Timestamp", ".", "Before", "(", "checkpointTime", ")", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "blockHash", ",", "blockHeader", ".", "Timestamp", ",", "checkpointTime", ")", "\n", "return", "false", ",", "false", ",", "ruleError", "(", "ErrCheckpointTimeTooOld", ",", "str", ")", "\n", "}", "\n", "if", "!", "fastAdd", "{", "// Even though the checks prior to now have already ensured the", "// proof of work exceeds the claimed amount, the claimed amount", "// is a field in the block header which could be forged. This", "// check ensures the proof of work is at least the minimum", "// expected based on elapsed time since the last checkpoint and", "// maximum adjustment allowed by the retarget rules.", "duration", ":=", "blockHeader", ".", "Timestamp", ".", "Sub", "(", "checkpointTime", ")", "\n", "requiredTarget", ":=", "CompactToBig", "(", "b", ".", "calcEasiestDifficulty", "(", "checkpointNode", ".", "bits", ",", "duration", ")", ")", "\n", "currentTarget", ":=", "CompactToBig", "(", "blockHeader", ".", "Bits", ")", "\n", "if", "currentTarget", ".", "Cmp", "(", "requiredTarget", ")", ">", "0", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ",", "currentTarget", ")", "\n", "return", "false", ",", "false", ",", "ruleError", "(", "ErrDifficultyTooLow", ",", "str", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Handle orphan blocks.", "prevHash", ":=", "&", "blockHeader", ".", "PrevBlock", "\n", "prevHashExists", ",", "err", ":=", "b", ".", "blockExists", "(", "prevHash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "false", ",", "err", "\n", "}", "\n", "if", "!", "prevHashExists", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "blockHash", ",", "prevHash", ")", "\n", "b", ".", "addOrphanBlock", "(", "block", ")", "\n\n", "return", "false", ",", "true", ",", "nil", "\n", "}", "\n\n", "// The block has passed all context independent checks and appears sane", "// enough to potentially accept it into the block chain.", "isMainChain", ",", "err", ":=", "b", ".", "maybeAcceptBlock", "(", "block", ",", "flags", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "false", ",", "err", "\n", "}", "\n\n", "// Accept any orphan blocks that depend on this block (they are", "// no longer orphans) and repeat for those accepted blocks until", "// there are no more.", "err", "=", "b", ".", "processOrphans", "(", "blockHash", ",", "flags", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "false", ",", "err", "\n", "}", "\n\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "blockHash", ")", "\n\n", "return", "isMainChain", ",", "false", ",", "nil", "\n", "}" ]
// ProcessBlock is the main workhorse for handling insertion of new blocks into // the block chain. It includes functionality such as rejecting duplicate // blocks, ensuring blocks follow all rules, orphan handling, and insertion into // the block chain along with best chain selection and reorganization. // // When no errors occurred during processing, the first return value indicates // whether or not the block is on the main chain and the second indicates // whether or not the block is an orphan. // // This function is safe for concurrent access.
[ "ProcessBlock", "is", "the", "main", "workhorse", "for", "handling", "insertion", "of", "new", "blocks", "into", "the", "block", "chain", ".", "It", "includes", "functionality", "such", "as", "rejecting", "duplicate", "blocks", "ensuring", "blocks", "follow", "all", "rules", "orphan", "handling", "and", "insertion", "into", "the", "block", "chain", "along", "with", "best", "chain", "selection", "and", "reorganization", ".", "When", "no", "errors", "occurred", "during", "processing", "the", "first", "return", "value", "indicates", "whether", "or", "not", "the", "block", "is", "on", "the", "main", "chain", "and", "the", "second", "indicates", "whether", "or", "not", "the", "block", "is", "an", "orphan", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/process.go#L142-L244
train
btcsuite/btcd
addrmgr/knownaddress.go
chance
func (ka *KnownAddress) chance() float64 { now := time.Now() lastAttempt := now.Sub(ka.lastattempt) if lastAttempt < 0 { lastAttempt = 0 } c := 1.0 // Very recent attempts are less likely to be retried. if lastAttempt < 10*time.Minute { c *= 0.01 } // Failed attempts deprioritise. for i := ka.attempts; i > 0; i-- { c /= 1.5 } return c }
go
func (ka *KnownAddress) chance() float64 { now := time.Now() lastAttempt := now.Sub(ka.lastattempt) if lastAttempt < 0 { lastAttempt = 0 } c := 1.0 // Very recent attempts are less likely to be retried. if lastAttempt < 10*time.Minute { c *= 0.01 } // Failed attempts deprioritise. for i := ka.attempts; i > 0; i-- { c /= 1.5 } return c }
[ "func", "(", "ka", "*", "KnownAddress", ")", "chance", "(", ")", "float64", "{", "now", ":=", "time", ".", "Now", "(", ")", "\n", "lastAttempt", ":=", "now", ".", "Sub", "(", "ka", ".", "lastattempt", ")", "\n\n", "if", "lastAttempt", "<", "0", "{", "lastAttempt", "=", "0", "\n", "}", "\n\n", "c", ":=", "1.0", "\n\n", "// Very recent attempts are less likely to be retried.", "if", "lastAttempt", "<", "10", "*", "time", ".", "Minute", "{", "c", "*=", "0.01", "\n", "}", "\n\n", "// Failed attempts deprioritise.", "for", "i", ":=", "ka", ".", "attempts", ";", "i", ">", "0", ";", "i", "--", "{", "c", "/=", "1.5", "\n", "}", "\n\n", "return", "c", "\n", "}" ]
// chance returns the selection probability for a known address. The priority // depends upon how recently the address has been seen, how recently it was last // attempted and how often attempts to connect to it have failed.
[ "chance", "returns", "the", "selection", "probability", "for", "a", "known", "address", ".", "The", "priority", "depends", "upon", "how", "recently", "the", "address", "has", "been", "seen", "how", "recently", "it", "was", "last", "attempted", "and", "how", "often", "attempts", "to", "connect", "to", "it", "have", "failed", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/knownaddress.go#L44-L65
train
btcsuite/btcd
blockchain/checkpoints.go
verifyCheckpoint
func (b *BlockChain) verifyCheckpoint(height int32, hash *chainhash.Hash) bool { if !b.HasCheckpoints() { return true } // Nothing to check if there is no checkpoint data for the block height. checkpoint, exists := b.checkpointsByHeight[height] if !exists { return true } if !checkpoint.Hash.IsEqual(hash) { return false } log.Infof("Verified checkpoint at height %d/block %s", checkpoint.Height, checkpoint.Hash) return true }
go
func (b *BlockChain) verifyCheckpoint(height int32, hash *chainhash.Hash) bool { if !b.HasCheckpoints() { return true } // Nothing to check if there is no checkpoint data for the block height. checkpoint, exists := b.checkpointsByHeight[height] if !exists { return true } if !checkpoint.Hash.IsEqual(hash) { return false } log.Infof("Verified checkpoint at height %d/block %s", checkpoint.Height, checkpoint.Hash) return true }
[ "func", "(", "b", "*", "BlockChain", ")", "verifyCheckpoint", "(", "height", "int32", ",", "hash", "*", "chainhash", ".", "Hash", ")", "bool", "{", "if", "!", "b", ".", "HasCheckpoints", "(", ")", "{", "return", "true", "\n", "}", "\n\n", "// Nothing to check if there is no checkpoint data for the block height.", "checkpoint", ",", "exists", ":=", "b", ".", "checkpointsByHeight", "[", "height", "]", "\n", "if", "!", "exists", "{", "return", "true", "\n", "}", "\n\n", "if", "!", "checkpoint", ".", "Hash", ".", "IsEqual", "(", "hash", ")", "{", "return", "false", "\n", "}", "\n\n", "log", ".", "Infof", "(", "\"", "\"", ",", "checkpoint", ".", "Height", ",", "checkpoint", ".", "Hash", ")", "\n", "return", "true", "\n", "}" ]
// verifyCheckpoint returns whether the passed block height and hash combination // match the checkpoint data. It also returns true if there is no checkpoint // data for the passed block height.
[ "verifyCheckpoint", "returns", "whether", "the", "passed", "block", "height", "and", "hash", "combination", "match", "the", "checkpoint", "data", ".", "It", "also", "returns", "true", "if", "there", "is", "no", "checkpoint", "data", "for", "the", "passed", "block", "height", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/checkpoints.go#L61-L79
train
btcsuite/btcd
blockchain/checkpoints.go
isNonstandardTransaction
func isNonstandardTransaction(tx *btcutil.Tx) bool { // Check all of the output public key scripts for non-standard scripts. for _, txOut := range tx.MsgTx().TxOut { scriptClass := txscript.GetScriptClass(txOut.PkScript) if scriptClass == txscript.NonStandardTy { return true } } return false }
go
func isNonstandardTransaction(tx *btcutil.Tx) bool { // Check all of the output public key scripts for non-standard scripts. for _, txOut := range tx.MsgTx().TxOut { scriptClass := txscript.GetScriptClass(txOut.PkScript) if scriptClass == txscript.NonStandardTy { return true } } return false }
[ "func", "isNonstandardTransaction", "(", "tx", "*", "btcutil", ".", "Tx", ")", "bool", "{", "// Check all of the output public key scripts for non-standard scripts.", "for", "_", ",", "txOut", ":=", "range", "tx", ".", "MsgTx", "(", ")", ".", "TxOut", "{", "scriptClass", ":=", "txscript", ".", "GetScriptClass", "(", "txOut", ".", "PkScript", ")", "\n", "if", "scriptClass", "==", "txscript", ".", "NonStandardTy", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isNonstandardTransaction determines whether a transaction contains any // scripts which are not one of the standard types.
[ "isNonstandardTransaction", "determines", "whether", "a", "transaction", "contains", "any", "scripts", "which", "are", "not", "one", "of", "the", "standard", "types", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/checkpoints.go#L172-L181
train
btcsuite/btcd
rpcclient/net.go
AddNodeAsync
func (c *Client) AddNodeAsync(host string, command AddNodeCommand) FutureAddNodeResult { cmd := btcjson.NewAddNodeCmd(host, btcjson.AddNodeSubCmd(command)) return c.sendCmd(cmd) }
go
func (c *Client) AddNodeAsync(host string, command AddNodeCommand) FutureAddNodeResult { cmd := btcjson.NewAddNodeCmd(host, btcjson.AddNodeSubCmd(command)) return c.sendCmd(cmd) }
[ "func", "(", "c", "*", "Client", ")", "AddNodeAsync", "(", "host", "string", ",", "command", "AddNodeCommand", ")", "FutureAddNodeResult", "{", "cmd", ":=", "btcjson", ".", "NewAddNodeCmd", "(", "host", ",", "btcjson", ".", "AddNodeSubCmd", "(", "command", ")", ")", "\n", "return", "c", ".", "sendCmd", "(", "cmd", ")", "\n", "}" ]
// AddNodeAsync returns an instance of a type that can be used to get the result // of the RPC at some future time by invoking the Receive function on the // returned instance. // // See AddNode for the blocking version and more details.
[ "AddNodeAsync", "returns", "an", "instance", "of", "a", "type", "that", "can", "be", "used", "to", "get", "the", "result", "of", "the", "RPC", "at", "some", "future", "time", "by", "invoking", "the", "Receive", "function", "on", "the", "returned", "instance", ".", "See", "AddNode", "for", "the", "blocking", "version", "and", "more", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/net.go#L52-L55
train
btcsuite/btcd
rpcclient/net.go
AddNode
func (c *Client) AddNode(host string, command AddNodeCommand) error { return c.AddNodeAsync(host, command).Receive() }
go
func (c *Client) AddNode(host string, command AddNodeCommand) error { return c.AddNodeAsync(host, command).Receive() }
[ "func", "(", "c", "*", "Client", ")", "AddNode", "(", "host", "string", ",", "command", "AddNodeCommand", ")", "error", "{", "return", "c", ".", "AddNodeAsync", "(", "host", ",", "command", ")", ".", "Receive", "(", ")", "\n", "}" ]
// AddNode attempts to perform the passed command on the passed persistent peer. // For example, it can be used to add or a remove a persistent peer, or to do // a one time connection to a peer. // // It may not be used to remove non-persistent peers.
[ "AddNode", "attempts", "to", "perform", "the", "passed", "command", "on", "the", "passed", "persistent", "peer", ".", "For", "example", "it", "can", "be", "used", "to", "add", "or", "a", "remove", "a", "persistent", "peer", "or", "to", "do", "a", "one", "time", "connection", "to", "a", "peer", ".", "It", "may", "not", "be", "used", "to", "remove", "non", "-", "persistent", "peers", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/net.go#L62-L64
train
btcsuite/btcd
rpcclient/net.go
NodeAsync
func (c *Client) NodeAsync(command btcjson.NodeSubCmd, host string, connectSubCmd *string) FutureNodeResult { cmd := btcjson.NewNodeCmd(command, host, connectSubCmd) return c.sendCmd(cmd) }
go
func (c *Client) NodeAsync(command btcjson.NodeSubCmd, host string, connectSubCmd *string) FutureNodeResult { cmd := btcjson.NewNodeCmd(command, host, connectSubCmd) return c.sendCmd(cmd) }
[ "func", "(", "c", "*", "Client", ")", "NodeAsync", "(", "command", "btcjson", ".", "NodeSubCmd", ",", "host", "string", ",", "connectSubCmd", "*", "string", ")", "FutureNodeResult", "{", "cmd", ":=", "btcjson", ".", "NewNodeCmd", "(", "command", ",", "host", ",", "connectSubCmd", ")", "\n", "return", "c", ".", "sendCmd", "(", "cmd", ")", "\n", "}" ]
// NodeAsync returns an instance of a type that can be used to get the result // of the RPC at some future time by invoking the Receive function on the // returned instance. // // See Node for the blocking version and more details.
[ "NodeAsync", "returns", "an", "instance", "of", "a", "type", "that", "can", "be", "used", "to", "get", "the", "result", "of", "the", "RPC", "at", "some", "future", "time", "by", "invoking", "the", "Receive", "function", "on", "the", "returned", "instance", ".", "See", "Node", "for", "the", "blocking", "version", "and", "more", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/net.go#L82-L86
train
btcsuite/btcd
rpcclient/net.go
Node
func (c *Client) Node(command btcjson.NodeSubCmd, host string, connectSubCmd *string) error { return c.NodeAsync(command, host, connectSubCmd).Receive() }
go
func (c *Client) Node(command btcjson.NodeSubCmd, host string, connectSubCmd *string) error { return c.NodeAsync(command, host, connectSubCmd).Receive() }
[ "func", "(", "c", "*", "Client", ")", "Node", "(", "command", "btcjson", ".", "NodeSubCmd", ",", "host", "string", ",", "connectSubCmd", "*", "string", ")", "error", "{", "return", "c", ".", "NodeAsync", "(", "command", ",", "host", ",", "connectSubCmd", ")", ".", "Receive", "(", ")", "\n", "}" ]
// Node attempts to perform the passed node command on the host. // For example, it can be used to add or a remove a persistent peer, or to do // connect or diconnect a non-persistent one. // // The connectSubCmd should be set either "perm" or "temp", depending on // whether we are targetting a persistent or non-persistent peer. Passing nil // will cause the default value to be used, which currently is "temp".
[ "Node", "attempts", "to", "perform", "the", "passed", "node", "command", "on", "the", "host", ".", "For", "example", "it", "can", "be", "used", "to", "add", "or", "a", "remove", "a", "persistent", "peer", "or", "to", "do", "connect", "or", "diconnect", "a", "non", "-", "persistent", "one", ".", "The", "connectSubCmd", "should", "be", "set", "either", "perm", "or", "temp", "depending", "on", "whether", "we", "are", "targetting", "a", "persistent", "or", "non", "-", "persistent", "peer", ".", "Passing", "nil", "will", "cause", "the", "default", "value", "to", "be", "used", "which", "currently", "is", "temp", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/net.go#L95-L98
train
btcsuite/btcd
rpcclient/net.go
GetAddedNodeInfoAsync
func (c *Client) GetAddedNodeInfoAsync(peer string) FutureGetAddedNodeInfoResult { cmd := btcjson.NewGetAddedNodeInfoCmd(true, &peer) return c.sendCmd(cmd) }
go
func (c *Client) GetAddedNodeInfoAsync(peer string) FutureGetAddedNodeInfoResult { cmd := btcjson.NewGetAddedNodeInfoCmd(true, &peer) return c.sendCmd(cmd) }
[ "func", "(", "c", "*", "Client", ")", "GetAddedNodeInfoAsync", "(", "peer", "string", ")", "FutureGetAddedNodeInfoResult", "{", "cmd", ":=", "btcjson", ".", "NewGetAddedNodeInfoCmd", "(", "true", ",", "&", "peer", ")", "\n", "return", "c", ".", "sendCmd", "(", "cmd", ")", "\n", "}" ]
// GetAddedNodeInfoAsync returns an instance of a type that can be used to get // the result of the RPC at some future time by invoking the Receive function on // the returned instance. // // See GetAddedNodeInfo for the blocking version and more details.
[ "GetAddedNodeInfoAsync", "returns", "an", "instance", "of", "a", "type", "that", "can", "be", "used", "to", "get", "the", "result", "of", "the", "RPC", "at", "some", "future", "time", "by", "invoking", "the", "Receive", "function", "on", "the", "returned", "instance", ".", "See", "GetAddedNodeInfo", "for", "the", "blocking", "version", "and", "more", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/net.go#L127-L130
train
btcsuite/btcd
rpcclient/net.go
GetAddedNodeInfoNoDNSAsync
func (c *Client) GetAddedNodeInfoNoDNSAsync(peer string) FutureGetAddedNodeInfoNoDNSResult { cmd := btcjson.NewGetAddedNodeInfoCmd(false, &peer) return c.sendCmd(cmd) }
go
func (c *Client) GetAddedNodeInfoNoDNSAsync(peer string) FutureGetAddedNodeInfoNoDNSResult { cmd := btcjson.NewGetAddedNodeInfoCmd(false, &peer) return c.sendCmd(cmd) }
[ "func", "(", "c", "*", "Client", ")", "GetAddedNodeInfoNoDNSAsync", "(", "peer", "string", ")", "FutureGetAddedNodeInfoNoDNSResult", "{", "cmd", ":=", "btcjson", ".", "NewGetAddedNodeInfoCmd", "(", "false", ",", "&", "peer", ")", "\n", "return", "c", ".", "sendCmd", "(", "cmd", ")", "\n", "}" ]
// GetAddedNodeInfoNoDNSAsync returns an instance of a type that can be used to // get the result of the RPC at some future time by invoking the Receive // function on the returned instance. // // See GetAddedNodeInfoNoDNS for the blocking version and more details.
[ "GetAddedNodeInfoNoDNSAsync", "returns", "an", "instance", "of", "a", "type", "that", "can", "be", "used", "to", "get", "the", "result", "of", "the", "RPC", "at", "some", "future", "time", "by", "invoking", "the", "Receive", "function", "on", "the", "returned", "instance", ".", "See", "GetAddedNodeInfoNoDNS", "for", "the", "blocking", "version", "and", "more", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/net.go#L167-L170
train
btcsuite/btcd
rpcclient/net.go
GetConnectionCountAsync
func (c *Client) GetConnectionCountAsync() FutureGetConnectionCountResult { cmd := btcjson.NewGetConnectionCountCmd() return c.sendCmd(cmd) }
go
func (c *Client) GetConnectionCountAsync() FutureGetConnectionCountResult { cmd := btcjson.NewGetConnectionCountCmd() return c.sendCmd(cmd) }
[ "func", "(", "c", "*", "Client", ")", "GetConnectionCountAsync", "(", ")", "FutureGetConnectionCountResult", "{", "cmd", ":=", "btcjson", ".", "NewGetConnectionCountCmd", "(", ")", "\n", "return", "c", ".", "sendCmd", "(", "cmd", ")", "\n", "}" ]
// GetConnectionCountAsync returns an instance of a type that can be used to get // the result of the RPC at some future time by invoking the Receive function on // the returned instance. // // See GetConnectionCount for the blocking version and more details.
[ "GetConnectionCountAsync", "returns", "an", "instance", "of", "a", "type", "that", "can", "be", "used", "to", "get", "the", "result", "of", "the", "RPC", "at", "some", "future", "time", "by", "invoking", "the", "Receive", "function", "on", "the", "returned", "instance", ".", "See", "GetConnectionCount", "for", "the", "blocking", "version", "and", "more", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/net.go#L208-L211
train
btcsuite/btcd
rpcclient/net.go
PingAsync
func (c *Client) PingAsync() FuturePingResult { cmd := btcjson.NewPingCmd() return c.sendCmd(cmd) }
go
func (c *Client) PingAsync() FuturePingResult { cmd := btcjson.NewPingCmd() return c.sendCmd(cmd) }
[ "func", "(", "c", "*", "Client", ")", "PingAsync", "(", ")", "FuturePingResult", "{", "cmd", ":=", "btcjson", ".", "NewPingCmd", "(", ")", "\n", "return", "c", ".", "sendCmd", "(", "cmd", ")", "\n", "}" ]
// PingAsync returns an instance of a type that can be used to get the result of // the RPC at some future time by invoking the Receive function on the returned // instance. // // See Ping for the blocking version and more details.
[ "PingAsync", "returns", "an", "instance", "of", "a", "type", "that", "can", "be", "used", "to", "get", "the", "result", "of", "the", "RPC", "at", "some", "future", "time", "by", "invoking", "the", "Receive", "function", "on", "the", "returned", "instance", ".", "See", "Ping", "for", "the", "blocking", "version", "and", "more", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/net.go#L234-L237
train
btcsuite/btcd
rpcclient/net.go
Receive
func (r FutureGetPeerInfoResult) Receive() ([]btcjson.GetPeerInfoResult, error) { res, err := receiveFuture(r) if err != nil { return nil, err } // Unmarshal result as an array of getpeerinfo result objects. var peerInfo []btcjson.GetPeerInfoResult err = json.Unmarshal(res, &peerInfo) if err != nil { return nil, err } return peerInfo, nil }
go
func (r FutureGetPeerInfoResult) Receive() ([]btcjson.GetPeerInfoResult, error) { res, err := receiveFuture(r) if err != nil { return nil, err } // Unmarshal result as an array of getpeerinfo result objects. var peerInfo []btcjson.GetPeerInfoResult err = json.Unmarshal(res, &peerInfo) if err != nil { return nil, err } return peerInfo, nil }
[ "func", "(", "r", "FutureGetPeerInfoResult", ")", "Receive", "(", ")", "(", "[", "]", "btcjson", ".", "GetPeerInfoResult", ",", "error", ")", "{", "res", ",", "err", ":=", "receiveFuture", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Unmarshal result as an array of getpeerinfo result objects.", "var", "peerInfo", "[", "]", "btcjson", ".", "GetPeerInfoResult", "\n", "err", "=", "json", ".", "Unmarshal", "(", "res", ",", "&", "peerInfo", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "peerInfo", ",", "nil", "\n", "}" ]
// Receive waits for the response promised by the future and returns data about // each connected network peer.
[ "Receive", "waits", "for", "the", "response", "promised", "by", "the", "future", "and", "returns", "data", "about", "each", "connected", "network", "peer", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/net.go#L253-L267
train
btcsuite/btcd
rpcclient/net.go
GetPeerInfoAsync
func (c *Client) GetPeerInfoAsync() FutureGetPeerInfoResult { cmd := btcjson.NewGetPeerInfoCmd() return c.sendCmd(cmd) }
go
func (c *Client) GetPeerInfoAsync() FutureGetPeerInfoResult { cmd := btcjson.NewGetPeerInfoCmd() return c.sendCmd(cmd) }
[ "func", "(", "c", "*", "Client", ")", "GetPeerInfoAsync", "(", ")", "FutureGetPeerInfoResult", "{", "cmd", ":=", "btcjson", ".", "NewGetPeerInfoCmd", "(", ")", "\n", "return", "c", ".", "sendCmd", "(", "cmd", ")", "\n", "}" ]
// GetPeerInfoAsync returns an instance of a type that can be used to get the // result of the RPC at some future time by invoking the Receive function on the // returned instance. // // See GetPeerInfo for the blocking version and more details.
[ "GetPeerInfoAsync", "returns", "an", "instance", "of", "a", "type", "that", "can", "be", "used", "to", "get", "the", "result", "of", "the", "RPC", "at", "some", "future", "time", "by", "invoking", "the", "Receive", "function", "on", "the", "returned", "instance", ".", "See", "GetPeerInfo", "for", "the", "blocking", "version", "and", "more", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/net.go#L274-L277
train
btcsuite/btcd
rpcclient/net.go
Receive
func (r FutureGetNetTotalsResult) Receive() (*btcjson.GetNetTotalsResult, error) { res, err := receiveFuture(r) if err != nil { return nil, err } // Unmarshal result as a getnettotals result object. var totals btcjson.GetNetTotalsResult err = json.Unmarshal(res, &totals) if err != nil { return nil, err } return &totals, nil }
go
func (r FutureGetNetTotalsResult) Receive() (*btcjson.GetNetTotalsResult, error) { res, err := receiveFuture(r) if err != nil { return nil, err } // Unmarshal result as a getnettotals result object. var totals btcjson.GetNetTotalsResult err = json.Unmarshal(res, &totals) if err != nil { return nil, err } return &totals, nil }
[ "func", "(", "r", "FutureGetNetTotalsResult", ")", "Receive", "(", ")", "(", "*", "btcjson", ".", "GetNetTotalsResult", ",", "error", ")", "{", "res", ",", "err", ":=", "receiveFuture", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Unmarshal result as a getnettotals result object.", "var", "totals", "btcjson", ".", "GetNetTotalsResult", "\n", "err", "=", "json", ".", "Unmarshal", "(", "res", ",", "&", "totals", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "totals", ",", "nil", "\n", "}" ]
// Receive waits for the response promised by the future and returns network // traffic statistics.
[ "Receive", "waits", "for", "the", "response", "promised", "by", "the", "future", "and", "returns", "network", "traffic", "statistics", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/net.go#L290-L304
train
btcsuite/btcd
rpcclient/net.go
GetNetTotalsAsync
func (c *Client) GetNetTotalsAsync() FutureGetNetTotalsResult { cmd := btcjson.NewGetNetTotalsCmd() return c.sendCmd(cmd) }
go
func (c *Client) GetNetTotalsAsync() FutureGetNetTotalsResult { cmd := btcjson.NewGetNetTotalsCmd() return c.sendCmd(cmd) }
[ "func", "(", "c", "*", "Client", ")", "GetNetTotalsAsync", "(", ")", "FutureGetNetTotalsResult", "{", "cmd", ":=", "btcjson", ".", "NewGetNetTotalsCmd", "(", ")", "\n", "return", "c", ".", "sendCmd", "(", "cmd", ")", "\n", "}" ]
// GetNetTotalsAsync returns an instance of a type that can be used to get the // result of the RPC at some future time by invoking the Receive function on the // returned instance. // // See GetNetTotals for the blocking version and more details.
[ "GetNetTotalsAsync", "returns", "an", "instance", "of", "a", "type", "that", "can", "be", "used", "to", "get", "the", "result", "of", "the", "RPC", "at", "some", "future", "time", "by", "invoking", "the", "Receive", "function", "on", "the", "returned", "instance", ".", "See", "GetNetTotals", "for", "the", "blocking", "version", "and", "more", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/net.go#L311-L314
train
btcsuite/btcd
blockchain/mediantime.go
Swap
func (s int64Sorter) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
go
func (s int64Sorter) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
[ "func", "(", "s", "int64Sorter", ")", "Swap", "(", "i", ",", "j", "int", ")", "{", "s", "[", "i", "]", ",", "s", "[", "j", "]", "=", "s", "[", "j", "]", ",", "s", "[", "i", "]", "\n", "}" ]
// Swap swaps the 64-bit integers at the passed indices. It is part of the // sort.Interface implementation.
[ "Swap", "swaps", "the", "64", "-", "bit", "integers", "at", "the", "passed", "indices", ".", "It", "is", "part", "of", "the", "sort", ".", "Interface", "implementation", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/mediantime.go#L62-L64
train
btcsuite/btcd
blockchain/mediantime.go
Less
func (s int64Sorter) Less(i, j int) bool { return s[i] < s[j] }
go
func (s int64Sorter) Less(i, j int) bool { return s[i] < s[j] }
[ "func", "(", "s", "int64Sorter", ")", "Less", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "s", "[", "i", "]", "<", "s", "[", "j", "]", "\n", "}" ]
// Less returns whether the 64-bit integer with index i should sort before the // 64-bit integer with index j. It is part of the sort.Interface // implementation.
[ "Less", "returns", "whether", "the", "64", "-", "bit", "integer", "with", "index", "i", "should", "sort", "before", "the", "64", "-", "bit", "integer", "with", "index", "j", ".", "It", "is", "part", "of", "the", "sort", ".", "Interface", "implementation", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/mediantime.go#L69-L71
train
btcsuite/btcd
blockchain/mediantime.go
AdjustedTime
func (m *medianTime) AdjustedTime() time.Time { m.mtx.Lock() defer m.mtx.Unlock() // Limit the adjusted time to 1 second precision. now := time.Unix(time.Now().Unix(), 0) return now.Add(time.Duration(m.offsetSecs) * time.Second) }
go
func (m *medianTime) AdjustedTime() time.Time { m.mtx.Lock() defer m.mtx.Unlock() // Limit the adjusted time to 1 second precision. now := time.Unix(time.Now().Unix(), 0) return now.Add(time.Duration(m.offsetSecs) * time.Second) }
[ "func", "(", "m", "*", "medianTime", ")", "AdjustedTime", "(", ")", "time", ".", "Time", "{", "m", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "// Limit the adjusted time to 1 second precision.", "now", ":=", "time", ".", "Unix", "(", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", ",", "0", ")", "\n", "return", "now", ".", "Add", "(", "time", ".", "Duration", "(", "m", ".", "offsetSecs", ")", "*", "time", ".", "Second", ")", "\n", "}" ]
// AdjustedTime returns the current time adjusted by the median time offset as // calculated from the time samples added by AddTimeSample. // // This function is safe for concurrent access and is part of the // MedianTimeSource interface implementation.
[ "AdjustedTime", "returns", "the", "current", "time", "adjusted", "by", "the", "median", "time", "offset", "as", "calculated", "from", "the", "time", "samples", "added", "by", "AddTimeSample", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "and", "is", "part", "of", "the", "MedianTimeSource", "interface", "implementation", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/mediantime.go#L93-L100
train
btcsuite/btcd
blockchain/mediantime.go
AddTimeSample
func (m *medianTime) AddTimeSample(sourceID string, timeVal time.Time) { m.mtx.Lock() defer m.mtx.Unlock() // Don't add time data from the same source. if _, exists := m.knownIDs[sourceID]; exists { return } m.knownIDs[sourceID] = struct{}{} // Truncate the provided offset to seconds and append it to the slice // of offsets while respecting the maximum number of allowed entries by // replacing the oldest entry with the new entry once the maximum number // of entries is reached. now := time.Unix(time.Now().Unix(), 0) offsetSecs := int64(timeVal.Sub(now).Seconds()) numOffsets := len(m.offsets) if numOffsets == maxMedianTimeEntries && maxMedianTimeEntries > 0 { m.offsets = m.offsets[1:] numOffsets-- } m.offsets = append(m.offsets, offsetSecs) numOffsets++ // Sort the offsets so the median can be obtained as needed later. sortedOffsets := make([]int64, numOffsets) copy(sortedOffsets, m.offsets) sort.Sort(int64Sorter(sortedOffsets)) offsetDuration := time.Duration(offsetSecs) * time.Second log.Debugf("Added time sample of %v (total: %v)", offsetDuration, numOffsets) // NOTE: The following code intentionally has a bug to mirror the // buggy behavior in Bitcoin Core since the median time is used in the // consensus rules. // // In particular, the offset is only updated when the number of entries // is odd, but the max number of entries is 200, an even number. Thus, // the offset will never be updated again once the max number of entries // is reached. // The median offset is only updated when there are enough offsets and // the number of offsets is odd so the middle value is the true median. // Thus, there is nothing to do when those conditions are not met. if numOffsets < 5 || numOffsets&0x01 != 1 { return } // At this point the number of offsets in the list is odd, so the // middle value of the sorted offsets is the median. median := sortedOffsets[numOffsets/2] // Set the new offset when the median offset is within the allowed // offset range. if math.Abs(float64(median)) < maxAllowedOffsetSecs { m.offsetSecs = median } else { // The median offset of all added time data is larger than the // maximum allowed offset, so don't use an offset. This // effectively limits how far the local clock can be skewed. m.offsetSecs = 0 if !m.invalidTimeChecked { m.invalidTimeChecked = true // Find if any time samples have a time that is close // to the local time. var remoteHasCloseTime bool for _, offset := range sortedOffsets { if math.Abs(float64(offset)) < similarTimeSecs { remoteHasCloseTime = true break } } // Warn if none of the time samples are close. if !remoteHasCloseTime { log.Warnf("Please check your date and time " + "are correct! btcd will not work " + "properly with an invalid time") } } } medianDuration := time.Duration(m.offsetSecs) * time.Second log.Debugf("New time offset: %v", medianDuration) }
go
func (m *medianTime) AddTimeSample(sourceID string, timeVal time.Time) { m.mtx.Lock() defer m.mtx.Unlock() // Don't add time data from the same source. if _, exists := m.knownIDs[sourceID]; exists { return } m.knownIDs[sourceID] = struct{}{} // Truncate the provided offset to seconds and append it to the slice // of offsets while respecting the maximum number of allowed entries by // replacing the oldest entry with the new entry once the maximum number // of entries is reached. now := time.Unix(time.Now().Unix(), 0) offsetSecs := int64(timeVal.Sub(now).Seconds()) numOffsets := len(m.offsets) if numOffsets == maxMedianTimeEntries && maxMedianTimeEntries > 0 { m.offsets = m.offsets[1:] numOffsets-- } m.offsets = append(m.offsets, offsetSecs) numOffsets++ // Sort the offsets so the median can be obtained as needed later. sortedOffsets := make([]int64, numOffsets) copy(sortedOffsets, m.offsets) sort.Sort(int64Sorter(sortedOffsets)) offsetDuration := time.Duration(offsetSecs) * time.Second log.Debugf("Added time sample of %v (total: %v)", offsetDuration, numOffsets) // NOTE: The following code intentionally has a bug to mirror the // buggy behavior in Bitcoin Core since the median time is used in the // consensus rules. // // In particular, the offset is only updated when the number of entries // is odd, but the max number of entries is 200, an even number. Thus, // the offset will never be updated again once the max number of entries // is reached. // The median offset is only updated when there are enough offsets and // the number of offsets is odd so the middle value is the true median. // Thus, there is nothing to do when those conditions are not met. if numOffsets < 5 || numOffsets&0x01 != 1 { return } // At this point the number of offsets in the list is odd, so the // middle value of the sorted offsets is the median. median := sortedOffsets[numOffsets/2] // Set the new offset when the median offset is within the allowed // offset range. if math.Abs(float64(median)) < maxAllowedOffsetSecs { m.offsetSecs = median } else { // The median offset of all added time data is larger than the // maximum allowed offset, so don't use an offset. This // effectively limits how far the local clock can be skewed. m.offsetSecs = 0 if !m.invalidTimeChecked { m.invalidTimeChecked = true // Find if any time samples have a time that is close // to the local time. var remoteHasCloseTime bool for _, offset := range sortedOffsets { if math.Abs(float64(offset)) < similarTimeSecs { remoteHasCloseTime = true break } } // Warn if none of the time samples are close. if !remoteHasCloseTime { log.Warnf("Please check your date and time " + "are correct! btcd will not work " + "properly with an invalid time") } } } medianDuration := time.Duration(m.offsetSecs) * time.Second log.Debugf("New time offset: %v", medianDuration) }
[ "func", "(", "m", "*", "medianTime", ")", "AddTimeSample", "(", "sourceID", "string", ",", "timeVal", "time", ".", "Time", ")", "{", "m", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "// Don't add time data from the same source.", "if", "_", ",", "exists", ":=", "m", ".", "knownIDs", "[", "sourceID", "]", ";", "exists", "{", "return", "\n", "}", "\n", "m", ".", "knownIDs", "[", "sourceID", "]", "=", "struct", "{", "}", "{", "}", "\n\n", "// Truncate the provided offset to seconds and append it to the slice", "// of offsets while respecting the maximum number of allowed entries by", "// replacing the oldest entry with the new entry once the maximum number", "// of entries is reached.", "now", ":=", "time", ".", "Unix", "(", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", ",", "0", ")", "\n", "offsetSecs", ":=", "int64", "(", "timeVal", ".", "Sub", "(", "now", ")", ".", "Seconds", "(", ")", ")", "\n", "numOffsets", ":=", "len", "(", "m", ".", "offsets", ")", "\n", "if", "numOffsets", "==", "maxMedianTimeEntries", "&&", "maxMedianTimeEntries", ">", "0", "{", "m", ".", "offsets", "=", "m", ".", "offsets", "[", "1", ":", "]", "\n", "numOffsets", "--", "\n", "}", "\n", "m", ".", "offsets", "=", "append", "(", "m", ".", "offsets", ",", "offsetSecs", ")", "\n", "numOffsets", "++", "\n\n", "// Sort the offsets so the median can be obtained as needed later.", "sortedOffsets", ":=", "make", "(", "[", "]", "int64", ",", "numOffsets", ")", "\n", "copy", "(", "sortedOffsets", ",", "m", ".", "offsets", ")", "\n", "sort", ".", "Sort", "(", "int64Sorter", "(", "sortedOffsets", ")", ")", "\n\n", "offsetDuration", ":=", "time", ".", "Duration", "(", "offsetSecs", ")", "*", "time", ".", "Second", "\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "offsetDuration", ",", "numOffsets", ")", "\n\n", "// NOTE: The following code intentionally has a bug to mirror the", "// buggy behavior in Bitcoin Core since the median time is used in the", "// consensus rules.", "//", "// In particular, the offset is only updated when the number of entries", "// is odd, but the max number of entries is 200, an even number. Thus,", "// the offset will never be updated again once the max number of entries", "// is reached.", "// The median offset is only updated when there are enough offsets and", "// the number of offsets is odd so the middle value is the true median.", "// Thus, there is nothing to do when those conditions are not met.", "if", "numOffsets", "<", "5", "||", "numOffsets", "&", "0x01", "!=", "1", "{", "return", "\n", "}", "\n\n", "// At this point the number of offsets in the list is odd, so the", "// middle value of the sorted offsets is the median.", "median", ":=", "sortedOffsets", "[", "numOffsets", "/", "2", "]", "\n\n", "// Set the new offset when the median offset is within the allowed", "// offset range.", "if", "math", ".", "Abs", "(", "float64", "(", "median", ")", ")", "<", "maxAllowedOffsetSecs", "{", "m", ".", "offsetSecs", "=", "median", "\n", "}", "else", "{", "// The median offset of all added time data is larger than the", "// maximum allowed offset, so don't use an offset. This", "// effectively limits how far the local clock can be skewed.", "m", ".", "offsetSecs", "=", "0", "\n\n", "if", "!", "m", ".", "invalidTimeChecked", "{", "m", ".", "invalidTimeChecked", "=", "true", "\n\n", "// Find if any time samples have a time that is close", "// to the local time.", "var", "remoteHasCloseTime", "bool", "\n", "for", "_", ",", "offset", ":=", "range", "sortedOffsets", "{", "if", "math", ".", "Abs", "(", "float64", "(", "offset", ")", ")", "<", "similarTimeSecs", "{", "remoteHasCloseTime", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n\n", "// Warn if none of the time samples are close.", "if", "!", "remoteHasCloseTime", "{", "log", ".", "Warnf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "medianDuration", ":=", "time", ".", "Duration", "(", "m", ".", "offsetSecs", ")", "*", "time", ".", "Second", "\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "medianDuration", ")", "\n", "}" ]
// AddTimeSample adds a time sample that is used when determining the median // time of the added samples. // // This function is safe for concurrent access and is part of the // MedianTimeSource interface implementation.
[ "AddTimeSample", "adds", "a", "time", "sample", "that", "is", "used", "when", "determining", "the", "median", "time", "of", "the", "added", "samples", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "and", "is", "part", "of", "the", "MedianTimeSource", "interface", "implementation", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/mediantime.go#L107-L194
train
btcsuite/btcd
blockchain/mediantime.go
Offset
func (m *medianTime) Offset() time.Duration { m.mtx.Lock() defer m.mtx.Unlock() return time.Duration(m.offsetSecs) * time.Second }
go
func (m *medianTime) Offset() time.Duration { m.mtx.Lock() defer m.mtx.Unlock() return time.Duration(m.offsetSecs) * time.Second }
[ "func", "(", "m", "*", "medianTime", ")", "Offset", "(", ")", "time", ".", "Duration", "{", "m", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "return", "time", ".", "Duration", "(", "m", ".", "offsetSecs", ")", "*", "time", ".", "Second", "\n", "}" ]
// Offset returns the number of seconds to adjust the local clock based upon the // median of the time samples added by AddTimeData. // // This function is safe for concurrent access and is part of the // MedianTimeSource interface implementation.
[ "Offset", "returns", "the", "number", "of", "seconds", "to", "adjust", "the", "local", "clock", "based", "upon", "the", "median", "of", "the", "time", "samples", "added", "by", "AddTimeData", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "and", "is", "part", "of", "the", "MedianTimeSource", "interface", "implementation", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/mediantime.go#L201-L206
train
btcsuite/btcd
blockchain/mediantime.go
NewMedianTime
func NewMedianTime() MedianTimeSource { return &medianTime{ knownIDs: make(map[string]struct{}), offsets: make([]int64, 0, maxMedianTimeEntries), } }
go
func NewMedianTime() MedianTimeSource { return &medianTime{ knownIDs: make(map[string]struct{}), offsets: make([]int64, 0, maxMedianTimeEntries), } }
[ "func", "NewMedianTime", "(", ")", "MedianTimeSource", "{", "return", "&", "medianTime", "{", "knownIDs", ":", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", ",", "offsets", ":", "make", "(", "[", "]", "int64", ",", "0", ",", "maxMedianTimeEntries", ")", ",", "}", "\n", "}" ]
// NewMedianTime returns a new instance of concurrency-safe implementation of // the MedianTimeSource interface. The returned implementation contains the // rules necessary for proper time handling in the chain consensus rules and // expects the time samples to be added from the timestamp field of the version // message received from remote peers that successfully connect and negotiate.
[ "NewMedianTime", "returns", "a", "new", "instance", "of", "concurrency", "-", "safe", "implementation", "of", "the", "MedianTimeSource", "interface", ".", "The", "returned", "implementation", "contains", "the", "rules", "necessary", "for", "proper", "time", "handling", "in", "the", "chain", "consensus", "rules", "and", "expects", "the", "time", "samples", "to", "be", "added", "from", "the", "timestamp", "field", "of", "the", "version", "message", "received", "from", "remote", "peers", "that", "successfully", "connect", "and", "negotiate", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/mediantime.go#L213-L218
train
btcsuite/btcd
rpcwebsocket.go
WebsocketHandler
func (s *rpcServer) WebsocketHandler(conn *websocket.Conn, remoteAddr string, authenticated bool, isAdmin bool) { // Clear the read deadline that was set before the websocket hijacked // the connection. conn.SetReadDeadline(timeZeroVal) // Limit max number of websocket clients. rpcsLog.Infof("New websocket client %s", remoteAddr) if s.ntfnMgr.NumClients()+1 > cfg.RPCMaxWebsockets { rpcsLog.Infof("Max websocket clients exceeded [%d] - "+ "disconnecting client %s", cfg.RPCMaxWebsockets, remoteAddr) conn.Close() return } // Create a new websocket client to handle the new websocket connection // and wait for it to shutdown. Once it has shutdown (and hence // disconnected), remove it and any notifications it registered for. client, err := newWebsocketClient(s, conn, remoteAddr, authenticated, isAdmin) if err != nil { rpcsLog.Errorf("Failed to serve client %s: %v", remoteAddr, err) conn.Close() return } s.ntfnMgr.AddClient(client) client.Start() client.WaitForShutdown() s.ntfnMgr.RemoveClient(client) rpcsLog.Infof("Disconnected websocket client %s", remoteAddr) }
go
func (s *rpcServer) WebsocketHandler(conn *websocket.Conn, remoteAddr string, authenticated bool, isAdmin bool) { // Clear the read deadline that was set before the websocket hijacked // the connection. conn.SetReadDeadline(timeZeroVal) // Limit max number of websocket clients. rpcsLog.Infof("New websocket client %s", remoteAddr) if s.ntfnMgr.NumClients()+1 > cfg.RPCMaxWebsockets { rpcsLog.Infof("Max websocket clients exceeded [%d] - "+ "disconnecting client %s", cfg.RPCMaxWebsockets, remoteAddr) conn.Close() return } // Create a new websocket client to handle the new websocket connection // and wait for it to shutdown. Once it has shutdown (and hence // disconnected), remove it and any notifications it registered for. client, err := newWebsocketClient(s, conn, remoteAddr, authenticated, isAdmin) if err != nil { rpcsLog.Errorf("Failed to serve client %s: %v", remoteAddr, err) conn.Close() return } s.ntfnMgr.AddClient(client) client.Start() client.WaitForShutdown() s.ntfnMgr.RemoveClient(client) rpcsLog.Infof("Disconnected websocket client %s", remoteAddr) }
[ "func", "(", "s", "*", "rpcServer", ")", "WebsocketHandler", "(", "conn", "*", "websocket", ".", "Conn", ",", "remoteAddr", "string", ",", "authenticated", "bool", ",", "isAdmin", "bool", ")", "{", "// Clear the read deadline that was set before the websocket hijacked", "// the connection.", "conn", ".", "SetReadDeadline", "(", "timeZeroVal", ")", "\n\n", "// Limit max number of websocket clients.", "rpcsLog", ".", "Infof", "(", "\"", "\"", ",", "remoteAddr", ")", "\n", "if", "s", ".", "ntfnMgr", ".", "NumClients", "(", ")", "+", "1", ">", "cfg", ".", "RPCMaxWebsockets", "{", "rpcsLog", ".", "Infof", "(", "\"", "\"", "+", "\"", "\"", ",", "cfg", ".", "RPCMaxWebsockets", ",", "remoteAddr", ")", "\n", "conn", ".", "Close", "(", ")", "\n", "return", "\n", "}", "\n\n", "// Create a new websocket client to handle the new websocket connection", "// and wait for it to shutdown. Once it has shutdown (and hence", "// disconnected), remove it and any notifications it registered for.", "client", ",", "err", ":=", "newWebsocketClient", "(", "s", ",", "conn", ",", "remoteAddr", ",", "authenticated", ",", "isAdmin", ")", "\n", "if", "err", "!=", "nil", "{", "rpcsLog", ".", "Errorf", "(", "\"", "\"", ",", "remoteAddr", ",", "err", ")", "\n", "conn", ".", "Close", "(", ")", "\n", "return", "\n", "}", "\n", "s", ".", "ntfnMgr", ".", "AddClient", "(", "client", ")", "\n", "client", ".", "Start", "(", ")", "\n", "client", ".", "WaitForShutdown", "(", ")", "\n", "s", ".", "ntfnMgr", ".", "RemoveClient", "(", "client", ")", "\n", "rpcsLog", ".", "Infof", "(", "\"", "\"", ",", "remoteAddr", ")", "\n", "}" ]
// WebsocketHandler handles a new websocket client by creating a new wsClient, // starting it, and blocking until the connection closes. Since it blocks, it // must be run in a separate goroutine. It should be invoked from the websocket // server handler which runs each new connection in a new goroutine thereby // satisfying the requirement.
[ "WebsocketHandler", "handles", "a", "new", "websocket", "client", "by", "creating", "a", "new", "wsClient", "starting", "it", "and", "blocking", "until", "the", "connection", "closes", ".", "Since", "it", "blocks", "it", "must", "be", "run", "in", "a", "separate", "goroutine", ".", "It", "should", "be", "invoked", "from", "the", "websocket", "server", "handler", "which", "runs", "each", "new", "connection", "in", "a", "new", "goroutine", "thereby", "satisfying", "the", "requirement", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L86-L117
train
btcsuite/btcd
rpcwebsocket.go
queueHandler
func queueHandler(in <-chan interface{}, out chan<- interface{}, quit <-chan struct{}) { var q []interface{} var dequeue chan<- interface{} skipQueue := out var next interface{} out: for { select { case n, ok := <-in: if !ok { // Sender closed input channel. break out } // Either send to out immediately if skipQueue is // non-nil (queue is empty) and reader is ready, // or append to the queue and send later. select { case skipQueue <- n: default: q = append(q, n) dequeue = out skipQueue = nil next = q[0] } case dequeue <- next: copy(q, q[1:]) q[len(q)-1] = nil // avoid leak q = q[:len(q)-1] if len(q) == 0 { dequeue = nil skipQueue = out } else { next = q[0] } case <-quit: break out } } close(out) }
go
func queueHandler(in <-chan interface{}, out chan<- interface{}, quit <-chan struct{}) { var q []interface{} var dequeue chan<- interface{} skipQueue := out var next interface{} out: for { select { case n, ok := <-in: if !ok { // Sender closed input channel. break out } // Either send to out immediately if skipQueue is // non-nil (queue is empty) and reader is ready, // or append to the queue and send later. select { case skipQueue <- n: default: q = append(q, n) dequeue = out skipQueue = nil next = q[0] } case dequeue <- next: copy(q, q[1:]) q[len(q)-1] = nil // avoid leak q = q[:len(q)-1] if len(q) == 0 { dequeue = nil skipQueue = out } else { next = q[0] } case <-quit: break out } } close(out) }
[ "func", "queueHandler", "(", "in", "<-", "chan", "interface", "{", "}", ",", "out", "chan", "<-", "interface", "{", "}", ",", "quit", "<-", "chan", "struct", "{", "}", ")", "{", "var", "q", "[", "]", "interface", "{", "}", "\n", "var", "dequeue", "chan", "<-", "interface", "{", "}", "\n", "skipQueue", ":=", "out", "\n", "var", "next", "interface", "{", "}", "\n", "out", ":", "for", "{", "select", "{", "case", "n", ",", "ok", ":=", "<-", "in", ":", "if", "!", "ok", "{", "// Sender closed input channel.", "break", "out", "\n", "}", "\n\n", "// Either send to out immediately if skipQueue is", "// non-nil (queue is empty) and reader is ready,", "// or append to the queue and send later.", "select", "{", "case", "skipQueue", "<-", "n", ":", "default", ":", "q", "=", "append", "(", "q", ",", "n", ")", "\n", "dequeue", "=", "out", "\n", "skipQueue", "=", "nil", "\n", "next", "=", "q", "[", "0", "]", "\n", "}", "\n\n", "case", "dequeue", "<-", "next", ":", "copy", "(", "q", ",", "q", "[", "1", ":", "]", ")", "\n", "q", "[", "len", "(", "q", ")", "-", "1", "]", "=", "nil", "// avoid leak", "\n", "q", "=", "q", "[", ":", "len", "(", "q", ")", "-", "1", "]", "\n", "if", "len", "(", "q", ")", "==", "0", "{", "dequeue", "=", "nil", "\n", "skipQueue", "=", "out", "\n", "}", "else", "{", "next", "=", "q", "[", "0", "]", "\n", "}", "\n\n", "case", "<-", "quit", ":", "break", "out", "\n", "}", "\n", "}", "\n", "close", "(", "out", ")", "\n", "}" ]
// queueHandler manages a queue of empty interfaces, reading from in and // sending the oldest unsent to out. This handler stops when either of the // in or quit channels are closed, and closes out before returning, without // waiting to send any variables still remaining in the queue.
[ "queueHandler", "manages", "a", "queue", "of", "empty", "interfaces", "reading", "from", "in", "and", "sending", "the", "oldest", "unsent", "to", "out", ".", "This", "handler", "stops", "when", "either", "of", "the", "in", "or", "quit", "channels", "are", "closed", "and", "closes", "out", "before", "returning", "without", "waiting", "to", "send", "any", "variables", "still", "remaining", "in", "the", "queue", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L151-L193
train
btcsuite/btcd
rpcwebsocket.go
queueHandler
func (m *wsNotificationManager) queueHandler() { queueHandler(m.queueNotification, m.notificationMsgs, m.quit) m.wg.Done() }
go
func (m *wsNotificationManager) queueHandler() { queueHandler(m.queueNotification, m.notificationMsgs, m.quit) m.wg.Done() }
[ "func", "(", "m", "*", "wsNotificationManager", ")", "queueHandler", "(", ")", "{", "queueHandler", "(", "m", ".", "queueNotification", ",", "m", ".", "notificationMsgs", ",", "m", ".", "quit", ")", "\n", "m", ".", "wg", ".", "Done", "(", ")", "\n", "}" ]
// queueHandler maintains a queue of notifications and notification handler // control messages.
[ "queueHandler", "maintains", "a", "queue", "of", "notifications", "and", "notification", "handler", "control", "messages", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L197-L200
train
btcsuite/btcd
rpcwebsocket.go
NotifyBlockConnected
func (m *wsNotificationManager) NotifyBlockConnected(block *btcutil.Block) { // As NotifyBlockConnected will be called by the block manager // and the RPC server may no longer be running, use a select // statement to unblock enqueuing the notification once the RPC // server has begun shutting down. select { case m.queueNotification <- (*notificationBlockConnected)(block): case <-m.quit: } }
go
func (m *wsNotificationManager) NotifyBlockConnected(block *btcutil.Block) { // As NotifyBlockConnected will be called by the block manager // and the RPC server may no longer be running, use a select // statement to unblock enqueuing the notification once the RPC // server has begun shutting down. select { case m.queueNotification <- (*notificationBlockConnected)(block): case <-m.quit: } }
[ "func", "(", "m", "*", "wsNotificationManager", ")", "NotifyBlockConnected", "(", "block", "*", "btcutil", ".", "Block", ")", "{", "// As NotifyBlockConnected will be called by the block manager", "// and the RPC server may no longer be running, use a select", "// statement to unblock enqueuing the notification once the RPC", "// server has begun shutting down.", "select", "{", "case", "m", ".", "queueNotification", "<-", "(", "*", "notificationBlockConnected", ")", "(", "block", ")", ":", "case", "<-", "m", ".", "quit", ":", "}", "\n", "}" ]
// NotifyBlockConnected passes a block newly-connected to the best chain // to the notification manager for block and transaction notification // processing.
[ "NotifyBlockConnected", "passes", "a", "block", "newly", "-", "connected", "to", "the", "best", "chain", "to", "the", "notification", "manager", "for", "block", "and", "transaction", "notification", "processing", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L205-L214
train
btcsuite/btcd
rpcwebsocket.go
NotifyBlockDisconnected
func (m *wsNotificationManager) NotifyBlockDisconnected(block *btcutil.Block) { // As NotifyBlockDisconnected will be called by the block manager // and the RPC server may no longer be running, use a select // statement to unblock enqueuing the notification once the RPC // server has begun shutting down. select { case m.queueNotification <- (*notificationBlockDisconnected)(block): case <-m.quit: } }
go
func (m *wsNotificationManager) NotifyBlockDisconnected(block *btcutil.Block) { // As NotifyBlockDisconnected will be called by the block manager // and the RPC server may no longer be running, use a select // statement to unblock enqueuing the notification once the RPC // server has begun shutting down. select { case m.queueNotification <- (*notificationBlockDisconnected)(block): case <-m.quit: } }
[ "func", "(", "m", "*", "wsNotificationManager", ")", "NotifyBlockDisconnected", "(", "block", "*", "btcutil", ".", "Block", ")", "{", "// As NotifyBlockDisconnected will be called by the block manager", "// and the RPC server may no longer be running, use a select", "// statement to unblock enqueuing the notification once the RPC", "// server has begun shutting down.", "select", "{", "case", "m", ".", "queueNotification", "<-", "(", "*", "notificationBlockDisconnected", ")", "(", "block", ")", ":", "case", "<-", "m", ".", "quit", ":", "}", "\n", "}" ]
// NotifyBlockDisconnected passes a block disconnected from the best chain // to the notification manager for block notification processing.
[ "NotifyBlockDisconnected", "passes", "a", "block", "disconnected", "from", "the", "best", "chain", "to", "the", "notification", "manager", "for", "block", "notification", "processing", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L218-L227
train
btcsuite/btcd
rpcwebsocket.go
NotifyMempoolTx
func (m *wsNotificationManager) NotifyMempoolTx(tx *btcutil.Tx, isNew bool) { n := &notificationTxAcceptedByMempool{ isNew: isNew, tx: tx, } // As NotifyMempoolTx will be called by mempool and the RPC server // may no longer be running, use a select statement to unblock // enqueuing the notification once the RPC server has begun // shutting down. select { case m.queueNotification <- n: case <-m.quit: } }
go
func (m *wsNotificationManager) NotifyMempoolTx(tx *btcutil.Tx, isNew bool) { n := &notificationTxAcceptedByMempool{ isNew: isNew, tx: tx, } // As NotifyMempoolTx will be called by mempool and the RPC server // may no longer be running, use a select statement to unblock // enqueuing the notification once the RPC server has begun // shutting down. select { case m.queueNotification <- n: case <-m.quit: } }
[ "func", "(", "m", "*", "wsNotificationManager", ")", "NotifyMempoolTx", "(", "tx", "*", "btcutil", ".", "Tx", ",", "isNew", "bool", ")", "{", "n", ":=", "&", "notificationTxAcceptedByMempool", "{", "isNew", ":", "isNew", ",", "tx", ":", "tx", ",", "}", "\n\n", "// As NotifyMempoolTx will be called by mempool and the RPC server", "// may no longer be running, use a select statement to unblock", "// enqueuing the notification once the RPC server has begun", "// shutting down.", "select", "{", "case", "m", ".", "queueNotification", "<-", "n", ":", "case", "<-", "m", ".", "quit", ":", "}", "\n", "}" ]
// NotifyMempoolTx passes a transaction accepted by mempool to the // notification manager for transaction notification processing. If // isNew is true, the tx is is a new transaction, rather than one // added to the mempool during a reorg.
[ "NotifyMempoolTx", "passes", "a", "transaction", "accepted", "by", "mempool", "to", "the", "notification", "manager", "for", "transaction", "notification", "processing", ".", "If", "isNew", "is", "true", "the", "tx", "is", "is", "a", "new", "transaction", "rather", "than", "one", "added", "to", "the", "mempool", "during", "a", "reorg", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L233-L247
train
btcsuite/btcd
rpcwebsocket.go
NumClients
func (m *wsNotificationManager) NumClients() (n int) { select { case n = <-m.numClients: case <-m.quit: // Use default n (0) if server has shut down. } return }
go
func (m *wsNotificationManager) NumClients() (n int) { select { case n = <-m.numClients: case <-m.quit: // Use default n (0) if server has shut down. } return }
[ "func", "(", "m", "*", "wsNotificationManager", ")", "NumClients", "(", ")", "(", "n", "int", ")", "{", "select", "{", "case", "n", "=", "<-", "m", ".", "numClients", ":", "case", "<-", "m", ".", "quit", ":", "// Use default n (0) if server has shut down.", "}", "\n", "return", "\n", "}" ]
// NumClients returns the number of clients actively being served.
[ "NumClients", "returns", "the", "number", "of", "clients", "actively", "being", "served", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L608-L614
train
btcsuite/btcd
rpcwebsocket.go
subscribedClients
func (m *wsNotificationManager) subscribedClients(tx *btcutil.Tx, clients map[chan struct{}]*wsClient) map[chan struct{}]struct{} { // Use a map of client quit channels as keys to prevent duplicates when // multiple inputs and/or outputs are relevant to the client. subscribed := make(map[chan struct{}]struct{}) msgTx := tx.MsgTx() for _, input := range msgTx.TxIn { for quitChan, wsc := range clients { wsc.Lock() filter := wsc.filterData wsc.Unlock() if filter == nil { continue } filter.mu.Lock() if filter.existsUnspentOutPoint(&input.PreviousOutPoint) { subscribed[quitChan] = struct{}{} } filter.mu.Unlock() } } for i, output := range msgTx.TxOut { _, addrs, _, err := txscript.ExtractPkScriptAddrs( output.PkScript, m.server.cfg.ChainParams) if err != nil { // Clients are not able to subscribe to // nonstandard or non-address outputs. continue } for quitChan, wsc := range clients { wsc.Lock() filter := wsc.filterData wsc.Unlock() if filter == nil { continue } filter.mu.Lock() for _, a := range addrs { if filter.existsAddress(a) { subscribed[quitChan] = struct{}{} op := wire.OutPoint{ Hash: *tx.Hash(), Index: uint32(i), } filter.addUnspentOutPoint(&op) } } filter.mu.Unlock() } } return subscribed }
go
func (m *wsNotificationManager) subscribedClients(tx *btcutil.Tx, clients map[chan struct{}]*wsClient) map[chan struct{}]struct{} { // Use a map of client quit channels as keys to prevent duplicates when // multiple inputs and/or outputs are relevant to the client. subscribed := make(map[chan struct{}]struct{}) msgTx := tx.MsgTx() for _, input := range msgTx.TxIn { for quitChan, wsc := range clients { wsc.Lock() filter := wsc.filterData wsc.Unlock() if filter == nil { continue } filter.mu.Lock() if filter.existsUnspentOutPoint(&input.PreviousOutPoint) { subscribed[quitChan] = struct{}{} } filter.mu.Unlock() } } for i, output := range msgTx.TxOut { _, addrs, _, err := txscript.ExtractPkScriptAddrs( output.PkScript, m.server.cfg.ChainParams) if err != nil { // Clients are not able to subscribe to // nonstandard or non-address outputs. continue } for quitChan, wsc := range clients { wsc.Lock() filter := wsc.filterData wsc.Unlock() if filter == nil { continue } filter.mu.Lock() for _, a := range addrs { if filter.existsAddress(a) { subscribed[quitChan] = struct{}{} op := wire.OutPoint{ Hash: *tx.Hash(), Index: uint32(i), } filter.addUnspentOutPoint(&op) } } filter.mu.Unlock() } } return subscribed }
[ "func", "(", "m", "*", "wsNotificationManager", ")", "subscribedClients", "(", "tx", "*", "btcutil", ".", "Tx", ",", "clients", "map", "[", "chan", "struct", "{", "}", "]", "*", "wsClient", ")", "map", "[", "chan", "struct", "{", "}", "]", "struct", "{", "}", "{", "// Use a map of client quit channels as keys to prevent duplicates when", "// multiple inputs and/or outputs are relevant to the client.", "subscribed", ":=", "make", "(", "map", "[", "chan", "struct", "{", "}", "]", "struct", "{", "}", ")", "\n\n", "msgTx", ":=", "tx", ".", "MsgTx", "(", ")", "\n", "for", "_", ",", "input", ":=", "range", "msgTx", ".", "TxIn", "{", "for", "quitChan", ",", "wsc", ":=", "range", "clients", "{", "wsc", ".", "Lock", "(", ")", "\n", "filter", ":=", "wsc", ".", "filterData", "\n", "wsc", ".", "Unlock", "(", ")", "\n", "if", "filter", "==", "nil", "{", "continue", "\n", "}", "\n", "filter", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "filter", ".", "existsUnspentOutPoint", "(", "&", "input", ".", "PreviousOutPoint", ")", "{", "subscribed", "[", "quitChan", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "filter", ".", "mu", ".", "Unlock", "(", ")", "\n", "}", "\n", "}", "\n\n", "for", "i", ",", "output", ":=", "range", "msgTx", ".", "TxOut", "{", "_", ",", "addrs", ",", "_", ",", "err", ":=", "txscript", ".", "ExtractPkScriptAddrs", "(", "output", ".", "PkScript", ",", "m", ".", "server", ".", "cfg", ".", "ChainParams", ")", "\n", "if", "err", "!=", "nil", "{", "// Clients are not able to subscribe to", "// nonstandard or non-address outputs.", "continue", "\n", "}", "\n", "for", "quitChan", ",", "wsc", ":=", "range", "clients", "{", "wsc", ".", "Lock", "(", ")", "\n", "filter", ":=", "wsc", ".", "filterData", "\n", "wsc", ".", "Unlock", "(", ")", "\n", "if", "filter", "==", "nil", "{", "continue", "\n", "}", "\n", "filter", ".", "mu", ".", "Lock", "(", ")", "\n", "for", "_", ",", "a", ":=", "range", "addrs", "{", "if", "filter", ".", "existsAddress", "(", "a", ")", "{", "subscribed", "[", "quitChan", "]", "=", "struct", "{", "}", "{", "}", "\n", "op", ":=", "wire", ".", "OutPoint", "{", "Hash", ":", "*", "tx", ".", "Hash", "(", ")", ",", "Index", ":", "uint32", "(", "i", ")", ",", "}", "\n", "filter", ".", "addUnspentOutPoint", "(", "&", "op", ")", "\n", "}", "\n", "}", "\n", "filter", ".", "mu", ".", "Unlock", "(", ")", "\n", "}", "\n", "}", "\n\n", "return", "subscribed", "\n", "}" ]
// subscribedClients returns the set of all websocket client quit channels that // are registered to receive notifications regarding tx, either due to tx // spending a watched output or outputting to a watched address. Matching // client's filters are updated based on this transaction's outputs and output // addresses that may be relevant for a client.
[ "subscribedClients", "returns", "the", "set", "of", "all", "websocket", "client", "quit", "channels", "that", "are", "registered", "to", "receive", "notifications", "regarding", "tx", "either", "due", "to", "tx", "spending", "a", "watched", "output", "or", "outputting", "to", "a", "watched", "address", ".", "Matching", "client", "s", "filters", "are", "updated", "based", "on", "this", "transaction", "s", "outputs", "and", "output", "addresses", "that", "may", "be", "relevant", "for", "a", "client", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L633-L688
train
btcsuite/btcd
rpcwebsocket.go
notifyBlockConnected
func (*wsNotificationManager) notifyBlockConnected(clients map[chan struct{}]*wsClient, block *btcutil.Block) { // Notify interested websocket clients about the connected block. ntfn := btcjson.NewBlockConnectedNtfn(block.Hash().String(), block.Height(), block.MsgBlock().Header.Timestamp.Unix()) marshalledJSON, err := btcjson.MarshalCmd(nil, ntfn) if err != nil { rpcsLog.Errorf("Failed to marshal block connected notification: "+ "%v", err) return } for _, wsc := range clients { wsc.QueueNotification(marshalledJSON) } }
go
func (*wsNotificationManager) notifyBlockConnected(clients map[chan struct{}]*wsClient, block *btcutil.Block) { // Notify interested websocket clients about the connected block. ntfn := btcjson.NewBlockConnectedNtfn(block.Hash().String(), block.Height(), block.MsgBlock().Header.Timestamp.Unix()) marshalledJSON, err := btcjson.MarshalCmd(nil, ntfn) if err != nil { rpcsLog.Errorf("Failed to marshal block connected notification: "+ "%v", err) return } for _, wsc := range clients { wsc.QueueNotification(marshalledJSON) } }
[ "func", "(", "*", "wsNotificationManager", ")", "notifyBlockConnected", "(", "clients", "map", "[", "chan", "struct", "{", "}", "]", "*", "wsClient", ",", "block", "*", "btcutil", ".", "Block", ")", "{", "// Notify interested websocket clients about the connected block.", "ntfn", ":=", "btcjson", ".", "NewBlockConnectedNtfn", "(", "block", ".", "Hash", "(", ")", ".", "String", "(", ")", ",", "block", ".", "Height", "(", ")", ",", "block", ".", "MsgBlock", "(", ")", ".", "Header", ".", "Timestamp", ".", "Unix", "(", ")", ")", "\n", "marshalledJSON", ",", "err", ":=", "btcjson", ".", "MarshalCmd", "(", "nil", ",", "ntfn", ")", "\n", "if", "err", "!=", "nil", "{", "rpcsLog", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "for", "_", ",", "wsc", ":=", "range", "clients", "{", "wsc", ".", "QueueNotification", "(", "marshalledJSON", ")", "\n", "}", "\n", "}" ]
// notifyBlockConnected notifies websocket clients that have registered for // block updates when a block is connected to the main chain.
[ "notifyBlockConnected", "notifies", "websocket", "clients", "that", "have", "registered", "for", "block", "updates", "when", "a", "block", "is", "connected", "to", "the", "main", "chain", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L692-L707
train
btcsuite/btcd
rpcwebsocket.go
notifyFilteredBlockConnected
func (m *wsNotificationManager) notifyFilteredBlockConnected(clients map[chan struct{}]*wsClient, block *btcutil.Block) { // Create the common portion of the notification that is the same for // every client. var w bytes.Buffer err := block.MsgBlock().Header.Serialize(&w) if err != nil { rpcsLog.Errorf("Failed to serialize header for filtered block "+ "connected notification: %v", err) return } ntfn := btcjson.NewFilteredBlockConnectedNtfn(block.Height(), hex.EncodeToString(w.Bytes()), nil) // Search for relevant transactions for each client and save them // serialized in hex encoding for the notification. subscribedTxs := make(map[chan struct{}][]string) for _, tx := range block.Transactions() { var txHex string for quitChan := range m.subscribedClients(tx, clients) { if txHex == "" { txHex = txHexString(tx.MsgTx()) } subscribedTxs[quitChan] = append(subscribedTxs[quitChan], txHex) } } for quitChan, wsc := range clients { // Add all discovered transactions for this client. For clients // that have no new-style filter, add the empty string slice. ntfn.SubscribedTxs = subscribedTxs[quitChan] // Marshal and queue notification. marshalledJSON, err := btcjson.MarshalCmd(nil, ntfn) if err != nil { rpcsLog.Errorf("Failed to marshal filtered block "+ "connected notification: %v", err) return } wsc.QueueNotification(marshalledJSON) } }
go
func (m *wsNotificationManager) notifyFilteredBlockConnected(clients map[chan struct{}]*wsClient, block *btcutil.Block) { // Create the common portion of the notification that is the same for // every client. var w bytes.Buffer err := block.MsgBlock().Header.Serialize(&w) if err != nil { rpcsLog.Errorf("Failed to serialize header for filtered block "+ "connected notification: %v", err) return } ntfn := btcjson.NewFilteredBlockConnectedNtfn(block.Height(), hex.EncodeToString(w.Bytes()), nil) // Search for relevant transactions for each client and save them // serialized in hex encoding for the notification. subscribedTxs := make(map[chan struct{}][]string) for _, tx := range block.Transactions() { var txHex string for quitChan := range m.subscribedClients(tx, clients) { if txHex == "" { txHex = txHexString(tx.MsgTx()) } subscribedTxs[quitChan] = append(subscribedTxs[quitChan], txHex) } } for quitChan, wsc := range clients { // Add all discovered transactions for this client. For clients // that have no new-style filter, add the empty string slice. ntfn.SubscribedTxs = subscribedTxs[quitChan] // Marshal and queue notification. marshalledJSON, err := btcjson.MarshalCmd(nil, ntfn) if err != nil { rpcsLog.Errorf("Failed to marshal filtered block "+ "connected notification: %v", err) return } wsc.QueueNotification(marshalledJSON) } }
[ "func", "(", "m", "*", "wsNotificationManager", ")", "notifyFilteredBlockConnected", "(", "clients", "map", "[", "chan", "struct", "{", "}", "]", "*", "wsClient", ",", "block", "*", "btcutil", ".", "Block", ")", "{", "// Create the common portion of the notification that is the same for", "// every client.", "var", "w", "bytes", ".", "Buffer", "\n", "err", ":=", "block", ".", "MsgBlock", "(", ")", ".", "Header", ".", "Serialize", "(", "&", "w", ")", "\n", "if", "err", "!=", "nil", "{", "rpcsLog", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "ntfn", ":=", "btcjson", ".", "NewFilteredBlockConnectedNtfn", "(", "block", ".", "Height", "(", ")", ",", "hex", ".", "EncodeToString", "(", "w", ".", "Bytes", "(", ")", ")", ",", "nil", ")", "\n\n", "// Search for relevant transactions for each client and save them", "// serialized in hex encoding for the notification.", "subscribedTxs", ":=", "make", "(", "map", "[", "chan", "struct", "{", "}", "]", "[", "]", "string", ")", "\n", "for", "_", ",", "tx", ":=", "range", "block", ".", "Transactions", "(", ")", "{", "var", "txHex", "string", "\n", "for", "quitChan", ":=", "range", "m", ".", "subscribedClients", "(", "tx", ",", "clients", ")", "{", "if", "txHex", "==", "\"", "\"", "{", "txHex", "=", "txHexString", "(", "tx", ".", "MsgTx", "(", ")", ")", "\n", "}", "\n", "subscribedTxs", "[", "quitChan", "]", "=", "append", "(", "subscribedTxs", "[", "quitChan", "]", ",", "txHex", ")", "\n", "}", "\n", "}", "\n", "for", "quitChan", ",", "wsc", ":=", "range", "clients", "{", "// Add all discovered transactions for this client. For clients", "// that have no new-style filter, add the empty string slice.", "ntfn", ".", "SubscribedTxs", "=", "subscribedTxs", "[", "quitChan", "]", "\n\n", "// Marshal and queue notification.", "marshalledJSON", ",", "err", ":=", "btcjson", ".", "MarshalCmd", "(", "nil", ",", "ntfn", ")", "\n", "if", "err", "!=", "nil", "{", "rpcsLog", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "wsc", ".", "QueueNotification", "(", "marshalledJSON", ")", "\n", "}", "\n", "}" ]
// notifyFilteredBlockConnected notifies websocket clients that have registered for // block updates when a block is connected to the main chain.
[ "notifyFilteredBlockConnected", "notifies", "websocket", "clients", "that", "have", "registered", "for", "block", "updates", "when", "a", "block", "is", "connected", "to", "the", "main", "chain", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L735-L776
train
btcsuite/btcd
rpcwebsocket.go
notifyForNewTx
func (m *wsNotificationManager) notifyForNewTx(clients map[chan struct{}]*wsClient, tx *btcutil.Tx) { txHashStr := tx.Hash().String() mtx := tx.MsgTx() var amount int64 for _, txOut := range mtx.TxOut { amount += txOut.Value } ntfn := btcjson.NewTxAcceptedNtfn(txHashStr, btcutil.Amount(amount).ToBTC()) marshalledJSON, err := btcjson.MarshalCmd(nil, ntfn) if err != nil { rpcsLog.Errorf("Failed to marshal tx notification: %s", err.Error()) return } var verboseNtfn *btcjson.TxAcceptedVerboseNtfn var marshalledJSONVerbose []byte for _, wsc := range clients { if wsc.verboseTxUpdates { if marshalledJSONVerbose != nil { wsc.QueueNotification(marshalledJSONVerbose) continue } net := m.server.cfg.ChainParams rawTx, err := createTxRawResult(net, mtx, txHashStr, nil, "", 0, 0) if err != nil { return } verboseNtfn = btcjson.NewTxAcceptedVerboseNtfn(*rawTx) marshalledJSONVerbose, err = btcjson.MarshalCmd(nil, verboseNtfn) if err != nil { rpcsLog.Errorf("Failed to marshal verbose tx "+ "notification: %s", err.Error()) return } wsc.QueueNotification(marshalledJSONVerbose) } else { wsc.QueueNotification(marshalledJSON) } } }
go
func (m *wsNotificationManager) notifyForNewTx(clients map[chan struct{}]*wsClient, tx *btcutil.Tx) { txHashStr := tx.Hash().String() mtx := tx.MsgTx() var amount int64 for _, txOut := range mtx.TxOut { amount += txOut.Value } ntfn := btcjson.NewTxAcceptedNtfn(txHashStr, btcutil.Amount(amount).ToBTC()) marshalledJSON, err := btcjson.MarshalCmd(nil, ntfn) if err != nil { rpcsLog.Errorf("Failed to marshal tx notification: %s", err.Error()) return } var verboseNtfn *btcjson.TxAcceptedVerboseNtfn var marshalledJSONVerbose []byte for _, wsc := range clients { if wsc.verboseTxUpdates { if marshalledJSONVerbose != nil { wsc.QueueNotification(marshalledJSONVerbose) continue } net := m.server.cfg.ChainParams rawTx, err := createTxRawResult(net, mtx, txHashStr, nil, "", 0, 0) if err != nil { return } verboseNtfn = btcjson.NewTxAcceptedVerboseNtfn(*rawTx) marshalledJSONVerbose, err = btcjson.MarshalCmd(nil, verboseNtfn) if err != nil { rpcsLog.Errorf("Failed to marshal verbose tx "+ "notification: %s", err.Error()) return } wsc.QueueNotification(marshalledJSONVerbose) } else { wsc.QueueNotification(marshalledJSON) } } }
[ "func", "(", "m", "*", "wsNotificationManager", ")", "notifyForNewTx", "(", "clients", "map", "[", "chan", "struct", "{", "}", "]", "*", "wsClient", ",", "tx", "*", "btcutil", ".", "Tx", ")", "{", "txHashStr", ":=", "tx", ".", "Hash", "(", ")", ".", "String", "(", ")", "\n", "mtx", ":=", "tx", ".", "MsgTx", "(", ")", "\n\n", "var", "amount", "int64", "\n", "for", "_", ",", "txOut", ":=", "range", "mtx", ".", "TxOut", "{", "amount", "+=", "txOut", ".", "Value", "\n", "}", "\n\n", "ntfn", ":=", "btcjson", ".", "NewTxAcceptedNtfn", "(", "txHashStr", ",", "btcutil", ".", "Amount", "(", "amount", ")", ".", "ToBTC", "(", ")", ")", "\n", "marshalledJSON", ",", "err", ":=", "btcjson", ".", "MarshalCmd", "(", "nil", ",", "ntfn", ")", "\n", "if", "err", "!=", "nil", "{", "rpcsLog", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "return", "\n", "}", "\n\n", "var", "verboseNtfn", "*", "btcjson", ".", "TxAcceptedVerboseNtfn", "\n", "var", "marshalledJSONVerbose", "[", "]", "byte", "\n", "for", "_", ",", "wsc", ":=", "range", "clients", "{", "if", "wsc", ".", "verboseTxUpdates", "{", "if", "marshalledJSONVerbose", "!=", "nil", "{", "wsc", ".", "QueueNotification", "(", "marshalledJSONVerbose", ")", "\n", "continue", "\n", "}", "\n\n", "net", ":=", "m", ".", "server", ".", "cfg", ".", "ChainParams", "\n", "rawTx", ",", "err", ":=", "createTxRawResult", "(", "net", ",", "mtx", ",", "txHashStr", ",", "nil", ",", "\"", "\"", ",", "0", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "verboseNtfn", "=", "btcjson", ".", "NewTxAcceptedVerboseNtfn", "(", "*", "rawTx", ")", "\n", "marshalledJSONVerbose", ",", "err", "=", "btcjson", ".", "MarshalCmd", "(", "nil", ",", "verboseNtfn", ")", "\n", "if", "err", "!=", "nil", "{", "rpcsLog", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "return", "\n", "}", "\n", "wsc", ".", "QueueNotification", "(", "marshalledJSONVerbose", ")", "\n", "}", "else", "{", "wsc", ".", "QueueNotification", "(", "marshalledJSON", ")", "\n", "}", "\n", "}", "\n", "}" ]
// notifyForNewTx notifies websocket clients that have registered for updates // when a new transaction is added to the memory pool.
[ "notifyForNewTx", "notifies", "websocket", "clients", "that", "have", "registered", "for", "updates", "when", "a", "new", "transaction", "is", "added", "to", "the", "memory", "pool", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L824-L869
train
btcsuite/btcd
rpcwebsocket.go
addSpentRequests
func (m *wsNotificationManager) addSpentRequests(opMap map[wire.OutPoint]map[chan struct{}]*wsClient, wsc *wsClient, ops []*wire.OutPoint) { for _, op := range ops { // Track the request in the client as well so it can be quickly // be removed on disconnect. wsc.spentRequests[*op] = struct{}{} // Add the client to the list to notify when the outpoint is seen. // Create the list as needed. cmap, ok := opMap[*op] if !ok { cmap = make(map[chan struct{}]*wsClient) opMap[*op] = cmap } cmap[wsc.quit] = wsc } // Check if any transactions spending these outputs already exists in // the mempool, if so send the notification immediately. spends := make(map[chainhash.Hash]*btcutil.Tx) for _, op := range ops { spend := m.server.cfg.TxMemPool.CheckSpend(*op) if spend != nil { rpcsLog.Debugf("Found existing mempool spend for "+ "outpoint<%v>: %v", op, spend.Hash()) spends[*spend.Hash()] = spend } } for _, spend := range spends { m.notifyForTx(opMap, nil, spend, nil) } }
go
func (m *wsNotificationManager) addSpentRequests(opMap map[wire.OutPoint]map[chan struct{}]*wsClient, wsc *wsClient, ops []*wire.OutPoint) { for _, op := range ops { // Track the request in the client as well so it can be quickly // be removed on disconnect. wsc.spentRequests[*op] = struct{}{} // Add the client to the list to notify when the outpoint is seen. // Create the list as needed. cmap, ok := opMap[*op] if !ok { cmap = make(map[chan struct{}]*wsClient) opMap[*op] = cmap } cmap[wsc.quit] = wsc } // Check if any transactions spending these outputs already exists in // the mempool, if so send the notification immediately. spends := make(map[chainhash.Hash]*btcutil.Tx) for _, op := range ops { spend := m.server.cfg.TxMemPool.CheckSpend(*op) if spend != nil { rpcsLog.Debugf("Found existing mempool spend for "+ "outpoint<%v>: %v", op, spend.Hash()) spends[*spend.Hash()] = spend } } for _, spend := range spends { m.notifyForTx(opMap, nil, spend, nil) } }
[ "func", "(", "m", "*", "wsNotificationManager", ")", "addSpentRequests", "(", "opMap", "map", "[", "wire", ".", "OutPoint", "]", "map", "[", "chan", "struct", "{", "}", "]", "*", "wsClient", ",", "wsc", "*", "wsClient", ",", "ops", "[", "]", "*", "wire", ".", "OutPoint", ")", "{", "for", "_", ",", "op", ":=", "range", "ops", "{", "// Track the request in the client as well so it can be quickly", "// be removed on disconnect.", "wsc", ".", "spentRequests", "[", "*", "op", "]", "=", "struct", "{", "}", "{", "}", "\n\n", "// Add the client to the list to notify when the outpoint is seen.", "// Create the list as needed.", "cmap", ",", "ok", ":=", "opMap", "[", "*", "op", "]", "\n", "if", "!", "ok", "{", "cmap", "=", "make", "(", "map", "[", "chan", "struct", "{", "}", "]", "*", "wsClient", ")", "\n", "opMap", "[", "*", "op", "]", "=", "cmap", "\n", "}", "\n", "cmap", "[", "wsc", ".", "quit", "]", "=", "wsc", "\n", "}", "\n\n", "// Check if any transactions spending these outputs already exists in", "// the mempool, if so send the notification immediately.", "spends", ":=", "make", "(", "map", "[", "chainhash", ".", "Hash", "]", "*", "btcutil", ".", "Tx", ")", "\n", "for", "_", ",", "op", ":=", "range", "ops", "{", "spend", ":=", "m", ".", "server", ".", "cfg", ".", "TxMemPool", ".", "CheckSpend", "(", "*", "op", ")", "\n", "if", "spend", "!=", "nil", "{", "rpcsLog", ".", "Debugf", "(", "\"", "\"", "+", "\"", "\"", ",", "op", ",", "spend", ".", "Hash", "(", ")", ")", "\n", "spends", "[", "*", "spend", ".", "Hash", "(", ")", "]", "=", "spend", "\n", "}", "\n", "}", "\n\n", "for", "_", ",", "spend", ":=", "range", "spends", "{", "m", ".", "notifyForTx", "(", "opMap", ",", "nil", ",", "spend", ",", "nil", ")", "\n", "}", "\n", "}" ]
// addSpentRequests modifies a map of watched outpoints to sets of websocket // clients to add a new request watch all of the outpoints in ops and create // and send a notification when spent to the websocket client wsc.
[ "addSpentRequests", "modifies", "a", "map", "of", "watched", "outpoints", "to", "sets", "of", "websocket", "clients", "to", "add", "a", "new", "request", "watch", "all", "of", "the", "outpoints", "in", "ops", "and", "create", "and", "send", "a", "notification", "when", "spent", "to", "the", "websocket", "client", "wsc", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L885-L918
train
btcsuite/btcd
rpcwebsocket.go
removeSpentRequest
func (*wsNotificationManager) removeSpentRequest(ops map[wire.OutPoint]map[chan struct{}]*wsClient, wsc *wsClient, op *wire.OutPoint) { // Remove the request tracking from the client. delete(wsc.spentRequests, *op) // Remove the client from the list to notify. notifyMap, ok := ops[*op] if !ok { rpcsLog.Warnf("Attempt to remove nonexistent spent request "+ "for websocket client %s", wsc.addr) return } delete(notifyMap, wsc.quit) // Remove the map entry altogether if there are // no more clients interested in it. if len(notifyMap) == 0 { delete(ops, *op) } }
go
func (*wsNotificationManager) removeSpentRequest(ops map[wire.OutPoint]map[chan struct{}]*wsClient, wsc *wsClient, op *wire.OutPoint) { // Remove the request tracking from the client. delete(wsc.spentRequests, *op) // Remove the client from the list to notify. notifyMap, ok := ops[*op] if !ok { rpcsLog.Warnf("Attempt to remove nonexistent spent request "+ "for websocket client %s", wsc.addr) return } delete(notifyMap, wsc.quit) // Remove the map entry altogether if there are // no more clients interested in it. if len(notifyMap) == 0 { delete(ops, *op) } }
[ "func", "(", "*", "wsNotificationManager", ")", "removeSpentRequest", "(", "ops", "map", "[", "wire", ".", "OutPoint", "]", "map", "[", "chan", "struct", "{", "}", "]", "*", "wsClient", ",", "wsc", "*", "wsClient", ",", "op", "*", "wire", ".", "OutPoint", ")", "{", "// Remove the request tracking from the client.", "delete", "(", "wsc", ".", "spentRequests", ",", "*", "op", ")", "\n\n", "// Remove the client from the list to notify.", "notifyMap", ",", "ok", ":=", "ops", "[", "*", "op", "]", "\n", "if", "!", "ok", "{", "rpcsLog", ".", "Warnf", "(", "\"", "\"", "+", "\"", "\"", ",", "wsc", ".", "addr", ")", "\n", "return", "\n", "}", "\n", "delete", "(", "notifyMap", ",", "wsc", ".", "quit", ")", "\n\n", "// Remove the map entry altogether if there are", "// no more clients interested in it.", "if", "len", "(", "notifyMap", ")", "==", "0", "{", "delete", "(", "ops", ",", "*", "op", ")", "\n", "}", "\n", "}" ]
// removeSpentRequest modifies a map of watched outpoints to remove the // websocket client wsc from the set of clients to be notified when a // watched outpoint is spent. If wsc is the last client, the outpoint // key is removed from the map.
[ "removeSpentRequest", "modifies", "a", "map", "of", "watched", "outpoints", "to", "remove", "the", "websocket", "client", "wsc", "from", "the", "set", "of", "clients", "to", "be", "notified", "when", "a", "watched", "outpoint", "is", "spent", ".", "If", "wsc", "is", "the", "last", "client", "the", "outpoint", "key", "is", "removed", "from", "the", "map", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L934-L954
train
btcsuite/btcd
rpcwebsocket.go
txHexString
func txHexString(tx *wire.MsgTx) string { buf := bytes.NewBuffer(make([]byte, 0, tx.SerializeSize())) // Ignore Serialize's error, as writing to a bytes.buffer cannot fail. tx.Serialize(buf) return hex.EncodeToString(buf.Bytes()) }
go
func txHexString(tx *wire.MsgTx) string { buf := bytes.NewBuffer(make([]byte, 0, tx.SerializeSize())) // Ignore Serialize's error, as writing to a bytes.buffer cannot fail. tx.Serialize(buf) return hex.EncodeToString(buf.Bytes()) }
[ "func", "txHexString", "(", "tx", "*", "wire", ".", "MsgTx", ")", "string", "{", "buf", ":=", "bytes", ".", "NewBuffer", "(", "make", "(", "[", "]", "byte", ",", "0", ",", "tx", ".", "SerializeSize", "(", ")", ")", ")", "\n", "// Ignore Serialize's error, as writing to a bytes.buffer cannot fail.", "tx", ".", "Serialize", "(", "buf", ")", "\n", "return", "hex", ".", "EncodeToString", "(", "buf", ".", "Bytes", "(", ")", ")", "\n", "}" ]
// txHexString returns the serialized transaction encoded in hexadecimal.
[ "txHexString", "returns", "the", "serialized", "transaction", "encoded", "in", "hexadecimal", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L957-L962
train
btcsuite/btcd
rpcwebsocket.go
blockDetails
func blockDetails(block *btcutil.Block, txIndex int) *btcjson.BlockDetails { if block == nil { return nil } return &btcjson.BlockDetails{ Height: block.Height(), Hash: block.Hash().String(), Index: txIndex, Time: block.MsgBlock().Header.Timestamp.Unix(), } }
go
func blockDetails(block *btcutil.Block, txIndex int) *btcjson.BlockDetails { if block == nil { return nil } return &btcjson.BlockDetails{ Height: block.Height(), Hash: block.Hash().String(), Index: txIndex, Time: block.MsgBlock().Header.Timestamp.Unix(), } }
[ "func", "blockDetails", "(", "block", "*", "btcutil", ".", "Block", ",", "txIndex", "int", ")", "*", "btcjson", ".", "BlockDetails", "{", "if", "block", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "&", "btcjson", ".", "BlockDetails", "{", "Height", ":", "block", ".", "Height", "(", ")", ",", "Hash", ":", "block", ".", "Hash", "(", ")", ".", "String", "(", ")", ",", "Index", ":", "txIndex", ",", "Time", ":", "block", ".", "MsgBlock", "(", ")", ".", "Header", ".", "Timestamp", ".", "Unix", "(", ")", ",", "}", "\n", "}" ]
// blockDetails creates a BlockDetails struct to include in btcws notifications // from a block and a transaction's block index.
[ "blockDetails", "creates", "a", "BlockDetails", "struct", "to", "include", "in", "btcws", "notifications", "from", "a", "block", "and", "a", "transaction", "s", "block", "index", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L966-L976
train
btcsuite/btcd
rpcwebsocket.go
newRedeemingTxNotification
func newRedeemingTxNotification(txHex string, index int, block *btcutil.Block) ([]byte, error) { // Create and marshal the notification. ntfn := btcjson.NewRedeemingTxNtfn(txHex, blockDetails(block, index)) return btcjson.MarshalCmd(nil, ntfn) }
go
func newRedeemingTxNotification(txHex string, index int, block *btcutil.Block) ([]byte, error) { // Create and marshal the notification. ntfn := btcjson.NewRedeemingTxNtfn(txHex, blockDetails(block, index)) return btcjson.MarshalCmd(nil, ntfn) }
[ "func", "newRedeemingTxNotification", "(", "txHex", "string", ",", "index", "int", ",", "block", "*", "btcutil", ".", "Block", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// Create and marshal the notification.", "ntfn", ":=", "btcjson", ".", "NewRedeemingTxNtfn", "(", "txHex", ",", "blockDetails", "(", "block", ",", "index", ")", ")", "\n", "return", "btcjson", ".", "MarshalCmd", "(", "nil", ",", "ntfn", ")", "\n", "}" ]
// newRedeemingTxNotification returns a new marshalled redeemingtx notification // with the passed parameters.
[ "newRedeemingTxNotification", "returns", "a", "new", "marshalled", "redeemingtx", "notification", "with", "the", "passed", "parameters", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L980-L984
train
btcsuite/btcd
rpcwebsocket.go
notifyForTxOuts
func (m *wsNotificationManager) notifyForTxOuts(ops map[wire.OutPoint]map[chan struct{}]*wsClient, addrs map[string]map[chan struct{}]*wsClient, tx *btcutil.Tx, block *btcutil.Block) { // Nothing to do if nobody is listening for address notifications. if len(addrs) == 0 { return } txHex := "" wscNotified := make(map[chan struct{}]struct{}) for i, txOut := range tx.MsgTx().TxOut { _, txAddrs, _, err := txscript.ExtractPkScriptAddrs( txOut.PkScript, m.server.cfg.ChainParams) if err != nil { continue } for _, txAddr := range txAddrs { cmap, ok := addrs[txAddr.EncodeAddress()] if !ok { continue } if txHex == "" { txHex = txHexString(tx.MsgTx()) } ntfn := btcjson.NewRecvTxNtfn(txHex, blockDetails(block, tx.Index())) marshalledJSON, err := btcjson.MarshalCmd(nil, ntfn) if err != nil { rpcsLog.Errorf("Failed to marshal processedtx notification: %v", err) continue } op := []*wire.OutPoint{wire.NewOutPoint(tx.Hash(), uint32(i))} for wscQuit, wsc := range cmap { m.addSpentRequests(ops, wsc, op) if _, ok := wscNotified[wscQuit]; !ok { wscNotified[wscQuit] = struct{}{} wsc.QueueNotification(marshalledJSON) } } } } }
go
func (m *wsNotificationManager) notifyForTxOuts(ops map[wire.OutPoint]map[chan struct{}]*wsClient, addrs map[string]map[chan struct{}]*wsClient, tx *btcutil.Tx, block *btcutil.Block) { // Nothing to do if nobody is listening for address notifications. if len(addrs) == 0 { return } txHex := "" wscNotified := make(map[chan struct{}]struct{}) for i, txOut := range tx.MsgTx().TxOut { _, txAddrs, _, err := txscript.ExtractPkScriptAddrs( txOut.PkScript, m.server.cfg.ChainParams) if err != nil { continue } for _, txAddr := range txAddrs { cmap, ok := addrs[txAddr.EncodeAddress()] if !ok { continue } if txHex == "" { txHex = txHexString(tx.MsgTx()) } ntfn := btcjson.NewRecvTxNtfn(txHex, blockDetails(block, tx.Index())) marshalledJSON, err := btcjson.MarshalCmd(nil, ntfn) if err != nil { rpcsLog.Errorf("Failed to marshal processedtx notification: %v", err) continue } op := []*wire.OutPoint{wire.NewOutPoint(tx.Hash(), uint32(i))} for wscQuit, wsc := range cmap { m.addSpentRequests(ops, wsc, op) if _, ok := wscNotified[wscQuit]; !ok { wscNotified[wscQuit] = struct{}{} wsc.QueueNotification(marshalledJSON) } } } } }
[ "func", "(", "m", "*", "wsNotificationManager", ")", "notifyForTxOuts", "(", "ops", "map", "[", "wire", ".", "OutPoint", "]", "map", "[", "chan", "struct", "{", "}", "]", "*", "wsClient", ",", "addrs", "map", "[", "string", "]", "map", "[", "chan", "struct", "{", "}", "]", "*", "wsClient", ",", "tx", "*", "btcutil", ".", "Tx", ",", "block", "*", "btcutil", ".", "Block", ")", "{", "// Nothing to do if nobody is listening for address notifications.", "if", "len", "(", "addrs", ")", "==", "0", "{", "return", "\n", "}", "\n\n", "txHex", ":=", "\"", "\"", "\n", "wscNotified", ":=", "make", "(", "map", "[", "chan", "struct", "{", "}", "]", "struct", "{", "}", ")", "\n", "for", "i", ",", "txOut", ":=", "range", "tx", ".", "MsgTx", "(", ")", ".", "TxOut", "{", "_", ",", "txAddrs", ",", "_", ",", "err", ":=", "txscript", ".", "ExtractPkScriptAddrs", "(", "txOut", ".", "PkScript", ",", "m", ".", "server", ".", "cfg", ".", "ChainParams", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n\n", "for", "_", ",", "txAddr", ":=", "range", "txAddrs", "{", "cmap", ",", "ok", ":=", "addrs", "[", "txAddr", ".", "EncodeAddress", "(", ")", "]", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n\n", "if", "txHex", "==", "\"", "\"", "{", "txHex", "=", "txHexString", "(", "tx", ".", "MsgTx", "(", ")", ")", "\n", "}", "\n", "ntfn", ":=", "btcjson", ".", "NewRecvTxNtfn", "(", "txHex", ",", "blockDetails", "(", "block", ",", "tx", ".", "Index", "(", ")", ")", ")", "\n\n", "marshalledJSON", ",", "err", ":=", "btcjson", ".", "MarshalCmd", "(", "nil", ",", "ntfn", ")", "\n", "if", "err", "!=", "nil", "{", "rpcsLog", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "continue", "\n", "}", "\n\n", "op", ":=", "[", "]", "*", "wire", ".", "OutPoint", "{", "wire", ".", "NewOutPoint", "(", "tx", ".", "Hash", "(", ")", ",", "uint32", "(", "i", ")", ")", "}", "\n", "for", "wscQuit", ",", "wsc", ":=", "range", "cmap", "{", "m", ".", "addSpentRequests", "(", "ops", ",", "wsc", ",", "op", ")", "\n\n", "if", "_", ",", "ok", ":=", "wscNotified", "[", "wscQuit", "]", ";", "!", "ok", "{", "wscNotified", "[", "wscQuit", "]", "=", "struct", "{", "}", "{", "}", "\n", "wsc", ".", "QueueNotification", "(", "marshalledJSON", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// notifyForTxOuts examines each transaction output, notifying interested // websocket clients of the transaction if an output spends to a watched // address. A spent notification request is automatically registered for // the client for each matching output.
[ "notifyForTxOuts", "examines", "each", "transaction", "output", "notifying", "interested", "websocket", "clients", "of", "the", "transaction", "if", "an", "output", "spends", "to", "a", "watched", "address", ".", "A", "spent", "notification", "request", "is", "automatically", "registered", "for", "the", "client", "for", "each", "matching", "output", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L990-L1036
train
btcsuite/btcd
rpcwebsocket.go
notifyRelevantTxAccepted
func (m *wsNotificationManager) notifyRelevantTxAccepted(tx *btcutil.Tx, clients map[chan struct{}]*wsClient) { clientsToNotify := m.subscribedClients(tx, clients) if len(clientsToNotify) != 0 { n := btcjson.NewRelevantTxAcceptedNtfn(txHexString(tx.MsgTx())) marshalled, err := btcjson.MarshalCmd(nil, n) if err != nil { rpcsLog.Errorf("Failed to marshal notification: %v", err) return } for quitChan := range clientsToNotify { clients[quitChan].QueueNotification(marshalled) } } }
go
func (m *wsNotificationManager) notifyRelevantTxAccepted(tx *btcutil.Tx, clients map[chan struct{}]*wsClient) { clientsToNotify := m.subscribedClients(tx, clients) if len(clientsToNotify) != 0 { n := btcjson.NewRelevantTxAcceptedNtfn(txHexString(tx.MsgTx())) marshalled, err := btcjson.MarshalCmd(nil, n) if err != nil { rpcsLog.Errorf("Failed to marshal notification: %v", err) return } for quitChan := range clientsToNotify { clients[quitChan].QueueNotification(marshalled) } } }
[ "func", "(", "m", "*", "wsNotificationManager", ")", "notifyRelevantTxAccepted", "(", "tx", "*", "btcutil", ".", "Tx", ",", "clients", "map", "[", "chan", "struct", "{", "}", "]", "*", "wsClient", ")", "{", "clientsToNotify", ":=", "m", ".", "subscribedClients", "(", "tx", ",", "clients", ")", "\n\n", "if", "len", "(", "clientsToNotify", ")", "!=", "0", "{", "n", ":=", "btcjson", ".", "NewRelevantTxAcceptedNtfn", "(", "txHexString", "(", "tx", ".", "MsgTx", "(", ")", ")", ")", "\n", "marshalled", ",", "err", ":=", "btcjson", ".", "MarshalCmd", "(", "nil", ",", "n", ")", "\n", "if", "err", "!=", "nil", "{", "rpcsLog", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "for", "quitChan", ":=", "range", "clientsToNotify", "{", "clients", "[", "quitChan", "]", ".", "QueueNotification", "(", "marshalled", ")", "\n", "}", "\n", "}", "\n", "}" ]
// notifyRelevantTxAccepted examines the inputs and outputs of the passed // transaction, notifying websocket clients of outputs spending to a watched // address and inputs spending a watched outpoint. Any outputs paying to a // watched address result in the output being watched as well for future // notifications.
[ "notifyRelevantTxAccepted", "examines", "the", "inputs", "and", "outputs", "of", "the", "passed", "transaction", "notifying", "websocket", "clients", "of", "outputs", "spending", "to", "a", "watched", "address", "and", "inputs", "spending", "a", "watched", "outpoint", ".", "Any", "outputs", "paying", "to", "a", "watched", "address", "result", "in", "the", "output", "being", "watched", "as", "well", "for", "future", "notifications", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1043-L1059
train
btcsuite/btcd
rpcwebsocket.go
notifyForTx
func (m *wsNotificationManager) notifyForTx(ops map[wire.OutPoint]map[chan struct{}]*wsClient, addrs map[string]map[chan struct{}]*wsClient, tx *btcutil.Tx, block *btcutil.Block) { if len(ops) != 0 { m.notifyForTxIns(ops, tx, block) } if len(addrs) != 0 { m.notifyForTxOuts(ops, addrs, tx, block) } }
go
func (m *wsNotificationManager) notifyForTx(ops map[wire.OutPoint]map[chan struct{}]*wsClient, addrs map[string]map[chan struct{}]*wsClient, tx *btcutil.Tx, block *btcutil.Block) { if len(ops) != 0 { m.notifyForTxIns(ops, tx, block) } if len(addrs) != 0 { m.notifyForTxOuts(ops, addrs, tx, block) } }
[ "func", "(", "m", "*", "wsNotificationManager", ")", "notifyForTx", "(", "ops", "map", "[", "wire", ".", "OutPoint", "]", "map", "[", "chan", "struct", "{", "}", "]", "*", "wsClient", ",", "addrs", "map", "[", "string", "]", "map", "[", "chan", "struct", "{", "}", "]", "*", "wsClient", ",", "tx", "*", "btcutil", ".", "Tx", ",", "block", "*", "btcutil", ".", "Block", ")", "{", "if", "len", "(", "ops", ")", "!=", "0", "{", "m", ".", "notifyForTxIns", "(", "ops", ",", "tx", ",", "block", ")", "\n", "}", "\n", "if", "len", "(", "addrs", ")", "!=", "0", "{", "m", ".", "notifyForTxOuts", "(", "ops", ",", "addrs", ",", "tx", ",", "block", ")", "\n", "}", "\n", "}" ]
// notifyForTx examines the inputs and outputs of the passed transaction, // notifying websocket clients of outputs spending to a watched address // and inputs spending a watched outpoint.
[ "notifyForTx", "examines", "the", "inputs", "and", "outputs", "of", "the", "passed", "transaction", "notifying", "websocket", "clients", "of", "outputs", "spending", "to", "a", "watched", "address", "and", "inputs", "spending", "a", "watched", "outpoint", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1064-L1073
train
btcsuite/btcd
rpcwebsocket.go
notifyForTxIns
func (m *wsNotificationManager) notifyForTxIns(ops map[wire.OutPoint]map[chan struct{}]*wsClient, tx *btcutil.Tx, block *btcutil.Block) { // Nothing to do if nobody is watching outpoints. if len(ops) == 0 { return } txHex := "" wscNotified := make(map[chan struct{}]struct{}) for _, txIn := range tx.MsgTx().TxIn { prevOut := &txIn.PreviousOutPoint if cmap, ok := ops[*prevOut]; ok { if txHex == "" { txHex = txHexString(tx.MsgTx()) } marshalledJSON, err := newRedeemingTxNotification(txHex, tx.Index(), block) if err != nil { rpcsLog.Warnf("Failed to marshal redeemingtx notification: %v", err) continue } for wscQuit, wsc := range cmap { if block != nil { m.removeSpentRequest(ops, wsc, prevOut) } if _, ok := wscNotified[wscQuit]; !ok { wscNotified[wscQuit] = struct{}{} wsc.QueueNotification(marshalledJSON) } } } } }
go
func (m *wsNotificationManager) notifyForTxIns(ops map[wire.OutPoint]map[chan struct{}]*wsClient, tx *btcutil.Tx, block *btcutil.Block) { // Nothing to do if nobody is watching outpoints. if len(ops) == 0 { return } txHex := "" wscNotified := make(map[chan struct{}]struct{}) for _, txIn := range tx.MsgTx().TxIn { prevOut := &txIn.PreviousOutPoint if cmap, ok := ops[*prevOut]; ok { if txHex == "" { txHex = txHexString(tx.MsgTx()) } marshalledJSON, err := newRedeemingTxNotification(txHex, tx.Index(), block) if err != nil { rpcsLog.Warnf("Failed to marshal redeemingtx notification: %v", err) continue } for wscQuit, wsc := range cmap { if block != nil { m.removeSpentRequest(ops, wsc, prevOut) } if _, ok := wscNotified[wscQuit]; !ok { wscNotified[wscQuit] = struct{}{} wsc.QueueNotification(marshalledJSON) } } } } }
[ "func", "(", "m", "*", "wsNotificationManager", ")", "notifyForTxIns", "(", "ops", "map", "[", "wire", ".", "OutPoint", "]", "map", "[", "chan", "struct", "{", "}", "]", "*", "wsClient", ",", "tx", "*", "btcutil", ".", "Tx", ",", "block", "*", "btcutil", ".", "Block", ")", "{", "// Nothing to do if nobody is watching outpoints.", "if", "len", "(", "ops", ")", "==", "0", "{", "return", "\n", "}", "\n\n", "txHex", ":=", "\"", "\"", "\n", "wscNotified", ":=", "make", "(", "map", "[", "chan", "struct", "{", "}", "]", "struct", "{", "}", ")", "\n", "for", "_", ",", "txIn", ":=", "range", "tx", ".", "MsgTx", "(", ")", ".", "TxIn", "{", "prevOut", ":=", "&", "txIn", ".", "PreviousOutPoint", "\n", "if", "cmap", ",", "ok", ":=", "ops", "[", "*", "prevOut", "]", ";", "ok", "{", "if", "txHex", "==", "\"", "\"", "{", "txHex", "=", "txHexString", "(", "tx", ".", "MsgTx", "(", ")", ")", "\n", "}", "\n", "marshalledJSON", ",", "err", ":=", "newRedeemingTxNotification", "(", "txHex", ",", "tx", ".", "Index", "(", ")", ",", "block", ")", "\n", "if", "err", "!=", "nil", "{", "rpcsLog", ".", "Warnf", "(", "\"", "\"", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "for", "wscQuit", ",", "wsc", ":=", "range", "cmap", "{", "if", "block", "!=", "nil", "{", "m", ".", "removeSpentRequest", "(", "ops", ",", "wsc", ",", "prevOut", ")", "\n", "}", "\n\n", "if", "_", ",", "ok", ":=", "wscNotified", "[", "wscQuit", "]", ";", "!", "ok", "{", "wscNotified", "[", "wscQuit", "]", "=", "struct", "{", "}", "{", "}", "\n", "wsc", ".", "QueueNotification", "(", "marshalledJSON", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// notifyForTxIns examines the inputs of the passed transaction and sends // interested websocket clients a redeemingtx notification if any inputs // spend a watched output. If block is non-nil, any matching spent // requests are removed.
[ "notifyForTxIns", "examines", "the", "inputs", "of", "the", "passed", "transaction", "and", "sends", "interested", "websocket", "clients", "a", "redeemingtx", "notification", "if", "any", "inputs", "spend", "a", "watched", "output", ".", "If", "block", "is", "non", "-", "nil", "any", "matching", "spent", "requests", "are", "removed", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1079-L1112
train
btcsuite/btcd
rpcwebsocket.go
RegisterTxOutAddressRequests
func (m *wsNotificationManager) RegisterTxOutAddressRequests(wsc *wsClient, addrs []string) { m.queueNotification <- &notificationRegisterAddr{ wsc: wsc, addrs: addrs, } }
go
func (m *wsNotificationManager) RegisterTxOutAddressRequests(wsc *wsClient, addrs []string) { m.queueNotification <- &notificationRegisterAddr{ wsc: wsc, addrs: addrs, } }
[ "func", "(", "m", "*", "wsNotificationManager", ")", "RegisterTxOutAddressRequests", "(", "wsc", "*", "wsClient", ",", "addrs", "[", "]", "string", ")", "{", "m", ".", "queueNotification", "<-", "&", "notificationRegisterAddr", "{", "wsc", ":", "wsc", ",", "addrs", ":", "addrs", ",", "}", "\n", "}" ]
// RegisterTxOutAddressRequests requests notifications to the passed websocket // client when a transaction output spends to the passed address.
[ "RegisterTxOutAddressRequests", "requests", "notifications", "to", "the", "passed", "websocket", "client", "when", "a", "transaction", "output", "spends", "to", "the", "passed", "address", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1116-L1121
train
btcsuite/btcd
rpcwebsocket.go
addAddrRequests
func (*wsNotificationManager) addAddrRequests(addrMap map[string]map[chan struct{}]*wsClient, wsc *wsClient, addrs []string) { for _, addr := range addrs { // Track the request in the client as well so it can be quickly be // removed on disconnect. wsc.addrRequests[addr] = struct{}{} // Add the client to the set of clients to notify when the // outpoint is seen. Create map as needed. cmap, ok := addrMap[addr] if !ok { cmap = make(map[chan struct{}]*wsClient) addrMap[addr] = cmap } cmap[wsc.quit] = wsc } }
go
func (*wsNotificationManager) addAddrRequests(addrMap map[string]map[chan struct{}]*wsClient, wsc *wsClient, addrs []string) { for _, addr := range addrs { // Track the request in the client as well so it can be quickly be // removed on disconnect. wsc.addrRequests[addr] = struct{}{} // Add the client to the set of clients to notify when the // outpoint is seen. Create map as needed. cmap, ok := addrMap[addr] if !ok { cmap = make(map[chan struct{}]*wsClient) addrMap[addr] = cmap } cmap[wsc.quit] = wsc } }
[ "func", "(", "*", "wsNotificationManager", ")", "addAddrRequests", "(", "addrMap", "map", "[", "string", "]", "map", "[", "chan", "struct", "{", "}", "]", "*", "wsClient", ",", "wsc", "*", "wsClient", ",", "addrs", "[", "]", "string", ")", "{", "for", "_", ",", "addr", ":=", "range", "addrs", "{", "// Track the request in the client as well so it can be quickly be", "// removed on disconnect.", "wsc", ".", "addrRequests", "[", "addr", "]", "=", "struct", "{", "}", "{", "}", "\n\n", "// Add the client to the set of clients to notify when the", "// outpoint is seen. Create map as needed.", "cmap", ",", "ok", ":=", "addrMap", "[", "addr", "]", "\n", "if", "!", "ok", "{", "cmap", "=", "make", "(", "map", "[", "chan", "struct", "{", "}", "]", "*", "wsClient", ")", "\n", "addrMap", "[", "addr", "]", "=", "cmap", "\n", "}", "\n", "cmap", "[", "wsc", ".", "quit", "]", "=", "wsc", "\n", "}", "\n", "}" ]
// addAddrRequests adds the websocket client wsc to the address to client set // addrMap so wsc will be notified for any mempool or block transaction outputs // spending to any of the addresses in addrs.
[ "addAddrRequests", "adds", "the", "websocket", "client", "wsc", "to", "the", "address", "to", "client", "set", "addrMap", "so", "wsc", "will", "be", "notified", "for", "any", "mempool", "or", "block", "transaction", "outputs", "spending", "to", "any", "of", "the", "addresses", "in", "addrs", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1126-L1143
train
btcsuite/btcd
rpcwebsocket.go
UnregisterTxOutAddressRequest
func (m *wsNotificationManager) UnregisterTxOutAddressRequest(wsc *wsClient, addr string) { m.queueNotification <- &notificationUnregisterAddr{ wsc: wsc, addr: addr, } }
go
func (m *wsNotificationManager) UnregisterTxOutAddressRequest(wsc *wsClient, addr string) { m.queueNotification <- &notificationUnregisterAddr{ wsc: wsc, addr: addr, } }
[ "func", "(", "m", "*", "wsNotificationManager", ")", "UnregisterTxOutAddressRequest", "(", "wsc", "*", "wsClient", ",", "addr", "string", ")", "{", "m", ".", "queueNotification", "<-", "&", "notificationUnregisterAddr", "{", "wsc", ":", "wsc", ",", "addr", ":", "addr", ",", "}", "\n", "}" ]
// UnregisterTxOutAddressRequest removes a request from the passed websocket // client to be notified when a transaction spends to the passed address.
[ "UnregisterTxOutAddressRequest", "removes", "a", "request", "from", "the", "passed", "websocket", "client", "to", "be", "notified", "when", "a", "transaction", "spends", "to", "the", "passed", "address", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1147-L1152
train
btcsuite/btcd
rpcwebsocket.go
removeAddrRequest
func (*wsNotificationManager) removeAddrRequest(addrs map[string]map[chan struct{}]*wsClient, wsc *wsClient, addr string) { // Remove the request tracking from the client. delete(wsc.addrRequests, addr) // Remove the client from the list to notify. cmap, ok := addrs[addr] if !ok { rpcsLog.Warnf("Attempt to remove nonexistent addr request "+ "<%s> for websocket client %s", addr, wsc.addr) return } delete(cmap, wsc.quit) // Remove the map entry altogether if there are no more clients // interested in it. if len(cmap) == 0 { delete(addrs, addr) } }
go
func (*wsNotificationManager) removeAddrRequest(addrs map[string]map[chan struct{}]*wsClient, wsc *wsClient, addr string) { // Remove the request tracking from the client. delete(wsc.addrRequests, addr) // Remove the client from the list to notify. cmap, ok := addrs[addr] if !ok { rpcsLog.Warnf("Attempt to remove nonexistent addr request "+ "<%s> for websocket client %s", addr, wsc.addr) return } delete(cmap, wsc.quit) // Remove the map entry altogether if there are no more clients // interested in it. if len(cmap) == 0 { delete(addrs, addr) } }
[ "func", "(", "*", "wsNotificationManager", ")", "removeAddrRequest", "(", "addrs", "map", "[", "string", "]", "map", "[", "chan", "struct", "{", "}", "]", "*", "wsClient", ",", "wsc", "*", "wsClient", ",", "addr", "string", ")", "{", "// Remove the request tracking from the client.", "delete", "(", "wsc", ".", "addrRequests", ",", "addr", ")", "\n\n", "// Remove the client from the list to notify.", "cmap", ",", "ok", ":=", "addrs", "[", "addr", "]", "\n", "if", "!", "ok", "{", "rpcsLog", ".", "Warnf", "(", "\"", "\"", "+", "\"", "\"", ",", "addr", ",", "wsc", ".", "addr", ")", "\n", "return", "\n", "}", "\n", "delete", "(", "cmap", ",", "wsc", ".", "quit", ")", "\n\n", "// Remove the map entry altogether if there are no more clients", "// interested in it.", "if", "len", "(", "cmap", ")", "==", "0", "{", "delete", "(", "addrs", ",", "addr", ")", "\n", "}", "\n", "}" ]
// removeAddrRequest removes the websocket client wsc from the address to // client set addrs so it will no longer receive notification updates for // any transaction outputs send to addr.
[ "removeAddrRequest", "removes", "the", "websocket", "client", "wsc", "from", "the", "address", "to", "client", "set", "addrs", "so", "it", "will", "no", "longer", "receive", "notification", "updates", "for", "any", "transaction", "outputs", "send", "to", "addr", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1157-L1177
train
btcsuite/btcd
rpcwebsocket.go
RemoveClient
func (m *wsNotificationManager) RemoveClient(wsc *wsClient) { select { case m.queueNotification <- (*notificationUnregisterClient)(wsc): case <-m.quit: } }
go
func (m *wsNotificationManager) RemoveClient(wsc *wsClient) { select { case m.queueNotification <- (*notificationUnregisterClient)(wsc): case <-m.quit: } }
[ "func", "(", "m", "*", "wsNotificationManager", ")", "RemoveClient", "(", "wsc", "*", "wsClient", ")", "{", "select", "{", "case", "m", ".", "queueNotification", "<-", "(", "*", "notificationUnregisterClient", ")", "(", "wsc", ")", ":", "case", "<-", "m", ".", "quit", ":", "}", "\n", "}" ]
// RemoveClient removes the passed websocket client and all notifications // registered for it.
[ "RemoveClient", "removes", "the", "passed", "websocket", "client", "and", "all", "notifications", "registered", "for", "it", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1186-L1191
train
btcsuite/btcd
rpcwebsocket.go
Start
func (m *wsNotificationManager) Start() { m.wg.Add(2) go m.queueHandler() go m.notificationHandler() }
go
func (m *wsNotificationManager) Start() { m.wg.Add(2) go m.queueHandler() go m.notificationHandler() }
[ "func", "(", "m", "*", "wsNotificationManager", ")", "Start", "(", ")", "{", "m", ".", "wg", ".", "Add", "(", "2", ")", "\n", "go", "m", ".", "queueHandler", "(", ")", "\n", "go", "m", ".", "notificationHandler", "(", ")", "\n", "}" ]
// Start starts the goroutines required for the manager to queue and process // websocket client notifications.
[ "Start", "starts", "the", "goroutines", "required", "for", "the", "manager", "to", "queue", "and", "process", "websocket", "client", "notifications", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1195-L1199
train
btcsuite/btcd
rpcwebsocket.go
newWsNotificationManager
func newWsNotificationManager(server *rpcServer) *wsNotificationManager { return &wsNotificationManager{ server: server, queueNotification: make(chan interface{}), notificationMsgs: make(chan interface{}), numClients: make(chan int), quit: make(chan struct{}), } }
go
func newWsNotificationManager(server *rpcServer) *wsNotificationManager { return &wsNotificationManager{ server: server, queueNotification: make(chan interface{}), notificationMsgs: make(chan interface{}), numClients: make(chan int), quit: make(chan struct{}), } }
[ "func", "newWsNotificationManager", "(", "server", "*", "rpcServer", ")", "*", "wsNotificationManager", "{", "return", "&", "wsNotificationManager", "{", "server", ":", "server", ",", "queueNotification", ":", "make", "(", "chan", "interface", "{", "}", ")", ",", "notificationMsgs", ":", "make", "(", "chan", "interface", "{", "}", ")", ",", "numClients", ":", "make", "(", "chan", "int", ")", ",", "quit", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n", "}" ]
// newWsNotificationManager returns a new notification manager ready for use. // See wsNotificationManager for more details.
[ "newWsNotificationManager", "returns", "a", "new", "notification", "manager", "ready", "for", "use", ".", "See", "wsNotificationManager", "for", "more", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1215-L1223
train
btcsuite/btcd
rpcwebsocket.go
serviceRequest
func (c *wsClient) serviceRequest(r *parsedRPCCmd) { var ( result interface{} err error ) // Lookup the websocket extension for the command and if it doesn't // exist fallback to handling the command as a standard command. wsHandler, ok := wsHandlers[r.method] if ok { result, err = wsHandler(c, r.cmd) } else { result, err = c.server.standardCmdResult(r, nil) } reply, err := createMarshalledReply(r.id, result, err) if err != nil { rpcsLog.Errorf("Failed to marshal reply for <%s> "+ "command: %v", r.method, err) return } c.SendMessage(reply, nil) }
go
func (c *wsClient) serviceRequest(r *parsedRPCCmd) { var ( result interface{} err error ) // Lookup the websocket extension for the command and if it doesn't // exist fallback to handling the command as a standard command. wsHandler, ok := wsHandlers[r.method] if ok { result, err = wsHandler(c, r.cmd) } else { result, err = c.server.standardCmdResult(r, nil) } reply, err := createMarshalledReply(r.id, result, err) if err != nil { rpcsLog.Errorf("Failed to marshal reply for <%s> "+ "command: %v", r.method, err) return } c.SendMessage(reply, nil) }
[ "func", "(", "c", "*", "wsClient", ")", "serviceRequest", "(", "r", "*", "parsedRPCCmd", ")", "{", "var", "(", "result", "interface", "{", "}", "\n", "err", "error", "\n", ")", "\n\n", "// Lookup the websocket extension for the command and if it doesn't", "// exist fallback to handling the command as a standard command.", "wsHandler", ",", "ok", ":=", "wsHandlers", "[", "r", ".", "method", "]", "\n", "if", "ok", "{", "result", ",", "err", "=", "wsHandler", "(", "c", ",", "r", ".", "cmd", ")", "\n", "}", "else", "{", "result", ",", "err", "=", "c", ".", "server", ".", "standardCmdResult", "(", "r", ",", "nil", ")", "\n", "}", "\n", "reply", ",", "err", ":=", "createMarshalledReply", "(", "r", ".", "id", ",", "result", ",", "err", ")", "\n", "if", "err", "!=", "nil", "{", "rpcsLog", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "r", ".", "method", ",", "err", ")", "\n", "return", "\n", "}", "\n", "c", ".", "SendMessage", "(", "reply", ",", "nil", ")", "\n", "}" ]
// serviceRequest services a parsed RPC request by looking up and executing the // appropriate RPC handler. The response is marshalled and sent to the // websocket client.
[ "serviceRequest", "services", "a", "parsed", "RPC", "request", "by", "looking", "up", "and", "executing", "the", "appropriate", "RPC", "handler", ".", "The", "response", "is", "marshalled", "and", "sent", "to", "the", "websocket", "client", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1484-L1505
train
btcsuite/btcd
rpcwebsocket.go
outHandler
func (c *wsClient) outHandler() { out: for { // Send any messages ready for send until the quit channel is // closed. select { case r := <-c.sendChan: err := c.conn.WriteMessage(websocket.TextMessage, r.msg) if err != nil { c.Disconnect() break out } if r.doneChan != nil { r.doneChan <- true } case <-c.quit: break out } } // Drain any wait channels before exiting so nothing is left waiting // around to send. cleanup: for { select { case r := <-c.sendChan: if r.doneChan != nil { r.doneChan <- false } default: break cleanup } } c.wg.Done() rpcsLog.Tracef("Websocket client output handler done for %s", c.addr) }
go
func (c *wsClient) outHandler() { out: for { // Send any messages ready for send until the quit channel is // closed. select { case r := <-c.sendChan: err := c.conn.WriteMessage(websocket.TextMessage, r.msg) if err != nil { c.Disconnect() break out } if r.doneChan != nil { r.doneChan <- true } case <-c.quit: break out } } // Drain any wait channels before exiting so nothing is left waiting // around to send. cleanup: for { select { case r := <-c.sendChan: if r.doneChan != nil { r.doneChan <- false } default: break cleanup } } c.wg.Done() rpcsLog.Tracef("Websocket client output handler done for %s", c.addr) }
[ "func", "(", "c", "*", "wsClient", ")", "outHandler", "(", ")", "{", "out", ":", "for", "{", "// Send any messages ready for send until the quit channel is", "// closed.", "select", "{", "case", "r", ":=", "<-", "c", ".", "sendChan", ":", "err", ":=", "c", ".", "conn", ".", "WriteMessage", "(", "websocket", ".", "TextMessage", ",", "r", ".", "msg", ")", "\n", "if", "err", "!=", "nil", "{", "c", ".", "Disconnect", "(", ")", "\n", "break", "out", "\n", "}", "\n", "if", "r", ".", "doneChan", "!=", "nil", "{", "r", ".", "doneChan", "<-", "true", "\n", "}", "\n\n", "case", "<-", "c", ".", "quit", ":", "break", "out", "\n", "}", "\n", "}", "\n\n", "// Drain any wait channels before exiting so nothing is left waiting", "// around to send.", "cleanup", ":", "for", "{", "select", "{", "case", "r", ":=", "<-", "c", ".", "sendChan", ":", "if", "r", ".", "doneChan", "!=", "nil", "{", "r", ".", "doneChan", "<-", "false", "\n", "}", "\n", "default", ":", "break", "cleanup", "\n", "}", "\n", "}", "\n", "c", ".", "wg", ".", "Done", "(", ")", "\n", "rpcsLog", ".", "Tracef", "(", "\"", "\"", ",", "c", ".", "addr", ")", "\n", "}" ]
// outHandler handles all outgoing messages for the websocket connection. It // must be run as a goroutine. It uses a buffered channel to serialize output // messages while allowing the sender to continue running asynchronously. It // must be run as a goroutine.
[ "outHandler", "handles", "all", "outgoing", "messages", "for", "the", "websocket", "connection", ".", "It", "must", "be", "run", "as", "a", "goroutine", ".", "It", "uses", "a", "buffered", "channel", "to", "serialize", "output", "messages", "while", "allowing", "the", "sender", "to", "continue", "running", "asynchronously", ".", "It", "must", "be", "run", "as", "a", "goroutine", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1584-L1620
train
btcsuite/btcd
rpcwebsocket.go
SendMessage
func (c *wsClient) SendMessage(marshalledJSON []byte, doneChan chan bool) { // Don't send the message if disconnected. if c.Disconnected() { if doneChan != nil { doneChan <- false } return } c.sendChan <- wsResponse{msg: marshalledJSON, doneChan: doneChan} }
go
func (c *wsClient) SendMessage(marshalledJSON []byte, doneChan chan bool) { // Don't send the message if disconnected. if c.Disconnected() { if doneChan != nil { doneChan <- false } return } c.sendChan <- wsResponse{msg: marshalledJSON, doneChan: doneChan} }
[ "func", "(", "c", "*", "wsClient", ")", "SendMessage", "(", "marshalledJSON", "[", "]", "byte", ",", "doneChan", "chan", "bool", ")", "{", "// Don't send the message if disconnected.", "if", "c", ".", "Disconnected", "(", ")", "{", "if", "doneChan", "!=", "nil", "{", "doneChan", "<-", "false", "\n", "}", "\n", "return", "\n", "}", "\n\n", "c", ".", "sendChan", "<-", "wsResponse", "{", "msg", ":", "marshalledJSON", ",", "doneChan", ":", "doneChan", "}", "\n", "}" ]
// SendMessage sends the passed json to the websocket client. It is backed // by a buffered channel, so it will not block until the send channel is full. // Note however that QueueNotification must be used for sending async // notifications instead of the this function. This approach allows a limit to // the number of outstanding requests a client can make without preventing or // blocking on async notifications.
[ "SendMessage", "sends", "the", "passed", "json", "to", "the", "websocket", "client", ".", "It", "is", "backed", "by", "a", "buffered", "channel", "so", "it", "will", "not", "block", "until", "the", "send", "channel", "is", "full", ".", "Note", "however", "that", "QueueNotification", "must", "be", "used", "for", "sending", "async", "notifications", "instead", "of", "the", "this", "function", ".", "This", "approach", "allows", "a", "limit", "to", "the", "number", "of", "outstanding", "requests", "a", "client", "can", "make", "without", "preventing", "or", "blocking", "on", "async", "notifications", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1628-L1638
train
btcsuite/btcd
rpcwebsocket.go
QueueNotification
func (c *wsClient) QueueNotification(marshalledJSON []byte) error { // Don't queue the message if disconnected. if c.Disconnected() { return ErrClientQuit } c.ntfnChan <- marshalledJSON return nil }
go
func (c *wsClient) QueueNotification(marshalledJSON []byte) error { // Don't queue the message if disconnected. if c.Disconnected() { return ErrClientQuit } c.ntfnChan <- marshalledJSON return nil }
[ "func", "(", "c", "*", "wsClient", ")", "QueueNotification", "(", "marshalledJSON", "[", "]", "byte", ")", "error", "{", "// Don't queue the message if disconnected.", "if", "c", ".", "Disconnected", "(", ")", "{", "return", "ErrClientQuit", "\n", "}", "\n\n", "c", ".", "ntfnChan", "<-", "marshalledJSON", "\n", "return", "nil", "\n", "}" ]
// QueueNotification queues the passed notification to be sent to the websocket // client. This function, as the name implies, is only intended for // notifications since it has additional logic to prevent other subsystems, such // as the memory pool and block manager, from blocking even when the send // channel is full. // // If the client is in the process of shutting down, this function returns // ErrClientQuit. This is intended to be checked by long-running notification // handlers to stop processing if there is no more work needed to be done.
[ "QueueNotification", "queues", "the", "passed", "notification", "to", "be", "sent", "to", "the", "websocket", "client", ".", "This", "function", "as", "the", "name", "implies", "is", "only", "intended", "for", "notifications", "since", "it", "has", "additional", "logic", "to", "prevent", "other", "subsystems", "such", "as", "the", "memory", "pool", "and", "block", "manager", "from", "blocking", "even", "when", "the", "send", "channel", "is", "full", ".", "If", "the", "client", "is", "in", "the", "process", "of", "shutting", "down", "this", "function", "returns", "ErrClientQuit", ".", "This", "is", "intended", "to", "be", "checked", "by", "long", "-", "running", "notification", "handlers", "to", "stop", "processing", "if", "there", "is", "no", "more", "work", "needed", "to", "be", "done", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1653-L1661
train
btcsuite/btcd
rpcwebsocket.go
Disconnected
func (c *wsClient) Disconnected() bool { c.Lock() isDisconnected := c.disconnected c.Unlock() return isDisconnected }
go
func (c *wsClient) Disconnected() bool { c.Lock() isDisconnected := c.disconnected c.Unlock() return isDisconnected }
[ "func", "(", "c", "*", "wsClient", ")", "Disconnected", "(", ")", "bool", "{", "c", ".", "Lock", "(", ")", "\n", "isDisconnected", ":=", "c", ".", "disconnected", "\n", "c", ".", "Unlock", "(", ")", "\n\n", "return", "isDisconnected", "\n", "}" ]
// Disconnected returns whether or not the websocket client is disconnected.
[ "Disconnected", "returns", "whether", "or", "not", "the", "websocket", "client", "is", "disconnected", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1664-L1670
train
btcsuite/btcd
rpcwebsocket.go
Disconnect
func (c *wsClient) Disconnect() { c.Lock() defer c.Unlock() // Nothing to do if already disconnected. if c.disconnected { return } rpcsLog.Tracef("Disconnecting websocket client %s", c.addr) close(c.quit) c.conn.Close() c.disconnected = true }
go
func (c *wsClient) Disconnect() { c.Lock() defer c.Unlock() // Nothing to do if already disconnected. if c.disconnected { return } rpcsLog.Tracef("Disconnecting websocket client %s", c.addr) close(c.quit) c.conn.Close() c.disconnected = true }
[ "func", "(", "c", "*", "wsClient", ")", "Disconnect", "(", ")", "{", "c", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "Unlock", "(", ")", "\n\n", "// Nothing to do if already disconnected.", "if", "c", ".", "disconnected", "{", "return", "\n", "}", "\n\n", "rpcsLog", ".", "Tracef", "(", "\"", "\"", ",", "c", ".", "addr", ")", "\n", "close", "(", "c", ".", "quit", ")", "\n", "c", ".", "conn", ".", "Close", "(", ")", "\n", "c", ".", "disconnected", "=", "true", "\n", "}" ]
// Disconnect disconnects the websocket client.
[ "Disconnect", "disconnects", "the", "websocket", "client", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1673-L1686
train
btcsuite/btcd
rpcwebsocket.go
Start
func (c *wsClient) Start() { rpcsLog.Tracef("Starting websocket client %s", c.addr) // Start processing input and output. c.wg.Add(3) go c.inHandler() go c.notificationQueueHandler() go c.outHandler() }
go
func (c *wsClient) Start() { rpcsLog.Tracef("Starting websocket client %s", c.addr) // Start processing input and output. c.wg.Add(3) go c.inHandler() go c.notificationQueueHandler() go c.outHandler() }
[ "func", "(", "c", "*", "wsClient", ")", "Start", "(", ")", "{", "rpcsLog", ".", "Tracef", "(", "\"", "\"", ",", "c", ".", "addr", ")", "\n\n", "// Start processing input and output.", "c", ".", "wg", ".", "Add", "(", "3", ")", "\n", "go", "c", ".", "inHandler", "(", ")", "\n", "go", "c", ".", "notificationQueueHandler", "(", ")", "\n", "go", "c", ".", "outHandler", "(", ")", "\n", "}" ]
// Start begins processing input and output messages.
[ "Start", "begins", "processing", "input", "and", "output", "messages", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1689-L1697
train
btcsuite/btcd
rpcwebsocket.go
handleWebsocketHelp
func handleWebsocketHelp(wsc *wsClient, icmd interface{}) (interface{}, error) { cmd, ok := icmd.(*btcjson.HelpCmd) if !ok { return nil, btcjson.ErrRPCInternal } // Provide a usage overview of all commands when no specific command // was specified. var command string if cmd.Command != nil { command = *cmd.Command } if command == "" { usage, err := wsc.server.helpCacher.rpcUsage(true) if err != nil { context := "Failed to generate RPC usage" return nil, internalRPCError(err.Error(), context) } return usage, nil } // Check that the command asked for is supported and implemented. // Search the list of websocket handlers as well as the main list of // handlers since help should only be provided for those cases. valid := true if _, ok := rpcHandlers[command]; !ok { if _, ok := wsHandlers[command]; !ok { valid = false } } if !valid { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInvalidParameter, Message: "Unknown command: " + command, } } // Get the help for the command. help, err := wsc.server.helpCacher.rpcMethodHelp(command) if err != nil { context := "Failed to generate help" return nil, internalRPCError(err.Error(), context) } return help, nil }
go
func handleWebsocketHelp(wsc *wsClient, icmd interface{}) (interface{}, error) { cmd, ok := icmd.(*btcjson.HelpCmd) if !ok { return nil, btcjson.ErrRPCInternal } // Provide a usage overview of all commands when no specific command // was specified. var command string if cmd.Command != nil { command = *cmd.Command } if command == "" { usage, err := wsc.server.helpCacher.rpcUsage(true) if err != nil { context := "Failed to generate RPC usage" return nil, internalRPCError(err.Error(), context) } return usage, nil } // Check that the command asked for is supported and implemented. // Search the list of websocket handlers as well as the main list of // handlers since help should only be provided for those cases. valid := true if _, ok := rpcHandlers[command]; !ok { if _, ok := wsHandlers[command]; !ok { valid = false } } if !valid { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInvalidParameter, Message: "Unknown command: " + command, } } // Get the help for the command. help, err := wsc.server.helpCacher.rpcMethodHelp(command) if err != nil { context := "Failed to generate help" return nil, internalRPCError(err.Error(), context) } return help, nil }
[ "func", "handleWebsocketHelp", "(", "wsc", "*", "wsClient", ",", "icmd", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ",", "ok", ":=", "icmd", ".", "(", "*", "btcjson", ".", "HelpCmd", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "btcjson", ".", "ErrRPCInternal", "\n", "}", "\n\n", "// Provide a usage overview of all commands when no specific command", "// was specified.", "var", "command", "string", "\n", "if", "cmd", ".", "Command", "!=", "nil", "{", "command", "=", "*", "cmd", ".", "Command", "\n", "}", "\n", "if", "command", "==", "\"", "\"", "{", "usage", ",", "err", ":=", "wsc", ".", "server", ".", "helpCacher", ".", "rpcUsage", "(", "true", ")", "\n", "if", "err", "!=", "nil", "{", "context", ":=", "\"", "\"", "\n", "return", "nil", ",", "internalRPCError", "(", "err", ".", "Error", "(", ")", ",", "context", ")", "\n", "}", "\n", "return", "usage", ",", "nil", "\n", "}", "\n\n", "// Check that the command asked for is supported and implemented.", "// Search the list of websocket handlers as well as the main list of", "// handlers since help should only be provided for those cases.", "valid", ":=", "true", "\n", "if", "_", ",", "ok", ":=", "rpcHandlers", "[", "command", "]", ";", "!", "ok", "{", "if", "_", ",", "ok", ":=", "wsHandlers", "[", "command", "]", ";", "!", "ok", "{", "valid", "=", "false", "\n", "}", "\n", "}", "\n", "if", "!", "valid", "{", "return", "nil", ",", "&", "btcjson", ".", "RPCError", "{", "Code", ":", "btcjson", ".", "ErrRPCInvalidParameter", ",", "Message", ":", "\"", "\"", "+", "command", ",", "}", "\n", "}", "\n\n", "// Get the help for the command.", "help", ",", "err", ":=", "wsc", ".", "server", ".", "helpCacher", ".", "rpcMethodHelp", "(", "command", ")", "\n", "if", "err", "!=", "nil", "{", "context", ":=", "\"", "\"", "\n", "return", "nil", ",", "internalRPCError", "(", "err", ".", "Error", "(", ")", ",", "context", ")", "\n", "}", "\n", "return", "help", ",", "nil", "\n", "}" ]
// handleWebsocketHelp implements the help command for websocket connections.
[ "handleWebsocketHelp", "implements", "the", "help", "command", "for", "websocket", "connections", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1737-L1781
train
btcsuite/btcd
rpcwebsocket.go
handleNotifyBlocks
func handleNotifyBlocks(wsc *wsClient, icmd interface{}) (interface{}, error) { wsc.server.ntfnMgr.RegisterBlockUpdates(wsc) return nil, nil }
go
func handleNotifyBlocks(wsc *wsClient, icmd interface{}) (interface{}, error) { wsc.server.ntfnMgr.RegisterBlockUpdates(wsc) return nil, nil }
[ "func", "handleNotifyBlocks", "(", "wsc", "*", "wsClient", ",", "icmd", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "wsc", ".", "server", ".", "ntfnMgr", ".", "RegisterBlockUpdates", "(", "wsc", ")", "\n", "return", "nil", ",", "nil", "\n", "}" ]
// handleNotifyBlocks implements the notifyblocks command extension for // websocket connections.
[ "handleNotifyBlocks", "implements", "the", "notifyblocks", "command", "extension", "for", "websocket", "connections", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1830-L1833
train
btcsuite/btcd
rpcwebsocket.go
handleSession
func handleSession(wsc *wsClient, icmd interface{}) (interface{}, error) { return &btcjson.SessionResult{SessionID: wsc.sessionID}, nil }
go
func handleSession(wsc *wsClient, icmd interface{}) (interface{}, error) { return &btcjson.SessionResult{SessionID: wsc.sessionID}, nil }
[ "func", "handleSession", "(", "wsc", "*", "wsClient", ",", "icmd", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "&", "btcjson", ".", "SessionResult", "{", "SessionID", ":", "wsc", ".", "sessionID", "}", ",", "nil", "\n", "}" ]
// handleSession implements the session command extension for websocket // connections.
[ "handleSession", "implements", "the", "session", "command", "extension", "for", "websocket", "connections", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1837-L1839
train
btcsuite/btcd
rpcwebsocket.go
handleStopNotifyBlocks
func handleStopNotifyBlocks(wsc *wsClient, icmd interface{}) (interface{}, error) { wsc.server.ntfnMgr.UnregisterBlockUpdates(wsc) return nil, nil }
go
func handleStopNotifyBlocks(wsc *wsClient, icmd interface{}) (interface{}, error) { wsc.server.ntfnMgr.UnregisterBlockUpdates(wsc) return nil, nil }
[ "func", "handleStopNotifyBlocks", "(", "wsc", "*", "wsClient", ",", "icmd", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "wsc", ".", "server", ".", "ntfnMgr", ".", "UnregisterBlockUpdates", "(", "wsc", ")", "\n", "return", "nil", ",", "nil", "\n", "}" ]
// handleStopNotifyBlocks implements the stopnotifyblocks command extension for // websocket connections.
[ "handleStopNotifyBlocks", "implements", "the", "stopnotifyblocks", "command", "extension", "for", "websocket", "connections", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1843-L1846
train
btcsuite/btcd
rpcwebsocket.go
handleNotifySpent
func handleNotifySpent(wsc *wsClient, icmd interface{}) (interface{}, error) { cmd, ok := icmd.(*btcjson.NotifySpentCmd) if !ok { return nil, btcjson.ErrRPCInternal } outpoints, err := deserializeOutpoints(cmd.OutPoints) if err != nil { return nil, err } wsc.server.ntfnMgr.RegisterSpentRequests(wsc, outpoints) return nil, nil }
go
func handleNotifySpent(wsc *wsClient, icmd interface{}) (interface{}, error) { cmd, ok := icmd.(*btcjson.NotifySpentCmd) if !ok { return nil, btcjson.ErrRPCInternal } outpoints, err := deserializeOutpoints(cmd.OutPoints) if err != nil { return nil, err } wsc.server.ntfnMgr.RegisterSpentRequests(wsc, outpoints) return nil, nil }
[ "func", "handleNotifySpent", "(", "wsc", "*", "wsClient", ",", "icmd", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ",", "ok", ":=", "icmd", ".", "(", "*", "btcjson", ".", "NotifySpentCmd", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "btcjson", ".", "ErrRPCInternal", "\n", "}", "\n\n", "outpoints", ",", "err", ":=", "deserializeOutpoints", "(", "cmd", ".", "OutPoints", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "wsc", ".", "server", ".", "ntfnMgr", ".", "RegisterSpentRequests", "(", "wsc", ",", "outpoints", ")", "\n", "return", "nil", ",", "nil", "\n", "}" ]
// handleNotifySpent implements the notifyspent command extension for // websocket connections.
[ "handleNotifySpent", "implements", "the", "notifyspent", "command", "extension", "for", "websocket", "connections", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1850-L1863
train
btcsuite/btcd
rpcwebsocket.go
handleNotifyNewTransactions
func handleNotifyNewTransactions(wsc *wsClient, icmd interface{}) (interface{}, error) { cmd, ok := icmd.(*btcjson.NotifyNewTransactionsCmd) if !ok { return nil, btcjson.ErrRPCInternal } wsc.verboseTxUpdates = cmd.Verbose != nil && *cmd.Verbose wsc.server.ntfnMgr.RegisterNewMempoolTxsUpdates(wsc) return nil, nil }
go
func handleNotifyNewTransactions(wsc *wsClient, icmd interface{}) (interface{}, error) { cmd, ok := icmd.(*btcjson.NotifyNewTransactionsCmd) if !ok { return nil, btcjson.ErrRPCInternal } wsc.verboseTxUpdates = cmd.Verbose != nil && *cmd.Verbose wsc.server.ntfnMgr.RegisterNewMempoolTxsUpdates(wsc) return nil, nil }
[ "func", "handleNotifyNewTransactions", "(", "wsc", "*", "wsClient", ",", "icmd", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cmd", ",", "ok", ":=", "icmd", ".", "(", "*", "btcjson", ".", "NotifyNewTransactionsCmd", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "btcjson", ".", "ErrRPCInternal", "\n", "}", "\n\n", "wsc", ".", "verboseTxUpdates", "=", "cmd", ".", "Verbose", "!=", "nil", "&&", "*", "cmd", ".", "Verbose", "\n", "wsc", ".", "server", ".", "ntfnMgr", ".", "RegisterNewMempoolTxsUpdates", "(", "wsc", ")", "\n", "return", "nil", ",", "nil", "\n", "}" ]
// handleNotifyNewTransations implements the notifynewtransactions command // extension for websocket connections.
[ "handleNotifyNewTransations", "implements", "the", "notifynewtransactions", "command", "extension", "for", "websocket", "connections", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1867-L1876
train
btcsuite/btcd
rpcwebsocket.go
handleStopNotifyNewTransactions
func handleStopNotifyNewTransactions(wsc *wsClient, icmd interface{}) (interface{}, error) { wsc.server.ntfnMgr.UnregisterNewMempoolTxsUpdates(wsc) return nil, nil }
go
func handleStopNotifyNewTransactions(wsc *wsClient, icmd interface{}) (interface{}, error) { wsc.server.ntfnMgr.UnregisterNewMempoolTxsUpdates(wsc) return nil, nil }
[ "func", "handleStopNotifyNewTransactions", "(", "wsc", "*", "wsClient", ",", "icmd", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "wsc", ".", "server", ".", "ntfnMgr", ".", "UnregisterNewMempoolTxsUpdates", "(", "wsc", ")", "\n", "return", "nil", ",", "nil", "\n", "}" ]
// handleStopNotifyNewTransations implements the stopnotifynewtransactions // command extension for websocket connections.
[ "handleStopNotifyNewTransations", "implements", "the", "stopnotifynewtransactions", "command", "extension", "for", "websocket", "connections", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcwebsocket.go#L1880-L1883
train