id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
162,400
appleboy/gorush
gorush/log.go
SetLogOut
func SetLogOut(log *logrus.Logger, outString string) error { switch outString { case "stdout": log.Out = os.Stdout case "stderr": log.Out = os.Stderr default: f, err := os.OpenFile(outString, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644) if err != nil { return err } log.Out = f } return nil }
go
func SetLogOut(log *logrus.Logger, outString string) error { switch outString { case "stdout": log.Out = os.Stdout case "stderr": log.Out = os.Stderr default: f, err := os.OpenFile(outString, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644) if err != nil { return err } log.Out = f } return nil }
[ "func", "SetLogOut", "(", "log", "*", "logrus", ".", "Logger", ",", "outString", "string", ")", "error", "{", "switch", "outString", "{", "case", "\"", "\"", ":", "log", ".", "Out", "=", "os", ".", "Stdout", "\n", "case", "\"", "\"", ":", "log", "....
// SetLogOut provide log stdout and stderr output
[ "SetLogOut", "provide", "log", "stdout", "and", "stderr", "output" ]
55ff87f96fb660b9b632289448a880f7249e4c90
https://github.com/appleboy/gorush/blob/55ff87f96fb660b9b632289448a880f7249e4c90/gorush/log.go#L90-L107
162,401
appleboy/gorush
gorush/log.go
LogRequest
func LogRequest(uri string, method string, ip string, contentType string, agent string) { var output string log := &LogReq{ URI: uri, Method: method, IP: ip, ContentType: contentType, Agent: agent, } if PushConf.Log.Format == "json" { logJSON, _ := json.Marshal(log) output = string(logJSON) } else { var headerColor, resetColor string if isTerm { headerColor = magenta resetColor = reset } // format is string output = fmt.Sprintf("|%s header %s| %s %s %s %s %s", headerColor, resetColor, log.Method, log.URI, log.IP, log.ContentType, log.Agent, ) } LogAccess.Info(output) }
go
func LogRequest(uri string, method string, ip string, contentType string, agent string) { var output string log := &LogReq{ URI: uri, Method: method, IP: ip, ContentType: contentType, Agent: agent, } if PushConf.Log.Format == "json" { logJSON, _ := json.Marshal(log) output = string(logJSON) } else { var headerColor, resetColor string if isTerm { headerColor = magenta resetColor = reset } // format is string output = fmt.Sprintf("|%s header %s| %s %s %s %s %s", headerColor, resetColor, log.Method, log.URI, log.IP, log.ContentType, log.Agent, ) } LogAccess.Info(output) }
[ "func", "LogRequest", "(", "uri", "string", ",", "method", "string", ",", "ip", "string", ",", "contentType", "string", ",", "agent", "string", ")", "{", "var", "output", "string", "\n", "log", ":=", "&", "LogReq", "{", "URI", ":", "uri", ",", "Method"...
// LogRequest record http request
[ "LogRequest", "record", "http", "request" ]
55ff87f96fb660b9b632289448a880f7249e4c90
https://github.com/appleboy/gorush/blob/55ff87f96fb660b9b632289448a880f7249e4c90/gorush/log.go#L124-L158
162,402
appleboy/gorush
gorush/log.go
LogPush
func LogPush(status, token string, req PushNotification, errPush error) { var platColor, resetColor, output string if isTerm { platColor = colorForPlatForm(req.Platform) resetColor = reset } log := getLogPushEntry(status, token, req, errPush) if PushConf.Log.Format == "json" { logJSON, _ := json.Marshal(log) output = string(logJSON) } else { var typeColor string switch status { case SucceededPush: if isTerm { typeColor = green } output = fmt.Sprintf("|%s %s %s| %s%s%s [%s] %s", typeColor, log.Type, resetColor, platColor, log.Platform, resetColor, log.Token, log.Message, ) case FailedPush: if isTerm { typeColor = red } output = fmt.Sprintf("|%s %s %s| %s%s%s [%s] | %s | Error Message: %s", typeColor, log.Type, resetColor, platColor, log.Platform, resetColor, log.Token, log.Message, log.Error, ) } } switch status { case SucceededPush: LogAccess.Info(output) case FailedPush: LogError.Error(output) } }
go
func LogPush(status, token string, req PushNotification, errPush error) { var platColor, resetColor, output string if isTerm { platColor = colorForPlatForm(req.Platform) resetColor = reset } log := getLogPushEntry(status, token, req, errPush) if PushConf.Log.Format == "json" { logJSON, _ := json.Marshal(log) output = string(logJSON) } else { var typeColor string switch status { case SucceededPush: if isTerm { typeColor = green } output = fmt.Sprintf("|%s %s %s| %s%s%s [%s] %s", typeColor, log.Type, resetColor, platColor, log.Platform, resetColor, log.Token, log.Message, ) case FailedPush: if isTerm { typeColor = red } output = fmt.Sprintf("|%s %s %s| %s%s%s [%s] | %s | Error Message: %s", typeColor, log.Type, resetColor, platColor, log.Platform, resetColor, log.Token, log.Message, log.Error, ) } } switch status { case SucceededPush: LogAccess.Info(output) case FailedPush: LogError.Error(output) } }
[ "func", "LogPush", "(", "status", ",", "token", "string", ",", "req", "PushNotification", ",", "errPush", "error", ")", "{", "var", "platColor", ",", "resetColor", ",", "output", "string", "\n\n", "if", "isTerm", "{", "platColor", "=", "colorForPlatForm", "(...
// LogPush record user push request and server response.
[ "LogPush", "record", "user", "push", "request", "and", "server", "response", "." ]
55ff87f96fb660b9b632289448a880f7249e4c90
https://github.com/appleboy/gorush/blob/55ff87f96fb660b9b632289448a880f7249e4c90/gorush/log.go#L223-L272
162,403
appleboy/gorush
gorush/log.go
LogMiddleware
func LogMiddleware() gin.HandlerFunc { return func(c *gin.Context) { LogRequest(c.Request.URL.Path, c.Request.Method, c.ClientIP(), c.ContentType(), c.GetHeader("User-Agent")) c.Next() } }
go
func LogMiddleware() gin.HandlerFunc { return func(c *gin.Context) { LogRequest(c.Request.URL.Path, c.Request.Method, c.ClientIP(), c.ContentType(), c.GetHeader("User-Agent")) c.Next() } }
[ "func", "LogMiddleware", "(", ")", "gin", ".", "HandlerFunc", "{", "return", "func", "(", "c", "*", "gin", ".", "Context", ")", "{", "LogRequest", "(", "c", ".", "Request", ".", "URL", ".", "Path", ",", "c", ".", "Request", ".", "Method", ",", "c",...
// LogMiddleware provide gin router handler.
[ "LogMiddleware", "provide", "gin", "router", "handler", "." ]
55ff87f96fb660b9b632289448a880f7249e4c90
https://github.com/appleboy/gorush/blob/55ff87f96fb660b9b632289448a880f7249e4c90/gorush/log.go#L275-L280
162,404
appleboy/gorush
gorush/worker.go
InitWorkers
func InitWorkers(workerNum int64, queueNum int64) { LogAccess.Debug("worker number is ", workerNum, ", queue number is ", queueNum) QueueNotification = make(chan PushNotification, queueNum) for i := int64(0); i < workerNum; i++ { go startWorker() } }
go
func InitWorkers(workerNum int64, queueNum int64) { LogAccess.Debug("worker number is ", workerNum, ", queue number is ", queueNum) QueueNotification = make(chan PushNotification, queueNum) for i := int64(0); i < workerNum; i++ { go startWorker() } }
[ "func", "InitWorkers", "(", "workerNum", "int64", ",", "queueNum", "int64", ")", "{", "LogAccess", ".", "Debug", "(", "\"", "\"", ",", "workerNum", ",", "\"", "\"", ",", "queueNum", ")", "\n", "QueueNotification", "=", "make", "(", "chan", "PushNotificatio...
// InitWorkers for initialize all workers.
[ "InitWorkers", "for", "initialize", "all", "workers", "." ]
55ff87f96fb660b9b632289448a880f7249e4c90
https://github.com/appleboy/gorush/blob/55ff87f96fb660b9b632289448a880f7249e4c90/gorush/worker.go#L8-L14
162,405
appleboy/gorush
gorush/worker.go
SendNotification
func SendNotification(msg PushNotification) { switch msg.Platform { case PlatFormIos: PushToIOS(msg) case PlatFormAndroid: PushToAndroid(msg) } }
go
func SendNotification(msg PushNotification) { switch msg.Platform { case PlatFormIos: PushToIOS(msg) case PlatFormAndroid: PushToAndroid(msg) } }
[ "func", "SendNotification", "(", "msg", "PushNotification", ")", "{", "switch", "msg", ".", "Platform", "{", "case", "PlatFormIos", ":", "PushToIOS", "(", "msg", ")", "\n", "case", "PlatFormAndroid", ":", "PushToAndroid", "(", "msg", ")", "\n", "}", "\n", ...
// SendNotification is send message to iOS or Android
[ "SendNotification", "is", "send", "message", "to", "iOS", "or", "Android" ]
55ff87f96fb660b9b632289448a880f7249e4c90
https://github.com/appleboy/gorush/blob/55ff87f96fb660b9b632289448a880f7249e4c90/gorush/worker.go#L17-L24
162,406
appleboy/gorush
gorush/worker.go
queueNotification
func queueNotification(req RequestPush) (int, []LogPushEntry) { var count int wg := sync.WaitGroup{} newNotification := []*PushNotification{} for i := range req.Notifications { notification := &req.Notifications[i] switch notification.Platform { case PlatFormIos: if !PushConf.Ios.Enabled { continue } case PlatFormAndroid: if !PushConf.Android.Enabled { continue } } newNotification = append(newNotification, notification) } log := make([]LogPushEntry, 0, count) for _, notification := range newNotification { if PushConf.Core.Sync { notification.wg = &wg notification.log = &log notification.AddWaitCount() } if !tryEnqueue(*notification, QueueNotification) { LogError.Error("max capacity reached") } count += len(notification.Tokens) // Count topic message if notification.To != "" { count++ } } if PushConf.Core.Sync { wg.Wait() } StatStorage.AddTotalCount(int64(count)) return count, log }
go
func queueNotification(req RequestPush) (int, []LogPushEntry) { var count int wg := sync.WaitGroup{} newNotification := []*PushNotification{} for i := range req.Notifications { notification := &req.Notifications[i] switch notification.Platform { case PlatFormIos: if !PushConf.Ios.Enabled { continue } case PlatFormAndroid: if !PushConf.Android.Enabled { continue } } newNotification = append(newNotification, notification) } log := make([]LogPushEntry, 0, count) for _, notification := range newNotification { if PushConf.Core.Sync { notification.wg = &wg notification.log = &log notification.AddWaitCount() } if !tryEnqueue(*notification, QueueNotification) { LogError.Error("max capacity reached") } count += len(notification.Tokens) // Count topic message if notification.To != "" { count++ } } if PushConf.Core.Sync { wg.Wait() } StatStorage.AddTotalCount(int64(count)) return count, log }
[ "func", "queueNotification", "(", "req", "RequestPush", ")", "(", "int", ",", "[", "]", "LogPushEntry", ")", "{", "var", "count", "int", "\n", "wg", ":=", "sync", ".", "WaitGroup", "{", "}", "\n", "newNotification", ":=", "[", "]", "*", "PushNotification...
// queueNotification add notification to queue list.
[ "queueNotification", "add", "notification", "to", "queue", "list", "." ]
55ff87f96fb660b9b632289448a880f7249e4c90
https://github.com/appleboy/gorush/blob/55ff87f96fb660b9b632289448a880f7249e4c90/gorush/worker.go#L34-L77
162,407
appleboy/gorush
gorush/worker.go
tryEnqueue
func tryEnqueue(job PushNotification, jobChan chan<- PushNotification) bool { select { case jobChan <- job: return true default: return false } }
go
func tryEnqueue(job PushNotification, jobChan chan<- PushNotification) bool { select { case jobChan <- job: return true default: return false } }
[ "func", "tryEnqueue", "(", "job", "PushNotification", ",", "jobChan", "chan", "<-", "PushNotification", ")", "bool", "{", "select", "{", "case", "jobChan", "<-", "job", ":", "return", "true", "\n", "default", ":", "return", "false", "\n", "}", "\n", "}" ]
// tryEnqueue tries to enqueue a job to the given job channel. Returns true if // the operation was successful, and false if enqueuing would not have been // possible without blocking. Job is not enqueued in the latter case.
[ "tryEnqueue", "tries", "to", "enqueue", "a", "job", "to", "the", "given", "job", "channel", ".", "Returns", "true", "if", "the", "operation", "was", "successful", "and", "false", "if", "enqueuing", "would", "not", "have", "been", "possible", "without", "bloc...
55ff87f96fb660b9b632289448a880f7249e4c90
https://github.com/appleboy/gorush/blob/55ff87f96fb660b9b632289448a880f7249e4c90/gorush/worker.go#L82-L89
162,408
btcsuite/btcd
wire/msgcfheaders.go
AddCFHash
func (msg *MsgCFHeaders) AddCFHash(hash *chainhash.Hash) error { if len(msg.FilterHashes)+1 > MaxCFHeadersPerMsg { str := fmt.Sprintf("too many block headers in message [max %v]", MaxBlockHeadersPerMsg) return messageError("MsgCFHeaders.AddCFHash", str) } msg.FilterHashes = append(msg.FilterHashes, hash) return nil }
go
func (msg *MsgCFHeaders) AddCFHash(hash *chainhash.Hash) error { if len(msg.FilterHashes)+1 > MaxCFHeadersPerMsg { str := fmt.Sprintf("too many block headers in message [max %v]", MaxBlockHeadersPerMsg) return messageError("MsgCFHeaders.AddCFHash", str) } msg.FilterHashes = append(msg.FilterHashes, hash) return nil }
[ "func", "(", "msg", "*", "MsgCFHeaders", ")", "AddCFHash", "(", "hash", "*", "chainhash", ".", "Hash", ")", "error", "{", "if", "len", "(", "msg", ".", "FilterHashes", ")", "+", "1", ">", "MaxCFHeadersPerMsg", "{", "str", ":=", "fmt", ".", "Sprintf", ...
// AddCFHash adds a new filter hash to the message.
[ "AddCFHash", "adds", "a", "new", "filter", "hash", "to", "the", "message", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgcfheaders.go#L37-L46
162,409
btcsuite/btcd
wire/msgcfheaders.go
Deserialize
func (msg *MsgCFHeaders) Deserialize(r io.Reader) error { // At the current time, there is no difference between the wire encoding // and the stable long-term storage format. As a result, make use of // BtcDecode. return msg.BtcDecode(r, 0, BaseEncoding) }
go
func (msg *MsgCFHeaders) Deserialize(r io.Reader) error { // At the current time, there is no difference between the wire encoding // and the stable long-term storage format. As a result, make use of // BtcDecode. return msg.BtcDecode(r, 0, BaseEncoding) }
[ "func", "(", "msg", "*", "MsgCFHeaders", ")", "Deserialize", "(", "r", "io", ".", "Reader", ")", "error", "{", "// At the current time, there is no difference between the wire encoding", "// and the stable long-term storage format. As a result, make use of", "// BtcDecode.", "re...
// Deserialize decodes a filter header from r into the receiver using a format // that is suitable for long-term storage such as a database. This function // differs from BtcDecode in that BtcDecode decodes from the bitcoin wire // protocol as it was sent across the network. The wire encoding can // technically differ depending on the protocol version and doesn't even really // need to match the format of a stored filter header at all. As of the time // this comment was written, the encoded filter header is the same in both // instances, but there is a distinct difference and separating the two allows // the API to be flexible enough to deal with changes.
[ "Deserialize", "decodes", "a", "filter", "header", "from", "r", "into", "the", "receiver", "using", "a", "format", "that", "is", "suitable", "for", "long", "-", "term", "storage", "such", "as", "a", "database", ".", "This", "function", "differs", "from", "...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgcfheaders.go#L152-L157
162,410
btcsuite/btcd
txscript/scriptnum.go
checkMinimalDataEncoding
func checkMinimalDataEncoding(v []byte) error { if len(v) == 0 { return nil } // Check that the number is encoded with the minimum possible // number of bytes. // // If the most-significant-byte - excluding the sign bit - is zero // then we're not minimal. Note how this test also rejects the // negative-zero encoding, [0x80]. if v[len(v)-1]&0x7f == 0 { // One exception: if there's more than one byte and the most // significant bit of the second-most-significant-byte is set // it would conflict with the sign bit. An example of this case // is +-255, which encode to 0xff00 and 0xff80 respectively. // (big-endian). if len(v) == 1 || v[len(v)-2]&0x80 == 0 { str := fmt.Sprintf("numeric value encoded as %x is "+ "not minimally encoded", v) return scriptError(ErrMinimalData, str) } } return nil }
go
func checkMinimalDataEncoding(v []byte) error { if len(v) == 0 { return nil } // Check that the number is encoded with the minimum possible // number of bytes. // // If the most-significant-byte - excluding the sign bit - is zero // then we're not minimal. Note how this test also rejects the // negative-zero encoding, [0x80]. if v[len(v)-1]&0x7f == 0 { // One exception: if there's more than one byte and the most // significant bit of the second-most-significant-byte is set // it would conflict with the sign bit. An example of this case // is +-255, which encode to 0xff00 and 0xff80 respectively. // (big-endian). if len(v) == 1 || v[len(v)-2]&0x80 == 0 { str := fmt.Sprintf("numeric value encoded as %x is "+ "not minimally encoded", v) return scriptError(ErrMinimalData, str) } } return nil }
[ "func", "checkMinimalDataEncoding", "(", "v", "[", "]", "byte", ")", "error", "{", "if", "len", "(", "v", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "// Check that the number is encoded with the minimum possible", "// number of bytes.", "//", "// If ...
// checkMinimalDataEncoding returns whether or not the passed byte array adheres // to the minimal encoding requirements.
[ "checkMinimalDataEncoding", "returns", "whether", "or", "not", "the", "passed", "byte", "array", "adheres", "to", "the", "minimal", "encoding", "requirements", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/scriptnum.go#L50-L75
162,411
btcsuite/btcd
txscript/scriptnum.go
Int32
func (n scriptNum) Int32() int32 { if n > maxInt32 { return maxInt32 } if n < minInt32 { return minInt32 } return int32(n) }
go
func (n scriptNum) Int32() int32 { if n > maxInt32 { return maxInt32 } if n < minInt32 { return minInt32 } return int32(n) }
[ "func", "(", "n", "scriptNum", ")", "Int32", "(", ")", "int32", "{", "if", "n", ">", "maxInt32", "{", "return", "maxInt32", "\n", "}", "\n\n", "if", "n", "<", "minInt32", "{", "return", "minInt32", "\n", "}", "\n\n", "return", "int32", "(", "n", ")...
// Int32 returns the script number clamped to a valid int32. That is to say // when the script number is higher than the max allowed int32, the max int32 // value is returned and vice versa for the minimum value. Note that this // behavior is different from a simple int32 cast because that truncates // and the consensus rules dictate numbers which are directly cast to ints // provide this behavior. // // In practice, for most opcodes, the number should never be out of range since // it will have been created with makeScriptNum using the defaultScriptLen // value, which rejects them. In case something in the future ends up calling // this function against the result of some arithmetic, which IS allowed to be // out of range before being reinterpreted as an integer, this will provide the // correct behavior.
[ "Int32", "returns", "the", "script", "number", "clamped", "to", "a", "valid", "int32", ".", "That", "is", "to", "say", "when", "the", "script", "number", "is", "higher", "than", "the", "max", "allowed", "int32", "the", "max", "int32", "value", "is", "ret...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/scriptnum.go#L147-L157
162,412
btcsuite/btcd
blockchain/compress.go
putVLQ
func putVLQ(target []byte, n uint64) int { offset := 0 for ; ; offset++ { // The high bit is set when another byte follows. highBitMask := byte(0x80) if offset == 0 { highBitMask = 0x00 } target[offset] = byte(n&0x7f) | highBitMask if n <= 0x7f { break } n = (n >> 7) - 1 } // Reverse the bytes so it is MSB-encoded. for i, j := 0, offset; i < j; i, j = i+1, j-1 { target[i], target[j] = target[j], target[i] } return offset + 1 }
go
func putVLQ(target []byte, n uint64) int { offset := 0 for ; ; offset++ { // The high bit is set when another byte follows. highBitMask := byte(0x80) if offset == 0 { highBitMask = 0x00 } target[offset] = byte(n&0x7f) | highBitMask if n <= 0x7f { break } n = (n >> 7) - 1 } // Reverse the bytes so it is MSB-encoded. for i, j := 0, offset; i < j; i, j = i+1, j-1 { target[i], target[j] = target[j], target[i] } return offset + 1 }
[ "func", "putVLQ", "(", "target", "[", "]", "byte", ",", "n", "uint64", ")", "int", "{", "offset", ":=", "0", "\n", "for", ";", ";", "offset", "++", "{", "// The high bit is set when another byte follows.", "highBitMask", ":=", "byte", "(", "0x80", ")", "\n...
// putVLQ serializes the provided number to a variable-length quantity according // to the format described above and returns the number of bytes of the encoded // value. The result is placed directly into the passed byte slice which must // be at least large enough to handle the number of bytes returned by the // serializeSizeVLQ function or it will panic.
[ "putVLQ", "serializes", "the", "provided", "number", "to", "a", "variable", "-", "length", "quantity", "according", "to", "the", "format", "described", "above", "and", "returns", "the", "number", "of", "bytes", "of", "the", "encoded", "value", ".", "The", "r...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/compress.go#L66-L88
162,413
btcsuite/btcd
blockchain/compress.go
deserializeVLQ
func deserializeVLQ(serialized []byte) (uint64, int) { var n uint64 var size int for _, val := range serialized { size++ n = (n << 7) | uint64(val&0x7f) if val&0x80 != 0x80 { break } n++ } return n, size }
go
func deserializeVLQ(serialized []byte) (uint64, int) { var n uint64 var size int for _, val := range serialized { size++ n = (n << 7) | uint64(val&0x7f) if val&0x80 != 0x80 { break } n++ } return n, size }
[ "func", "deserializeVLQ", "(", "serialized", "[", "]", "byte", ")", "(", "uint64", ",", "int", ")", "{", "var", "n", "uint64", "\n", "var", "size", "int", "\n", "for", "_", ",", "val", ":=", "range", "serialized", "{", "size", "++", "\n", "n", "=",...
// deserializeVLQ deserializes the provided variable-length quantity according // to the format described above. It also returns the number of bytes // deserialized.
[ "deserializeVLQ", "deserializes", "the", "provided", "variable", "-", "length", "quantity", "according", "to", "the", "format", "described", "above", ".", "It", "also", "returns", "the", "number", "of", "bytes", "deserialized", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/compress.go#L93-L106
162,414
btcsuite/btcd
blockchain/compress.go
isPubKeyHash
func isPubKeyHash(script []byte) (bool, []byte) { if len(script) == 25 && script[0] == txscript.OP_DUP && script[1] == txscript.OP_HASH160 && script[2] == txscript.OP_DATA_20 && script[23] == txscript.OP_EQUALVERIFY && script[24] == txscript.OP_CHECKSIG { return true, script[3:23] } return false, nil }
go
func isPubKeyHash(script []byte) (bool, []byte) { if len(script) == 25 && script[0] == txscript.OP_DUP && script[1] == txscript.OP_HASH160 && script[2] == txscript.OP_DATA_20 && script[23] == txscript.OP_EQUALVERIFY && script[24] == txscript.OP_CHECKSIG { return true, script[3:23] } return false, nil }
[ "func", "isPubKeyHash", "(", "script", "[", "]", "byte", ")", "(", "bool", ",", "[", "]", "byte", ")", "{", "if", "len", "(", "script", ")", "==", "25", "&&", "script", "[", "0", "]", "==", "txscript", ".", "OP_DUP", "&&", "script", "[", "1", "...
// isPubKeyHash returns whether or not the passed public key script is a // standard pay-to-pubkey-hash script along with the pubkey hash it is paying to // if it is.
[ "isPubKeyHash", "returns", "whether", "or", "not", "the", "passed", "public", "key", "script", "is", "a", "standard", "pay", "-", "to", "-", "pubkey", "-", "hash", "script", "along", "with", "the", "pubkey", "hash", "it", "is", "paying", "to", "if", "it"...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/compress.go#L177-L188
162,415
btcsuite/btcd
blockchain/compress.go
isScriptHash
func isScriptHash(script []byte) (bool, []byte) { if len(script) == 23 && script[0] == txscript.OP_HASH160 && script[1] == txscript.OP_DATA_20 && script[22] == txscript.OP_EQUAL { return true, script[2:22] } return false, nil }
go
func isScriptHash(script []byte) (bool, []byte) { if len(script) == 23 && script[0] == txscript.OP_HASH160 && script[1] == txscript.OP_DATA_20 && script[22] == txscript.OP_EQUAL { return true, script[2:22] } return false, nil }
[ "func", "isScriptHash", "(", "script", "[", "]", "byte", ")", "(", "bool", ",", "[", "]", "byte", ")", "{", "if", "len", "(", "script", ")", "==", "23", "&&", "script", "[", "0", "]", "==", "txscript", ".", "OP_HASH160", "&&", "script", "[", "1",...
// isScriptHash returns whether or not the passed public key script is a // standard pay-to-script-hash script along with the script hash it is paying to // if it is.
[ "isScriptHash", "returns", "whether", "or", "not", "the", "passed", "public", "key", "script", "is", "a", "standard", "pay", "-", "to", "-", "script", "-", "hash", "script", "along", "with", "the", "script", "hash", "it", "is", "paying", "to", "if", "it"...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/compress.go#L193-L202
162,416
btcsuite/btcd
blockchain/compress.go
compressedScriptSize
func compressedScriptSize(pkScript []byte) int { // Pay-to-pubkey-hash script. if valid, _ := isPubKeyHash(pkScript); valid { return 21 } // Pay-to-script-hash script. if valid, _ := isScriptHash(pkScript); valid { return 21 } // Pay-to-pubkey (compressed or uncompressed) script. if valid, _ := isPubKey(pkScript); valid { return 33 } // When none of the above special cases apply, encode the script as is // preceded by the sum of its size and the number of special cases // encoded as a variable length quantity. return serializeSizeVLQ(uint64(len(pkScript)+numSpecialScripts)) + len(pkScript) }
go
func compressedScriptSize(pkScript []byte) int { // Pay-to-pubkey-hash script. if valid, _ := isPubKeyHash(pkScript); valid { return 21 } // Pay-to-script-hash script. if valid, _ := isScriptHash(pkScript); valid { return 21 } // Pay-to-pubkey (compressed or uncompressed) script. if valid, _ := isPubKey(pkScript); valid { return 33 } // When none of the above special cases apply, encode the script as is // preceded by the sum of its size and the number of special cases // encoded as a variable length quantity. return serializeSizeVLQ(uint64(len(pkScript)+numSpecialScripts)) + len(pkScript) }
[ "func", "compressedScriptSize", "(", "pkScript", "[", "]", "byte", ")", "int", "{", "// Pay-to-pubkey-hash script.", "if", "valid", ",", "_", ":=", "isPubKeyHash", "(", "pkScript", ")", ";", "valid", "{", "return", "21", "\n", "}", "\n\n", "// Pay-to-script-ha...
// compressedScriptSize returns the number of bytes the passed script would take // when encoded with the domain specific compression algorithm described above.
[ "compressedScriptSize", "returns", "the", "number", "of", "bytes", "the", "passed", "script", "would", "take", "when", "encoded", "with", "the", "domain", "specific", "compression", "algorithm", "described", "above", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/compress.go#L244-L265
162,417
btcsuite/btcd
blockchain/compress.go
decodeCompressedScriptSize
func decodeCompressedScriptSize(serialized []byte) int { scriptSize, bytesRead := deserializeVLQ(serialized) if bytesRead == 0 { return 0 } switch scriptSize { case cstPayToPubKeyHash: return 21 case cstPayToScriptHash: return 21 case cstPayToPubKeyComp2, cstPayToPubKeyComp3, cstPayToPubKeyUncomp4, cstPayToPubKeyUncomp5: return 33 } scriptSize -= numSpecialScripts scriptSize += uint64(bytesRead) return int(scriptSize) }
go
func decodeCompressedScriptSize(serialized []byte) int { scriptSize, bytesRead := deserializeVLQ(serialized) if bytesRead == 0 { return 0 } switch scriptSize { case cstPayToPubKeyHash: return 21 case cstPayToScriptHash: return 21 case cstPayToPubKeyComp2, cstPayToPubKeyComp3, cstPayToPubKeyUncomp4, cstPayToPubKeyUncomp5: return 33 } scriptSize -= numSpecialScripts scriptSize += uint64(bytesRead) return int(scriptSize) }
[ "func", "decodeCompressedScriptSize", "(", "serialized", "[", "]", "byte", ")", "int", "{", "scriptSize", ",", "bytesRead", ":=", "deserializeVLQ", "(", "serialized", ")", "\n", "if", "bytesRead", "==", "0", "{", "return", "0", "\n", "}", "\n\n", "switch", ...
// decodeCompressedScriptSize treats the passed serialized bytes as a compressed // script, possibly followed by other data, and returns the number of bytes it // occupies taking into account the special encoding of the script size by the // domain specific compression algorithm described above.
[ "decodeCompressedScriptSize", "treats", "the", "passed", "serialized", "bytes", "as", "a", "compressed", "script", "possibly", "followed", "by", "other", "data", "and", "returns", "the", "number", "of", "bytes", "it", "occupies", "taking", "into", "account", "the"...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/compress.go#L271-L292
162,418
btcsuite/btcd
blockchain/compress.go
putCompressedScript
func putCompressedScript(target, pkScript []byte) int { // Pay-to-pubkey-hash script. if valid, hash := isPubKeyHash(pkScript); valid { target[0] = cstPayToPubKeyHash copy(target[1:21], hash) return 21 } // Pay-to-script-hash script. if valid, hash := isScriptHash(pkScript); valid { target[0] = cstPayToScriptHash copy(target[1:21], hash) return 21 } // Pay-to-pubkey (compressed or uncompressed) script. if valid, serializedPubKey := isPubKey(pkScript); valid { pubKeyFormat := serializedPubKey[0] switch pubKeyFormat { case 0x02, 0x03: target[0] = pubKeyFormat copy(target[1:33], serializedPubKey[1:33]) return 33 case 0x04: // Encode the oddness of the serialized pubkey into the // compressed script type. target[0] = pubKeyFormat | (serializedPubKey[64] & 0x01) copy(target[1:33], serializedPubKey[1:33]) return 33 } } // When none of the above special cases apply, encode the unmodified // script preceded by the sum of its size and the number of special // cases encoded as a variable length quantity. encodedSize := uint64(len(pkScript) + numSpecialScripts) vlqSizeLen := putVLQ(target, encodedSize) copy(target[vlqSizeLen:], pkScript) return vlqSizeLen + len(pkScript) }
go
func putCompressedScript(target, pkScript []byte) int { // Pay-to-pubkey-hash script. if valid, hash := isPubKeyHash(pkScript); valid { target[0] = cstPayToPubKeyHash copy(target[1:21], hash) return 21 } // Pay-to-script-hash script. if valid, hash := isScriptHash(pkScript); valid { target[0] = cstPayToScriptHash copy(target[1:21], hash) return 21 } // Pay-to-pubkey (compressed or uncompressed) script. if valid, serializedPubKey := isPubKey(pkScript); valid { pubKeyFormat := serializedPubKey[0] switch pubKeyFormat { case 0x02, 0x03: target[0] = pubKeyFormat copy(target[1:33], serializedPubKey[1:33]) return 33 case 0x04: // Encode the oddness of the serialized pubkey into the // compressed script type. target[0] = pubKeyFormat | (serializedPubKey[64] & 0x01) copy(target[1:33], serializedPubKey[1:33]) return 33 } } // When none of the above special cases apply, encode the unmodified // script preceded by the sum of its size and the number of special // cases encoded as a variable length quantity. encodedSize := uint64(len(pkScript) + numSpecialScripts) vlqSizeLen := putVLQ(target, encodedSize) copy(target[vlqSizeLen:], pkScript) return vlqSizeLen + len(pkScript) }
[ "func", "putCompressedScript", "(", "target", ",", "pkScript", "[", "]", "byte", ")", "int", "{", "// Pay-to-pubkey-hash script.", "if", "valid", ",", "hash", ":=", "isPubKeyHash", "(", "pkScript", ")", ";", "valid", "{", "target", "[", "0", "]", "=", "cst...
// putCompressedScript compresses the passed script according to the domain // specific compression algorithm described above directly into the passed // target byte slice. The target byte slice must be at least large enough to // handle the number of bytes returned by the compressedScriptSize function or // it will panic.
[ "putCompressedScript", "compresses", "the", "passed", "script", "according", "to", "the", "domain", "specific", "compression", "algorithm", "described", "above", "directly", "into", "the", "passed", "target", "byte", "slice", ".", "The", "target", "byte", "slice", ...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/compress.go#L299-L338
162,419
btcsuite/btcd
blockchain/compress.go
decompressTxOutAmount
func decompressTxOutAmount(amount uint64) uint64 { // No need to do any work if it's zero. if amount == 0 { return 0 } // The decompressed amount is either of the following two equations: // x = 1 + 10*(9*n + d - 1) + e // x = 1 + 10*(n - 1) + 9 amount-- // The decompressed amount is now one of the following two equations: // x = 10*(9*n + d - 1) + e // x = 10*(n - 1) + 9 exponent := amount % 10 amount /= 10 // The decompressed amount is now one of the following two equations: // x = 9*n + d - 1 | where e < 9 // x = n - 1 | where e = 9 n := uint64(0) if exponent < 9 { lastDigit := amount%9 + 1 amount /= 9 n = amount*10 + lastDigit } else { n = amount + 1 } // Apply the exponent. for ; exponent > 0; exponent-- { n *= 10 } return n }
go
func decompressTxOutAmount(amount uint64) uint64 { // No need to do any work if it's zero. if amount == 0 { return 0 } // The decompressed amount is either of the following two equations: // x = 1 + 10*(9*n + d - 1) + e // x = 1 + 10*(n - 1) + 9 amount-- // The decompressed amount is now one of the following two equations: // x = 10*(9*n + d - 1) + e // x = 10*(n - 1) + 9 exponent := amount % 10 amount /= 10 // The decompressed amount is now one of the following two equations: // x = 9*n + d - 1 | where e < 9 // x = n - 1 | where e = 9 n := uint64(0) if exponent < 9 { lastDigit := amount%9 + 1 amount /= 9 n = amount*10 + lastDigit } else { n = amount + 1 } // Apply the exponent. for ; exponent > 0; exponent-- { n *= 10 } return n }
[ "func", "decompressTxOutAmount", "(", "amount", "uint64", ")", "uint64", "{", "// No need to do any work if it's zero.", "if", "amount", "==", "0", "{", "return", "0", "\n", "}", "\n\n", "// The decompressed amount is either of the following two equations:", "// x = 1 + 10*(9...
// decompressTxOutAmount returns the original amount the passed compressed // amount represents according to the domain specific compression algorithm // described above.
[ "decompressTxOutAmount", "returns", "the", "original", "amount", "the", "passed", "compressed", "amount", "represents", "according", "to", "the", "domain", "specific", "compression", "algorithm", "described", "above", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/compress.go#L493-L528
162,420
btcsuite/btcd
blockchain/compress.go
putCompressedTxOut
func putCompressedTxOut(target []byte, amount uint64, pkScript []byte) int { offset := putVLQ(target, compressTxOutAmount(amount)) offset += putCompressedScript(target[offset:], pkScript) return offset }
go
func putCompressedTxOut(target []byte, amount uint64, pkScript []byte) int { offset := putVLQ(target, compressTxOutAmount(amount)) offset += putCompressedScript(target[offset:], pkScript) return offset }
[ "func", "putCompressedTxOut", "(", "target", "[", "]", "byte", ",", "amount", "uint64", ",", "pkScript", "[", "]", "byte", ")", "int", "{", "offset", ":=", "putVLQ", "(", "target", ",", "compressTxOutAmount", "(", "amount", ")", ")", "\n", "offset", "+="...
// putCompressedTxOut compresses the passed amount and script according to their // domain specific compression algorithms and encodes them directly into the // passed target byte slice with the format described above. The target byte // slice must be at least large enough to handle the number of bytes returned by // the compressedTxOutSize function or it will panic.
[ "putCompressedTxOut", "compresses", "the", "passed", "amount", "and", "script", "according", "to", "their", "domain", "specific", "compression", "algorithms", "and", "encodes", "them", "directly", "into", "the", "passed", "target", "byte", "slice", "with", "the", ...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/compress.go#L556-L560
162,421
btcsuite/btcd
blockchain/compress.go
decodeCompressedTxOut
func decodeCompressedTxOut(serialized []byte) (uint64, []byte, int, error) { // Deserialize the compressed amount and ensure there are bytes // remaining for the compressed script. compressedAmount, bytesRead := deserializeVLQ(serialized) if bytesRead >= len(serialized) { return 0, nil, bytesRead, errDeserialize("unexpected end of " + "data after compressed amount") } // Decode the compressed script size and ensure there are enough bytes // left in the slice for it. scriptSize := decodeCompressedScriptSize(serialized[bytesRead:]) if len(serialized[bytesRead:]) < scriptSize { return 0, nil, bytesRead, errDeserialize("unexpected end of " + "data after script size") } // Decompress and return the amount and script. amount := decompressTxOutAmount(compressedAmount) script := decompressScript(serialized[bytesRead : bytesRead+scriptSize]) return amount, script, bytesRead + scriptSize, nil }
go
func decodeCompressedTxOut(serialized []byte) (uint64, []byte, int, error) { // Deserialize the compressed amount and ensure there are bytes // remaining for the compressed script. compressedAmount, bytesRead := deserializeVLQ(serialized) if bytesRead >= len(serialized) { return 0, nil, bytesRead, errDeserialize("unexpected end of " + "data after compressed amount") } // Decode the compressed script size and ensure there are enough bytes // left in the slice for it. scriptSize := decodeCompressedScriptSize(serialized[bytesRead:]) if len(serialized[bytesRead:]) < scriptSize { return 0, nil, bytesRead, errDeserialize("unexpected end of " + "data after script size") } // Decompress and return the amount and script. amount := decompressTxOutAmount(compressedAmount) script := decompressScript(serialized[bytesRead : bytesRead+scriptSize]) return amount, script, bytesRead + scriptSize, nil }
[ "func", "decodeCompressedTxOut", "(", "serialized", "[", "]", "byte", ")", "(", "uint64", ",", "[", "]", "byte", ",", "int", ",", "error", ")", "{", "// Deserialize the compressed amount and ensure there are bytes", "// remaining for the compressed script.", "compressedAm...
// decodeCompressedTxOut decodes the passed compressed txout, possibly followed // by other data, into its uncompressed amount and script and returns them along // with the number of bytes they occupied prior to decompression.
[ "decodeCompressedTxOut", "decodes", "the", "passed", "compressed", "txout", "possibly", "followed", "by", "other", "data", "into", "its", "uncompressed", "amount", "and", "script", "and", "returns", "them", "along", "with", "the", "number", "of", "bytes", "they", ...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/compress.go#L565-L586
162,422
btcsuite/btcd
wire/msgaddr.go
AddAddress
func (msg *MsgAddr) AddAddress(na *NetAddress) error { if len(msg.AddrList)+1 > MaxAddrPerMsg { str := fmt.Sprintf("too many addresses in message [max %v]", MaxAddrPerMsg) return messageError("MsgAddr.AddAddress", str) } msg.AddrList = append(msg.AddrList, na) return nil }
go
func (msg *MsgAddr) AddAddress(na *NetAddress) error { if len(msg.AddrList)+1 > MaxAddrPerMsg { str := fmt.Sprintf("too many addresses in message [max %v]", MaxAddrPerMsg) return messageError("MsgAddr.AddAddress", str) } msg.AddrList = append(msg.AddrList, na) return nil }
[ "func", "(", "msg", "*", "MsgAddr", ")", "AddAddress", "(", "na", "*", "NetAddress", ")", "error", "{", "if", "len", "(", "msg", ".", "AddrList", ")", "+", "1", ">", "MaxAddrPerMsg", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", ...
// AddAddress adds a known active peer to the message.
[ "AddAddress", "adds", "a", "known", "active", "peer", "to", "the", "message", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgaddr.go#L31-L40
162,423
btcsuite/btcd
wire/msgaddr.go
AddAddresses
func (msg *MsgAddr) AddAddresses(netAddrs ...*NetAddress) error { for _, na := range netAddrs { err := msg.AddAddress(na) if err != nil { return err } } return nil }
go
func (msg *MsgAddr) AddAddresses(netAddrs ...*NetAddress) error { for _, na := range netAddrs { err := msg.AddAddress(na) if err != nil { return err } } return nil }
[ "func", "(", "msg", "*", "MsgAddr", ")", "AddAddresses", "(", "netAddrs", "...", "*", "NetAddress", ")", "error", "{", "for", "_", ",", "na", ":=", "range", "netAddrs", "{", "err", ":=", "msg", ".", "AddAddress", "(", "na", ")", "\n", "if", "err", ...
// AddAddresses adds multiple known active peers to the message.
[ "AddAddresses", "adds", "multiple", "known", "active", "peers", "to", "the", "message", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgaddr.go#L43-L51
162,424
btcsuite/btcd
txscript/opcode.go
isConditional
func (pop *parsedOpcode) isConditional() bool { switch pop.opcode.value { case OP_IF: return true case OP_NOTIF: return true case OP_ELSE: return true case OP_ENDIF: return true default: return false } }
go
func (pop *parsedOpcode) isConditional() bool { switch pop.opcode.value { case OP_IF: return true case OP_NOTIF: return true case OP_ELSE: return true case OP_ENDIF: return true default: return false } }
[ "func", "(", "pop", "*", "parsedOpcode", ")", "isConditional", "(", ")", "bool", "{", "switch", "pop", ".", "opcode", ".", "value", "{", "case", "OP_IF", ":", "return", "true", "\n", "case", "OP_NOTIF", ":", "return", "true", "\n", "case", "OP_ELSE", "...
// isConditional returns whether or not the opcode is a conditional opcode which // changes the conditional execution stack when executed.
[ "isConditional", "returns", "whether", "or", "not", "the", "opcode", "is", "a", "conditional", "opcode", "which", "changes", "the", "conditional", "execution", "stack", "when", "executed", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/opcode.go#L675-L688
162,425
btcsuite/btcd
txscript/opcode.go
print
func (pop *parsedOpcode) print(oneline bool) string { // The reference implementation one-line disassembly replaces opcodes // which represent values (e.g. OP_0 through OP_16 and OP_1NEGATE) // with the raw value. However, when not doing a one-line dissassembly, // we prefer to show the actual opcode names. Thus, only replace the // opcodes in question when the oneline flag is set. opcodeName := pop.opcode.name if oneline { if replName, ok := opcodeOnelineRepls[opcodeName]; ok { opcodeName = replName } // Nothing more to do for non-data push opcodes. if pop.opcode.length == 1 { return opcodeName } return fmt.Sprintf("%x", pop.data) } // Nothing more to do for non-data push opcodes. if pop.opcode.length == 1 { return opcodeName } // Add length for the OP_PUSHDATA# opcodes. retString := opcodeName switch pop.opcode.length { case -1: retString += fmt.Sprintf(" 0x%02x", len(pop.data)) case -2: retString += fmt.Sprintf(" 0x%04x", len(pop.data)) case -4: retString += fmt.Sprintf(" 0x%08x", len(pop.data)) } return fmt.Sprintf("%s 0x%02x", retString, pop.data) }
go
func (pop *parsedOpcode) print(oneline bool) string { // The reference implementation one-line disassembly replaces opcodes // which represent values (e.g. OP_0 through OP_16 and OP_1NEGATE) // with the raw value. However, when not doing a one-line dissassembly, // we prefer to show the actual opcode names. Thus, only replace the // opcodes in question when the oneline flag is set. opcodeName := pop.opcode.name if oneline { if replName, ok := opcodeOnelineRepls[opcodeName]; ok { opcodeName = replName } // Nothing more to do for non-data push opcodes. if pop.opcode.length == 1 { return opcodeName } return fmt.Sprintf("%x", pop.data) } // Nothing more to do for non-data push opcodes. if pop.opcode.length == 1 { return opcodeName } // Add length for the OP_PUSHDATA# opcodes. retString := opcodeName switch pop.opcode.length { case -1: retString += fmt.Sprintf(" 0x%02x", len(pop.data)) case -2: retString += fmt.Sprintf(" 0x%04x", len(pop.data)) case -4: retString += fmt.Sprintf(" 0x%08x", len(pop.data)) } return fmt.Sprintf("%s 0x%02x", retString, pop.data) }
[ "func", "(", "pop", "*", "parsedOpcode", ")", "print", "(", "oneline", "bool", ")", "string", "{", "// The reference implementation one-line disassembly replaces opcodes", "// which represent values (e.g. OP_0 through OP_16 and OP_1NEGATE)", "// with the raw value. However, when not d...
// print returns a human-readable string representation of the opcode for use // in script disassembly.
[ "print", "returns", "a", "human", "-", "readable", "string", "representation", "of", "the", "opcode", "for", "use", "in", "script", "disassembly", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/opcode.go#L747-L784
162,426
btcsuite/btcd
txscript/opcode.go
bytes
func (pop *parsedOpcode) bytes() ([]byte, error) { var retbytes []byte if pop.opcode.length > 0 { retbytes = make([]byte, 1, pop.opcode.length) } else { retbytes = make([]byte, 1, 1+len(pop.data)- pop.opcode.length) } retbytes[0] = pop.opcode.value if pop.opcode.length == 1 { if len(pop.data) != 0 { str := fmt.Sprintf("internal consistency error - "+ "parsed opcode %s has data length %d when %d "+ "was expected", pop.opcode.name, len(pop.data), 0) return nil, scriptError(ErrInternal, str) } return retbytes, nil } nbytes := pop.opcode.length if pop.opcode.length < 0 { l := len(pop.data) // tempting just to hardcode to avoid the complexity here. switch pop.opcode.length { case -1: retbytes = append(retbytes, byte(l)) nbytes = int(retbytes[1]) + len(retbytes) case -2: retbytes = append(retbytes, byte(l&0xff), byte(l>>8&0xff)) nbytes = int(binary.LittleEndian.Uint16(retbytes[1:])) + len(retbytes) case -4: retbytes = append(retbytes, byte(l&0xff), byte((l>>8)&0xff), byte((l>>16)&0xff), byte((l>>24)&0xff)) nbytes = int(binary.LittleEndian.Uint32(retbytes[1:])) + len(retbytes) } } retbytes = append(retbytes, pop.data...) if len(retbytes) != nbytes { str := fmt.Sprintf("internal consistency error - "+ "parsed opcode %s has data length %d when %d was "+ "expected", pop.opcode.name, len(retbytes), nbytes) return nil, scriptError(ErrInternal, str) } return retbytes, nil }
go
func (pop *parsedOpcode) bytes() ([]byte, error) { var retbytes []byte if pop.opcode.length > 0 { retbytes = make([]byte, 1, pop.opcode.length) } else { retbytes = make([]byte, 1, 1+len(pop.data)- pop.opcode.length) } retbytes[0] = pop.opcode.value if pop.opcode.length == 1 { if len(pop.data) != 0 { str := fmt.Sprintf("internal consistency error - "+ "parsed opcode %s has data length %d when %d "+ "was expected", pop.opcode.name, len(pop.data), 0) return nil, scriptError(ErrInternal, str) } return retbytes, nil } nbytes := pop.opcode.length if pop.opcode.length < 0 { l := len(pop.data) // tempting just to hardcode to avoid the complexity here. switch pop.opcode.length { case -1: retbytes = append(retbytes, byte(l)) nbytes = int(retbytes[1]) + len(retbytes) case -2: retbytes = append(retbytes, byte(l&0xff), byte(l>>8&0xff)) nbytes = int(binary.LittleEndian.Uint16(retbytes[1:])) + len(retbytes) case -4: retbytes = append(retbytes, byte(l&0xff), byte((l>>8)&0xff), byte((l>>16)&0xff), byte((l>>24)&0xff)) nbytes = int(binary.LittleEndian.Uint32(retbytes[1:])) + len(retbytes) } } retbytes = append(retbytes, pop.data...) if len(retbytes) != nbytes { str := fmt.Sprintf("internal consistency error - "+ "parsed opcode %s has data length %d when %d was "+ "expected", pop.opcode.name, len(retbytes), nbytes) return nil, scriptError(ErrInternal, str) } return retbytes, nil }
[ "func", "(", "pop", "*", "parsedOpcode", ")", "bytes", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "retbytes", "[", "]", "byte", "\n", "if", "pop", ".", "opcode", ".", "length", ">", "0", "{", "retbytes", "=", "make", "(", "...
// bytes returns any data associated with the opcode encoded as it would be in // a script. This is used for unparsing scripts from parsed opcodes.
[ "bytes", "returns", "any", "data", "associated", "with", "the", "opcode", "encoded", "as", "it", "would", "be", "in", "a", "script", ".", "This", "is", "used", "for", "unparsing", "scripts", "from", "parsed", "opcodes", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/opcode.go#L788-L840
162,427
btcsuite/btcd
txscript/opcode.go
opcodeReserved
func opcodeReserved(op *parsedOpcode, vm *Engine) error { str := fmt.Sprintf("attempt to execute reserved opcode %s", op.opcode.name) return scriptError(ErrReservedOpcode, str) }
go
func opcodeReserved(op *parsedOpcode, vm *Engine) error { str := fmt.Sprintf("attempt to execute reserved opcode %s", op.opcode.name) return scriptError(ErrReservedOpcode, str) }
[ "func", "opcodeReserved", "(", "op", "*", "parsedOpcode", ",", "vm", "*", "Engine", ")", "error", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "op", ".", "opcode", ".", "name", ")", "\n", "return", "scriptError", "(", "ErrReservedOpco...
// opcodeReserved is a common handler for all reserved opcodes. It returns an // appropriate error indicating the opcode is reserved.
[ "opcodeReserved", "is", "a", "common", "handler", "for", "all", "reserved", "opcodes", ".", "It", "returns", "an", "appropriate", "error", "indicating", "the", "opcode", "is", "reserved", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/opcode.go#L860-L864
162,428
btcsuite/btcd
txscript/opcode.go
opcodeFalse
func opcodeFalse(op *parsedOpcode, vm *Engine) error { vm.dstack.PushByteArray(nil) return nil }
go
func opcodeFalse(op *parsedOpcode, vm *Engine) error { vm.dstack.PushByteArray(nil) return nil }
[ "func", "opcodeFalse", "(", "op", "*", "parsedOpcode", ",", "vm", "*", "Engine", ")", "error", "{", "vm", ".", "dstack", ".", "PushByteArray", "(", "nil", ")", "\n", "return", "nil", "\n", "}" ]
// opcodeFalse pushes an empty array to the data stack to represent false. Note // that 0, when encoded as a number according to the numeric encoding consensus // rules, is an empty array.
[ "opcodeFalse", "pushes", "an", "empty", "array", "to", "the", "data", "stack", "to", "represent", "false", ".", "Note", "that", "0", "when", "encoded", "as", "a", "number", "according", "to", "the", "numeric", "encoding", "consensus", "rules", "is", "an", ...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/opcode.go#L877-L880
162,429
btcsuite/btcd
txscript/opcode.go
opcode1Negate
func opcode1Negate(op *parsedOpcode, vm *Engine) error { vm.dstack.PushInt(scriptNum(-1)) return nil }
go
func opcode1Negate(op *parsedOpcode, vm *Engine) error { vm.dstack.PushInt(scriptNum(-1)) return nil }
[ "func", "opcode1Negate", "(", "op", "*", "parsedOpcode", ",", "vm", "*", "Engine", ")", "error", "{", "vm", ".", "dstack", ".", "PushInt", "(", "scriptNum", "(", "-", "1", ")", ")", "\n", "return", "nil", "\n", "}" ]
// opcode1Negate pushes -1, encoded as a number, to the data stack.
[ "opcode1Negate", "pushes", "-", "1", "encoded", "as", "a", "number", "to", "the", "data", "stack", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/opcode.go#L890-L893
162,430
btcsuite/btcd
txscript/opcode.go
opcodeNop
func opcodeNop(op *parsedOpcode, vm *Engine) error { switch op.opcode.value { case OP_NOP1, OP_NOP4, OP_NOP5, OP_NOP6, OP_NOP7, OP_NOP8, OP_NOP9, OP_NOP10: if vm.hasFlag(ScriptDiscourageUpgradableNops) { str := fmt.Sprintf("OP_NOP%d reserved for soft-fork "+ "upgrades", op.opcode.value-(OP_NOP1-1)) return scriptError(ErrDiscourageUpgradableNOPs, str) } } return nil }
go
func opcodeNop(op *parsedOpcode, vm *Engine) error { switch op.opcode.value { case OP_NOP1, OP_NOP4, OP_NOP5, OP_NOP6, OP_NOP7, OP_NOP8, OP_NOP9, OP_NOP10: if vm.hasFlag(ScriptDiscourageUpgradableNops) { str := fmt.Sprintf("OP_NOP%d reserved for soft-fork "+ "upgrades", op.opcode.value-(OP_NOP1-1)) return scriptError(ErrDiscourageUpgradableNOPs, str) } } return nil }
[ "func", "opcodeNop", "(", "op", "*", "parsedOpcode", ",", "vm", "*", "Engine", ")", "error", "{", "switch", "op", ".", "opcode", ".", "value", "{", "case", "OP_NOP1", ",", "OP_NOP4", ",", "OP_NOP5", ",", "OP_NOP6", ",", "OP_NOP7", ",", "OP_NOP8", ",", ...
// opcodeNop is a common handler for the NOP family of opcodes. As the name // implies it generally does nothing, however, it will return an error when // the flag to discourage use of NOPs is set for select opcodes.
[ "opcodeNop", "is", "a", "common", "handler", "for", "the", "NOP", "family", "of", "opcodes", ".", "As", "the", "name", "implies", "it", "generally", "does", "nothing", "however", "it", "will", "return", "an", "error", "when", "the", "flag", "to", "discoura...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/opcode.go#L908-L919
162,431
btcsuite/btcd
txscript/opcode.go
abstractVerify
func abstractVerify(op *parsedOpcode, vm *Engine, c ErrorCode) error { verified, err := vm.dstack.PopBool() if err != nil { return err } if !verified { str := fmt.Sprintf("%s failed", op.opcode.name) return scriptError(c, str) } return nil }
go
func abstractVerify(op *parsedOpcode, vm *Engine, c ErrorCode) error { verified, err := vm.dstack.PopBool() if err != nil { return err } if !verified { str := fmt.Sprintf("%s failed", op.opcode.name) return scriptError(c, str) } return nil }
[ "func", "abstractVerify", "(", "op", "*", "parsedOpcode", ",", "vm", "*", "Engine", ",", "c", "ErrorCode", ")", "error", "{", "verified", ",", "err", ":=", "vm", ".", "dstack", ".", "PopBool", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", ...
// abstractVerify examines the top item on the data stack as a boolean value and // verifies it evaluates to true. An error is returned either when there is no // item on the stack or when that item evaluates to false. In the latter case // where the verification fails specifically due to the top item evaluating // to false, the returned error will use the passed error code.
[ "abstractVerify", "examines", "the", "top", "item", "on", "the", "data", "stack", "as", "a", "boolean", "value", "and", "verifies", "it", "evaluates", "to", "true", ".", "An", "error", "is", "returned", "either", "when", "there", "is", "no", "item", "on", ...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/opcode.go#L1076-L1087
162,432
btcsuite/btcd
txscript/opcode.go
opcodeVerify
func opcodeVerify(op *parsedOpcode, vm *Engine) error { return abstractVerify(op, vm, ErrVerify) }
go
func opcodeVerify(op *parsedOpcode, vm *Engine) error { return abstractVerify(op, vm, ErrVerify) }
[ "func", "opcodeVerify", "(", "op", "*", "parsedOpcode", ",", "vm", "*", "Engine", ")", "error", "{", "return", "abstractVerify", "(", "op", ",", "vm", ",", "ErrVerify", ")", "\n", "}" ]
// opcodeVerify examines the top item on the data stack as a boolean value and // verifies it evaluates to true. An error is returned if it does not.
[ "opcodeVerify", "examines", "the", "top", "item", "on", "the", "data", "stack", "as", "a", "boolean", "value", "and", "verifies", "it", "evaluates", "to", "true", ".", "An", "error", "is", "returned", "if", "it", "does", "not", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/opcode.go#L1091-L1093
162,433
btcsuite/btcd
txscript/opcode.go
verifyLockTime
func verifyLockTime(txLockTime, threshold, lockTime int64) error { // The lockTimes in both the script and transaction must be of the same // type. if !((txLockTime < threshold && lockTime < threshold) || (txLockTime >= threshold && lockTime >= threshold)) { str := fmt.Sprintf("mismatched locktime types -- tx locktime "+ "%d, stack locktime %d", txLockTime, lockTime) return scriptError(ErrUnsatisfiedLockTime, str) } if lockTime > txLockTime { str := fmt.Sprintf("locktime requirement not satisfied -- "+ "locktime is greater than the transaction locktime: "+ "%d > %d", lockTime, txLockTime) return scriptError(ErrUnsatisfiedLockTime, str) } return nil }
go
func verifyLockTime(txLockTime, threshold, lockTime int64) error { // The lockTimes in both the script and transaction must be of the same // type. if !((txLockTime < threshold && lockTime < threshold) || (txLockTime >= threshold && lockTime >= threshold)) { str := fmt.Sprintf("mismatched locktime types -- tx locktime "+ "%d, stack locktime %d", txLockTime, lockTime) return scriptError(ErrUnsatisfiedLockTime, str) } if lockTime > txLockTime { str := fmt.Sprintf("locktime requirement not satisfied -- "+ "locktime is greater than the transaction locktime: "+ "%d > %d", lockTime, txLockTime) return scriptError(ErrUnsatisfiedLockTime, str) } return nil }
[ "func", "verifyLockTime", "(", "txLockTime", ",", "threshold", ",", "lockTime", "int64", ")", "error", "{", "// The lockTimes in both the script and transaction must be of the same", "// type.", "if", "!", "(", "(", "txLockTime", "<", "threshold", "&&", "lockTime", "<",...
// verifyLockTime is a helper function used to validate locktimes.
[ "verifyLockTime", "is", "a", "helper", "function", "used", "to", "validate", "locktimes", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/opcode.go#L1102-L1120
162,434
btcsuite/btcd
txscript/opcode.go
opcodeCheckLockTimeVerify
func opcodeCheckLockTimeVerify(op *parsedOpcode, vm *Engine) error { // If the ScriptVerifyCheckLockTimeVerify script flag is not set, treat // opcode as OP_NOP2 instead. if !vm.hasFlag(ScriptVerifyCheckLockTimeVerify) { if vm.hasFlag(ScriptDiscourageUpgradableNops) { return scriptError(ErrDiscourageUpgradableNOPs, "OP_NOP2 reserved for soft-fork upgrades") } return nil } // The current transaction locktime is a uint32 resulting in a maximum // locktime of 2^32-1 (the year 2106). However, scriptNums are signed // and therefore a standard 4-byte scriptNum would only support up to a // maximum of 2^31-1 (the year 2038). Thus, a 5-byte scriptNum is used // here since it will support up to 2^39-1 which allows dates beyond the // current locktime limit. // // PeekByteArray is used here instead of PeekInt because we do not want // to be limited to a 4-byte integer for reasons specified above. so, err := vm.dstack.PeekByteArray(0) if err != nil { return err } lockTime, err := makeScriptNum(so, vm.dstack.verifyMinimalData, 5) if err != nil { return err } // In the rare event that the argument needs to be < 0 due to some // arithmetic being done first, you can always use // 0 OP_MAX OP_CHECKLOCKTIMEVERIFY. if lockTime < 0 { str := fmt.Sprintf("negative lock time: %d", lockTime) return scriptError(ErrNegativeLockTime, str) } // The lock time field of a transaction is either a block height at // which the transaction is finalized or a timestamp depending on if the // value is before the txscript.LockTimeThreshold. When it is under the // threshold it is a block height. err = verifyLockTime(int64(vm.tx.LockTime), LockTimeThreshold, int64(lockTime)) if err != nil { return err } // The lock time feature can also be disabled, thereby bypassing // OP_CHECKLOCKTIMEVERIFY, if every transaction input has been finalized by // setting its sequence to the maximum value (wire.MaxTxInSequenceNum). This // condition would result in the transaction being allowed into the blockchain // making the opcode ineffective. // // This condition is prevented by enforcing that the input being used by // the opcode is unlocked (its sequence number is less than the max // value). This is sufficient to prove correctness without having to // check every input. // // NOTE: This implies that even if the transaction is not finalized due to // another input being unlocked, the opcode execution will still fail when the // input being used by the opcode is locked. if vm.tx.TxIn[vm.txIdx].Sequence == wire.MaxTxInSequenceNum { return scriptError(ErrUnsatisfiedLockTime, "transaction input is finalized") } return nil }
go
func opcodeCheckLockTimeVerify(op *parsedOpcode, vm *Engine) error { // If the ScriptVerifyCheckLockTimeVerify script flag is not set, treat // opcode as OP_NOP2 instead. if !vm.hasFlag(ScriptVerifyCheckLockTimeVerify) { if vm.hasFlag(ScriptDiscourageUpgradableNops) { return scriptError(ErrDiscourageUpgradableNOPs, "OP_NOP2 reserved for soft-fork upgrades") } return nil } // The current transaction locktime is a uint32 resulting in a maximum // locktime of 2^32-1 (the year 2106). However, scriptNums are signed // and therefore a standard 4-byte scriptNum would only support up to a // maximum of 2^31-1 (the year 2038). Thus, a 5-byte scriptNum is used // here since it will support up to 2^39-1 which allows dates beyond the // current locktime limit. // // PeekByteArray is used here instead of PeekInt because we do not want // to be limited to a 4-byte integer for reasons specified above. so, err := vm.dstack.PeekByteArray(0) if err != nil { return err } lockTime, err := makeScriptNum(so, vm.dstack.verifyMinimalData, 5) if err != nil { return err } // In the rare event that the argument needs to be < 0 due to some // arithmetic being done first, you can always use // 0 OP_MAX OP_CHECKLOCKTIMEVERIFY. if lockTime < 0 { str := fmt.Sprintf("negative lock time: %d", lockTime) return scriptError(ErrNegativeLockTime, str) } // The lock time field of a transaction is either a block height at // which the transaction is finalized or a timestamp depending on if the // value is before the txscript.LockTimeThreshold. When it is under the // threshold it is a block height. err = verifyLockTime(int64(vm.tx.LockTime), LockTimeThreshold, int64(lockTime)) if err != nil { return err } // The lock time feature can also be disabled, thereby bypassing // OP_CHECKLOCKTIMEVERIFY, if every transaction input has been finalized by // setting its sequence to the maximum value (wire.MaxTxInSequenceNum). This // condition would result in the transaction being allowed into the blockchain // making the opcode ineffective. // // This condition is prevented by enforcing that the input being used by // the opcode is unlocked (its sequence number is less than the max // value). This is sufficient to prove correctness without having to // check every input. // // NOTE: This implies that even if the transaction is not finalized due to // another input being unlocked, the opcode execution will still fail when the // input being used by the opcode is locked. if vm.tx.TxIn[vm.txIdx].Sequence == wire.MaxTxInSequenceNum { return scriptError(ErrUnsatisfiedLockTime, "transaction input is finalized") } return nil }
[ "func", "opcodeCheckLockTimeVerify", "(", "op", "*", "parsedOpcode", ",", "vm", "*", "Engine", ")", "error", "{", "// If the ScriptVerifyCheckLockTimeVerify script flag is not set, treat", "// opcode as OP_NOP2 instead.", "if", "!", "vm", ".", "hasFlag", "(", "ScriptVerifyC...
// opcodeCheckLockTimeVerify compares the top item on the data stack to the // LockTime field of the transaction containing the script signature // validating if the transaction outputs are spendable yet. If flag // ScriptVerifyCheckLockTimeVerify is not set, the code continues as if OP_NOP2 // were executed.
[ "opcodeCheckLockTimeVerify", "compares", "the", "top", "item", "on", "the", "data", "stack", "to", "the", "LockTime", "field", "of", "the", "transaction", "containing", "the", "script", "signature", "validating", "if", "the", "transaction", "outputs", "are", "spen...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/opcode.go#L1127-L1194
162,435
btcsuite/btcd
txscript/opcode.go
opcodeCheckSequenceVerify
func opcodeCheckSequenceVerify(op *parsedOpcode, vm *Engine) error { // If the ScriptVerifyCheckSequenceVerify script flag is not set, treat // opcode as OP_NOP3 instead. if !vm.hasFlag(ScriptVerifyCheckSequenceVerify) { if vm.hasFlag(ScriptDiscourageUpgradableNops) { return scriptError(ErrDiscourageUpgradableNOPs, "OP_NOP3 reserved for soft-fork upgrades") } return nil } // The current transaction sequence is a uint32 resulting in a maximum // sequence of 2^32-1. However, scriptNums are signed and therefore a // standard 4-byte scriptNum would only support up to a maximum of // 2^31-1. Thus, a 5-byte scriptNum is used here since it will support // up to 2^39-1 which allows sequences beyond the current sequence // limit. // // PeekByteArray is used here instead of PeekInt because we do not want // to be limited to a 4-byte integer for reasons specified above. so, err := vm.dstack.PeekByteArray(0) if err != nil { return err } stackSequence, err := makeScriptNum(so, vm.dstack.verifyMinimalData, 5) if err != nil { return err } // In the rare event that the argument needs to be < 0 due to some // arithmetic being done first, you can always use // 0 OP_MAX OP_CHECKSEQUENCEVERIFY. if stackSequence < 0 { str := fmt.Sprintf("negative sequence: %d", stackSequence) return scriptError(ErrNegativeLockTime, str) } sequence := int64(stackSequence) // To provide for future soft-fork extensibility, if the // operand has the disabled lock-time flag set, // CHECKSEQUENCEVERIFY behaves as a NOP. if sequence&int64(wire.SequenceLockTimeDisabled) != 0 { return nil } // Transaction version numbers not high enough to trigger CSV rules must // fail. if vm.tx.Version < 2 { str := fmt.Sprintf("invalid transaction version: %d", vm.tx.Version) return scriptError(ErrUnsatisfiedLockTime, str) } // Sequence numbers with their most significant bit set are not // consensus constrained. Testing that the transaction's sequence // number does not have this bit set prevents using this property // to get around a CHECKSEQUENCEVERIFY check. txSequence := int64(vm.tx.TxIn[vm.txIdx].Sequence) if txSequence&int64(wire.SequenceLockTimeDisabled) != 0 { str := fmt.Sprintf("transaction sequence has sequence "+ "locktime disabled bit set: 0x%x", txSequence) return scriptError(ErrUnsatisfiedLockTime, str) } // Mask off non-consensus bits before doing comparisons. lockTimeMask := int64(wire.SequenceLockTimeIsSeconds | wire.SequenceLockTimeMask) return verifyLockTime(txSequence&lockTimeMask, wire.SequenceLockTimeIsSeconds, sequence&lockTimeMask) }
go
func opcodeCheckSequenceVerify(op *parsedOpcode, vm *Engine) error { // If the ScriptVerifyCheckSequenceVerify script flag is not set, treat // opcode as OP_NOP3 instead. if !vm.hasFlag(ScriptVerifyCheckSequenceVerify) { if vm.hasFlag(ScriptDiscourageUpgradableNops) { return scriptError(ErrDiscourageUpgradableNOPs, "OP_NOP3 reserved for soft-fork upgrades") } return nil } // The current transaction sequence is a uint32 resulting in a maximum // sequence of 2^32-1. However, scriptNums are signed and therefore a // standard 4-byte scriptNum would only support up to a maximum of // 2^31-1. Thus, a 5-byte scriptNum is used here since it will support // up to 2^39-1 which allows sequences beyond the current sequence // limit. // // PeekByteArray is used here instead of PeekInt because we do not want // to be limited to a 4-byte integer for reasons specified above. so, err := vm.dstack.PeekByteArray(0) if err != nil { return err } stackSequence, err := makeScriptNum(so, vm.dstack.verifyMinimalData, 5) if err != nil { return err } // In the rare event that the argument needs to be < 0 due to some // arithmetic being done first, you can always use // 0 OP_MAX OP_CHECKSEQUENCEVERIFY. if stackSequence < 0 { str := fmt.Sprintf("negative sequence: %d", stackSequence) return scriptError(ErrNegativeLockTime, str) } sequence := int64(stackSequence) // To provide for future soft-fork extensibility, if the // operand has the disabled lock-time flag set, // CHECKSEQUENCEVERIFY behaves as a NOP. if sequence&int64(wire.SequenceLockTimeDisabled) != 0 { return nil } // Transaction version numbers not high enough to trigger CSV rules must // fail. if vm.tx.Version < 2 { str := fmt.Sprintf("invalid transaction version: %d", vm.tx.Version) return scriptError(ErrUnsatisfiedLockTime, str) } // Sequence numbers with their most significant bit set are not // consensus constrained. Testing that the transaction's sequence // number does not have this bit set prevents using this property // to get around a CHECKSEQUENCEVERIFY check. txSequence := int64(vm.tx.TxIn[vm.txIdx].Sequence) if txSequence&int64(wire.SequenceLockTimeDisabled) != 0 { str := fmt.Sprintf("transaction sequence has sequence "+ "locktime disabled bit set: 0x%x", txSequence) return scriptError(ErrUnsatisfiedLockTime, str) } // Mask off non-consensus bits before doing comparisons. lockTimeMask := int64(wire.SequenceLockTimeIsSeconds | wire.SequenceLockTimeMask) return verifyLockTime(txSequence&lockTimeMask, wire.SequenceLockTimeIsSeconds, sequence&lockTimeMask) }
[ "func", "opcodeCheckSequenceVerify", "(", "op", "*", "parsedOpcode", ",", "vm", "*", "Engine", ")", "error", "{", "// If the ScriptVerifyCheckSequenceVerify script flag is not set, treat", "// opcode as OP_NOP3 instead.", "if", "!", "vm", ".", "hasFlag", "(", "ScriptVerifyC...
// opcodeCheckSequenceVerify compares the top item on the data stack to the // LockTime field of the transaction containing the script signature // validating if the transaction outputs are spendable yet. If flag // ScriptVerifyCheckSequenceVerify is not set, the code continues as if OP_NOP3 // were executed.
[ "opcodeCheckSequenceVerify", "compares", "the", "top", "item", "on", "the", "data", "stack", "to", "the", "LockTime", "field", "of", "the", "transaction", "containing", "the", "script", "signature", "validating", "if", "the", "transaction", "outputs", "are", "spen...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/opcode.go#L1201-L1271
162,436
btcsuite/btcd
txscript/opcode.go
calcHash
func calcHash(buf []byte, hasher hash.Hash) []byte { hasher.Write(buf) return hasher.Sum(nil) }
go
func calcHash(buf []byte, hasher hash.Hash) []byte { hasher.Write(buf) return hasher.Sum(nil) }
[ "func", "calcHash", "(", "buf", "[", "]", "byte", ",", "hasher", "hash", ".", "Hash", ")", "[", "]", "byte", "{", "hasher", ".", "Write", "(", "buf", ")", "\n", "return", "hasher", ".", "Sum", "(", "nil", ")", "\n", "}" ]
// calcHash calculates the hash of hasher over buf.
[ "calcHash", "calculates", "the", "hash", "of", "hasher", "over", "buf", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/opcode.go#L1944-L1947
162,437
btcsuite/btcd
txscript/opcode.go
opcodeCodeSeparator
func opcodeCodeSeparator(op *parsedOpcode, vm *Engine) error { vm.lastCodeSep = vm.scriptOff return nil }
go
func opcodeCodeSeparator(op *parsedOpcode, vm *Engine) error { vm.lastCodeSep = vm.scriptOff return nil }
[ "func", "opcodeCodeSeparator", "(", "op", "*", "parsedOpcode", ",", "vm", "*", "Engine", ")", "error", "{", "vm", ".", "lastCodeSep", "=", "vm", ".", "scriptOff", "\n", "return", "nil", "\n", "}" ]
// opcodeCodeSeparator stores the current script offset as the most recently // seen OP_CODESEPARATOR which is used during signature checking. // // This opcode does not change the contents of the data stack.
[ "opcodeCodeSeparator", "stores", "the", "current", "script", "offset", "as", "the", "most", "recently", "seen", "OP_CODESEPARATOR", "which", "is", "used", "during", "signature", "checking", ".", "This", "opcode", "does", "not", "change", "the", "contents", "of", ...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/opcode.go#L2026-L2029
162,438
btcsuite/btcd
blockchain/difficulty.go
HashToBig
func HashToBig(hash *chainhash.Hash) *big.Int { // A Hash is in little-endian, but the big package wants the bytes in // big-endian, so reverse them. buf := *hash blen := len(buf) for i := 0; i < blen/2; i++ { buf[i], buf[blen-1-i] = buf[blen-1-i], buf[i] } return new(big.Int).SetBytes(buf[:]) }
go
func HashToBig(hash *chainhash.Hash) *big.Int { // A Hash is in little-endian, but the big package wants the bytes in // big-endian, so reverse them. buf := *hash blen := len(buf) for i := 0; i < blen/2; i++ { buf[i], buf[blen-1-i] = buf[blen-1-i], buf[i] } return new(big.Int).SetBytes(buf[:]) }
[ "func", "HashToBig", "(", "hash", "*", "chainhash", ".", "Hash", ")", "*", "big", ".", "Int", "{", "// A Hash is in little-endian, but the big package wants the bytes in", "// big-endian, so reverse them.", "buf", ":=", "*", "hash", "\n", "blen", ":=", "len", "(", "...
// HashToBig converts a chainhash.Hash into a big.Int that can be used to // perform math comparisons.
[ "HashToBig", "converts", "a", "chainhash", ".", "Hash", "into", "a", "big", ".", "Int", "that", "can", "be", "used", "to", "perform", "math", "comparisons", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/difficulty.go#L26-L36
162,439
btcsuite/btcd
blockchain/difficulty.go
calcEasiestDifficulty
func (b *BlockChain) calcEasiestDifficulty(bits uint32, duration time.Duration) uint32 { // Convert types used in the calculations below. durationVal := int64(duration / time.Second) adjustmentFactor := big.NewInt(b.chainParams.RetargetAdjustmentFactor) // The test network rules allow minimum difficulty blocks after more // than twice the desired amount of time needed to generate a block has // elapsed. if b.chainParams.ReduceMinDifficulty { reductionTime := int64(b.chainParams.MinDiffReductionTime / time.Second) if durationVal > reductionTime { return b.chainParams.PowLimitBits } } // Since easier difficulty equates to higher numbers, the easiest // difficulty for a given duration is the largest value possible given // the number of retargets for the duration and starting difficulty // multiplied by the max adjustment factor. newTarget := CompactToBig(bits) for durationVal > 0 && newTarget.Cmp(b.chainParams.PowLimit) < 0 { newTarget.Mul(newTarget, adjustmentFactor) durationVal -= b.maxRetargetTimespan } // Limit new value to the proof of work limit. if newTarget.Cmp(b.chainParams.PowLimit) > 0 { newTarget.Set(b.chainParams.PowLimit) } return BigToCompact(newTarget) }
go
func (b *BlockChain) calcEasiestDifficulty(bits uint32, duration time.Duration) uint32 { // Convert types used in the calculations below. durationVal := int64(duration / time.Second) adjustmentFactor := big.NewInt(b.chainParams.RetargetAdjustmentFactor) // The test network rules allow minimum difficulty blocks after more // than twice the desired amount of time needed to generate a block has // elapsed. if b.chainParams.ReduceMinDifficulty { reductionTime := int64(b.chainParams.MinDiffReductionTime / time.Second) if durationVal > reductionTime { return b.chainParams.PowLimitBits } } // Since easier difficulty equates to higher numbers, the easiest // difficulty for a given duration is the largest value possible given // the number of retargets for the duration and starting difficulty // multiplied by the max adjustment factor. newTarget := CompactToBig(bits) for durationVal > 0 && newTarget.Cmp(b.chainParams.PowLimit) < 0 { newTarget.Mul(newTarget, adjustmentFactor) durationVal -= b.maxRetargetTimespan } // Limit new value to the proof of work limit. if newTarget.Cmp(b.chainParams.PowLimit) > 0 { newTarget.Set(b.chainParams.PowLimit) } return BigToCompact(newTarget) }
[ "func", "(", "b", "*", "BlockChain", ")", "calcEasiestDifficulty", "(", "bits", "uint32", ",", "duration", "time", ".", "Duration", ")", "uint32", "{", "// Convert types used in the calculations below.", "durationVal", ":=", "int64", "(", "duration", "/", "time", ...
// calcEasiestDifficulty calculates the easiest possible difficulty that a block // can have given starting difficulty bits and a duration. It is mainly used to // verify that claimed proof of work by a block is sane as compared to a // known good checkpoint.
[ "calcEasiestDifficulty", "calculates", "the", "easiest", "possible", "difficulty", "that", "a", "block", "can", "have", "given", "starting", "difficulty", "bits", "and", "a", "duration", ".", "It", "is", "mainly", "used", "to", "verify", "that", "claimed", "proo...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/difficulty.go#L159-L191
162,440
btcsuite/btcd
blockchain/difficulty.go
calcNextRequiredDifficulty
func (b *BlockChain) calcNextRequiredDifficulty(lastNode *blockNode, newBlockTime time.Time) (uint32, error) { // Genesis block. if lastNode == nil { return b.chainParams.PowLimitBits, nil } // Return the previous block's difficulty requirements if this block // is not at a difficulty retarget interval. if (lastNode.height+1)%b.blocksPerRetarget != 0 { // For networks that support it, allow special reduction of the // required difficulty once too much time has elapsed without // mining a block. if b.chainParams.ReduceMinDifficulty { // Return minimum difficulty when more than the desired // amount of time has elapsed without mining a block. reductionTime := int64(b.chainParams.MinDiffReductionTime / time.Second) allowMinTime := lastNode.timestamp + reductionTime if newBlockTime.Unix() > allowMinTime { return b.chainParams.PowLimitBits, nil } // The block was mined within the desired timeframe, so // return the difficulty for the last block which did // not have the special minimum difficulty rule applied. return b.findPrevTestNetDifficulty(lastNode), nil } // For the main network (or any unrecognized networks), simply // return the previous block's difficulty requirements. return lastNode.bits, nil } // Get the block node at the previous retarget (targetTimespan days // worth of blocks). firstNode := lastNode.RelativeAncestor(b.blocksPerRetarget - 1) if firstNode == nil { return 0, AssertError("unable to obtain previous retarget block") } // Limit the amount of adjustment that can occur to the previous // difficulty. actualTimespan := lastNode.timestamp - firstNode.timestamp adjustedTimespan := actualTimespan if actualTimespan < b.minRetargetTimespan { adjustedTimespan = b.minRetargetTimespan } else if actualTimespan > b.maxRetargetTimespan { adjustedTimespan = b.maxRetargetTimespan } // Calculate new target difficulty as: // currentDifficulty * (adjustedTimespan / targetTimespan) // The result uses integer division which means it will be slightly // rounded down. Bitcoind also uses integer division to calculate this // result. oldTarget := CompactToBig(lastNode.bits) newTarget := new(big.Int).Mul(oldTarget, big.NewInt(adjustedTimespan)) targetTimeSpan := int64(b.chainParams.TargetTimespan / time.Second) newTarget.Div(newTarget, big.NewInt(targetTimeSpan)) // Limit new value to the proof of work limit. if newTarget.Cmp(b.chainParams.PowLimit) > 0 { newTarget.Set(b.chainParams.PowLimit) } // Log new target difficulty and return it. The new target logging is // intentionally converting the bits back to a number instead of using // newTarget since conversion to the compact representation loses // precision. newTargetBits := BigToCompact(newTarget) log.Debugf("Difficulty retarget at block height %d", lastNode.height+1) log.Debugf("Old target %08x (%064x)", lastNode.bits, oldTarget) log.Debugf("New target %08x (%064x)", newTargetBits, CompactToBig(newTargetBits)) log.Debugf("Actual timespan %v, adjusted timespan %v, target timespan %v", time.Duration(actualTimespan)*time.Second, time.Duration(adjustedTimespan)*time.Second, b.chainParams.TargetTimespan) return newTargetBits, nil }
go
func (b *BlockChain) calcNextRequiredDifficulty(lastNode *blockNode, newBlockTime time.Time) (uint32, error) { // Genesis block. if lastNode == nil { return b.chainParams.PowLimitBits, nil } // Return the previous block's difficulty requirements if this block // is not at a difficulty retarget interval. if (lastNode.height+1)%b.blocksPerRetarget != 0 { // For networks that support it, allow special reduction of the // required difficulty once too much time has elapsed without // mining a block. if b.chainParams.ReduceMinDifficulty { // Return minimum difficulty when more than the desired // amount of time has elapsed without mining a block. reductionTime := int64(b.chainParams.MinDiffReductionTime / time.Second) allowMinTime := lastNode.timestamp + reductionTime if newBlockTime.Unix() > allowMinTime { return b.chainParams.PowLimitBits, nil } // The block was mined within the desired timeframe, so // return the difficulty for the last block which did // not have the special minimum difficulty rule applied. return b.findPrevTestNetDifficulty(lastNode), nil } // For the main network (or any unrecognized networks), simply // return the previous block's difficulty requirements. return lastNode.bits, nil } // Get the block node at the previous retarget (targetTimespan days // worth of blocks). firstNode := lastNode.RelativeAncestor(b.blocksPerRetarget - 1) if firstNode == nil { return 0, AssertError("unable to obtain previous retarget block") } // Limit the amount of adjustment that can occur to the previous // difficulty. actualTimespan := lastNode.timestamp - firstNode.timestamp adjustedTimespan := actualTimespan if actualTimespan < b.minRetargetTimespan { adjustedTimespan = b.minRetargetTimespan } else if actualTimespan > b.maxRetargetTimespan { adjustedTimespan = b.maxRetargetTimespan } // Calculate new target difficulty as: // currentDifficulty * (adjustedTimespan / targetTimespan) // The result uses integer division which means it will be slightly // rounded down. Bitcoind also uses integer division to calculate this // result. oldTarget := CompactToBig(lastNode.bits) newTarget := new(big.Int).Mul(oldTarget, big.NewInt(adjustedTimespan)) targetTimeSpan := int64(b.chainParams.TargetTimespan / time.Second) newTarget.Div(newTarget, big.NewInt(targetTimeSpan)) // Limit new value to the proof of work limit. if newTarget.Cmp(b.chainParams.PowLimit) > 0 { newTarget.Set(b.chainParams.PowLimit) } // Log new target difficulty and return it. The new target logging is // intentionally converting the bits back to a number instead of using // newTarget since conversion to the compact representation loses // precision. newTargetBits := BigToCompact(newTarget) log.Debugf("Difficulty retarget at block height %d", lastNode.height+1) log.Debugf("Old target %08x (%064x)", lastNode.bits, oldTarget) log.Debugf("New target %08x (%064x)", newTargetBits, CompactToBig(newTargetBits)) log.Debugf("Actual timespan %v, adjusted timespan %v, target timespan %v", time.Duration(actualTimespan)*time.Second, time.Duration(adjustedTimespan)*time.Second, b.chainParams.TargetTimespan) return newTargetBits, nil }
[ "func", "(", "b", "*", "BlockChain", ")", "calcNextRequiredDifficulty", "(", "lastNode", "*", "blockNode", ",", "newBlockTime", "time", ".", "Time", ")", "(", "uint32", ",", "error", ")", "{", "// Genesis block.", "if", "lastNode", "==", "nil", "{", "return"...
// calcNextRequiredDifficulty calculates the required difficulty for the block // after the passed previous block node based on the difficulty retarget rules. // This function differs from the exported CalcNextRequiredDifficulty in that // the exported version uses the current best chain as the previous block node // while this function accepts any block node.
[ "calcNextRequiredDifficulty", "calculates", "the", "required", "difficulty", "for", "the", "block", "after", "the", "passed", "previous", "block", "node", "based", "on", "the", "difficulty", "retarget", "rules", ".", "This", "function", "differs", "from", "the", "...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/difficulty.go#L221-L300
162,441
btcsuite/btcd
blockchain/difficulty.go
CalcNextRequiredDifficulty
func (b *BlockChain) CalcNextRequiredDifficulty(timestamp time.Time) (uint32, error) { b.chainLock.Lock() difficulty, err := b.calcNextRequiredDifficulty(b.bestChain.Tip(), timestamp) b.chainLock.Unlock() return difficulty, err }
go
func (b *BlockChain) CalcNextRequiredDifficulty(timestamp time.Time) (uint32, error) { b.chainLock.Lock() difficulty, err := b.calcNextRequiredDifficulty(b.bestChain.Tip(), timestamp) b.chainLock.Unlock() return difficulty, err }
[ "func", "(", "b", "*", "BlockChain", ")", "CalcNextRequiredDifficulty", "(", "timestamp", "time", ".", "Time", ")", "(", "uint32", ",", "error", ")", "{", "b", ".", "chainLock", ".", "Lock", "(", ")", "\n", "difficulty", ",", "err", ":=", "b", ".", "...
// CalcNextRequiredDifficulty calculates the required difficulty for the block // after the end of the current best chain based on the difficulty retarget // rules. // // This function is safe for concurrent access.
[ "CalcNextRequiredDifficulty", "calculates", "the", "required", "difficulty", "for", "the", "block", "after", "the", "end", "of", "the", "current", "best", "chain", "based", "on", "the", "difficulty", "retarget", "rules", ".", "This", "function", "is", "safe", "f...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/difficulty.go#L307-L312
162,442
btcsuite/btcd
cmd/findcheckpoint/findcheckpoint.go
findCandidates
func findCandidates(chain *blockchain.BlockChain, latestHash *chainhash.Hash) ([]*chaincfg.Checkpoint, error) { // Start with the latest block of the main chain. block, err := chain.BlockByHash(latestHash) if err != nil { return nil, err } // Get the latest known checkpoint. latestCheckpoint := chain.LatestCheckpoint() if latestCheckpoint == nil { // Set the latest checkpoint to the genesis block if there isn't // already one. latestCheckpoint = &chaincfg.Checkpoint{ Hash: activeNetParams.GenesisHash, Height: 0, } } // The latest known block must be at least the last known checkpoint // plus required checkpoint confirmations. checkpointConfirmations := int32(blockchain.CheckpointConfirmations) requiredHeight := latestCheckpoint.Height + checkpointConfirmations if block.Height() < requiredHeight { return nil, fmt.Errorf("the block database is only at height "+ "%d which is less than the latest checkpoint height "+ "of %d plus required confirmations of %d", block.Height(), latestCheckpoint.Height, checkpointConfirmations) } // For the first checkpoint, the required height is any block after the // genesis block, so long as the chain has at least the required number // of confirmations (which is enforced above). if len(activeNetParams.Checkpoints) == 0 { requiredHeight = 1 } // Indeterminate progress setup. numBlocksToTest := block.Height() - requiredHeight progressInterval := (numBlocksToTest / 100) + 1 // min 1 fmt.Print("Searching for candidates") defer fmt.Println() // Loop backwards through the chain to find checkpoint candidates. candidates := make([]*chaincfg.Checkpoint, 0, cfg.NumCandidates) numTested := int32(0) for len(candidates) < cfg.NumCandidates && block.Height() > requiredHeight { // Display progress. if numTested%progressInterval == 0 { fmt.Print(".") } // Determine if this block is a checkpoint candidate. isCandidate, err := chain.IsCheckpointCandidate(block) if err != nil { return nil, err } // All checks passed, so this node seems like a reasonable // checkpoint candidate. if isCandidate { checkpoint := chaincfg.Checkpoint{ Height: block.Height(), Hash: block.Hash(), } candidates = append(candidates, &checkpoint) } prevHash := &block.MsgBlock().Header.PrevBlock block, err = chain.BlockByHash(prevHash) if err != nil { return nil, err } numTested++ } return candidates, nil }
go
func findCandidates(chain *blockchain.BlockChain, latestHash *chainhash.Hash) ([]*chaincfg.Checkpoint, error) { // Start with the latest block of the main chain. block, err := chain.BlockByHash(latestHash) if err != nil { return nil, err } // Get the latest known checkpoint. latestCheckpoint := chain.LatestCheckpoint() if latestCheckpoint == nil { // Set the latest checkpoint to the genesis block if there isn't // already one. latestCheckpoint = &chaincfg.Checkpoint{ Hash: activeNetParams.GenesisHash, Height: 0, } } // The latest known block must be at least the last known checkpoint // plus required checkpoint confirmations. checkpointConfirmations := int32(blockchain.CheckpointConfirmations) requiredHeight := latestCheckpoint.Height + checkpointConfirmations if block.Height() < requiredHeight { return nil, fmt.Errorf("the block database is only at height "+ "%d which is less than the latest checkpoint height "+ "of %d plus required confirmations of %d", block.Height(), latestCheckpoint.Height, checkpointConfirmations) } // For the first checkpoint, the required height is any block after the // genesis block, so long as the chain has at least the required number // of confirmations (which is enforced above). if len(activeNetParams.Checkpoints) == 0 { requiredHeight = 1 } // Indeterminate progress setup. numBlocksToTest := block.Height() - requiredHeight progressInterval := (numBlocksToTest / 100) + 1 // min 1 fmt.Print("Searching for candidates") defer fmt.Println() // Loop backwards through the chain to find checkpoint candidates. candidates := make([]*chaincfg.Checkpoint, 0, cfg.NumCandidates) numTested := int32(0) for len(candidates) < cfg.NumCandidates && block.Height() > requiredHeight { // Display progress. if numTested%progressInterval == 0 { fmt.Print(".") } // Determine if this block is a checkpoint candidate. isCandidate, err := chain.IsCheckpointCandidate(block) if err != nil { return nil, err } // All checks passed, so this node seems like a reasonable // checkpoint candidate. if isCandidate { checkpoint := chaincfg.Checkpoint{ Height: block.Height(), Hash: block.Hash(), } candidates = append(candidates, &checkpoint) } prevHash := &block.MsgBlock().Header.PrevBlock block, err = chain.BlockByHash(prevHash) if err != nil { return nil, err } numTested++ } return candidates, nil }
[ "func", "findCandidates", "(", "chain", "*", "blockchain", ".", "BlockChain", ",", "latestHash", "*", "chainhash", ".", "Hash", ")", "(", "[", "]", "*", "chaincfg", ".", "Checkpoint", ",", "error", ")", "{", "// Start with the latest block of the main chain.", "...
// findCandidates searches the chain backwards for checkpoint candidates and // returns a slice of found candidates, if any. It also stops searching for // candidates at the last checkpoint that is already hard coded into btcchain // since there is no point in finding candidates before already existing // checkpoints.
[ "findCandidates", "searches", "the", "chain", "backwards", "for", "checkpoint", "candidates", "and", "returns", "a", "slice", "of", "found", "candidates", "if", "any", ".", "It", "also", "stops", "searching", "for", "candidates", "at", "the", "last", "checkpoint...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/cmd/findcheckpoint/findcheckpoint.go#L42-L118
162,443
btcsuite/btcd
cmd/findcheckpoint/findcheckpoint.go
showCandidate
func showCandidate(candidateNum int, checkpoint *chaincfg.Checkpoint) { if cfg.UseGoOutput { fmt.Printf("Candidate %d -- {%d, newShaHashFromStr(\"%v\")},\n", candidateNum, checkpoint.Height, checkpoint.Hash) return } fmt.Printf("Candidate %d -- Height: %d, Hash: %v\n", candidateNum, checkpoint.Height, checkpoint.Hash) }
go
func showCandidate(candidateNum int, checkpoint *chaincfg.Checkpoint) { if cfg.UseGoOutput { fmt.Printf("Candidate %d -- {%d, newShaHashFromStr(\"%v\")},\n", candidateNum, checkpoint.Height, checkpoint.Hash) return } fmt.Printf("Candidate %d -- Height: %d, Hash: %v\n", candidateNum, checkpoint.Height, checkpoint.Hash) }
[ "func", "showCandidate", "(", "candidateNum", "int", ",", "checkpoint", "*", "chaincfg", ".", "Checkpoint", ")", "{", "if", "cfg", ".", "UseGoOutput", "{", "fmt", ".", "Printf", "(", "\"", "\\\"", "\\\"", "\\n", "\"", ",", "candidateNum", ",", "checkpoint"...
// showCandidate display a checkpoint candidate using and output format // determined by the configuration parameters. The Go syntax output // uses the format the btcchain code expects for checkpoints added to the list.
[ "showCandidate", "display", "a", "checkpoint", "candidate", "using", "and", "output", "format", "determined", "by", "the", "configuration", "parameters", ".", "The", "Go", "syntax", "output", "uses", "the", "format", "the", "btcchain", "code", "expects", "for", ...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/cmd/findcheckpoint/findcheckpoint.go#L123-L133
162,444
btcsuite/btcd
blockchain/versionbits.go
Condition
func (c deploymentChecker) Condition(node *blockNode) (bool, error) { conditionMask := uint32(1) << c.deployment.BitNumber version := uint32(node.version) return (version&vbTopMask == vbTopBits) && (version&conditionMask != 0), nil }
go
func (c deploymentChecker) Condition(node *blockNode) (bool, error) { conditionMask := uint32(1) << c.deployment.BitNumber version := uint32(node.version) return (version&vbTopMask == vbTopBits) && (version&conditionMask != 0), nil }
[ "func", "(", "c", "deploymentChecker", ")", "Condition", "(", "node", "*", "blockNode", ")", "(", "bool", ",", "error", ")", "{", "conditionMask", ":=", "uint32", "(", "1", ")", "<<", "c", ".", "deployment", ".", "BitNumber", "\n", "version", ":=", "ui...
// Condition returns true when the specific bit defined by the deployment // associated with the checker is set. // // This is part of the thresholdConditionChecker interface implementation.
[ "Condition", "returns", "true", "when", "the", "specific", "bit", "defined", "by", "the", "deployment", "associated", "with", "the", "checker", "is", "set", ".", "This", "is", "part", "of", "the", "thresholdConditionChecker", "interface", "implementation", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/versionbits.go#L184-L189
162,445
btcsuite/btcd
blockchain/versionbits.go
CalcNextBlockVersion
func (b *BlockChain) CalcNextBlockVersion() (int32, error) { b.chainLock.Lock() version, err := b.calcNextBlockVersion(b.bestChain.Tip()) b.chainLock.Unlock() return version, err }
go
func (b *BlockChain) CalcNextBlockVersion() (int32, error) { b.chainLock.Lock() version, err := b.calcNextBlockVersion(b.bestChain.Tip()) b.chainLock.Unlock() return version, err }
[ "func", "(", "b", "*", "BlockChain", ")", "CalcNextBlockVersion", "(", ")", "(", "int32", ",", "error", ")", "{", "b", ".", "chainLock", ".", "Lock", "(", ")", "\n", "version", ",", "err", ":=", "b", ".", "calcNextBlockVersion", "(", "b", ".", "bestC...
// CalcNextBlockVersion calculates the expected version of the block after the // end of the current best chain based on the state of started and locked in // rule change deployments. // // This function is safe for concurrent access.
[ "CalcNextBlockVersion", "calculates", "the", "expected", "version", "of", "the", "block", "after", "the", "end", "of", "the", "current", "best", "chain", "based", "on", "the", "state", "of", "started", "and", "locked", "in", "rule", "change", "deployments", "....
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/versionbits.go#L225-L230
162,446
btcsuite/btcd
wire/msgfilterload.go
NewMsgFilterLoad
func NewMsgFilterLoad(filter []byte, hashFuncs uint32, tweak uint32, flags BloomUpdateType) *MsgFilterLoad { return &MsgFilterLoad{ Filter: filter, HashFuncs: hashFuncs, Tweak: tweak, Flags: flags, } }
go
func NewMsgFilterLoad(filter []byte, hashFuncs uint32, tweak uint32, flags BloomUpdateType) *MsgFilterLoad { return &MsgFilterLoad{ Filter: filter, HashFuncs: hashFuncs, Tweak: tweak, Flags: flags, } }
[ "func", "NewMsgFilterLoad", "(", "filter", "[", "]", "byte", ",", "hashFuncs", "uint32", ",", "tweak", "uint32", ",", "flags", "BloomUpdateType", ")", "*", "MsgFilterLoad", "{", "return", "&", "MsgFilterLoad", "{", "Filter", ":", "filter", ",", "HashFuncs", ...
// NewMsgFilterLoad returns a new bitcoin filterload message that conforms to // the Message interface. See MsgFilterLoad for details.
[ "NewMsgFilterLoad", "returns", "a", "new", "bitcoin", "filterload", "message", "that", "conforms", "to", "the", "Message", "interface", ".", "See", "MsgFilterLoad", "for", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgfilterload.go#L129-L136
162,447
btcsuite/btcd
btcjson/cmdparse.go
makeParams
func makeParams(rt reflect.Type, rv reflect.Value) []interface{} { numFields := rt.NumField() params := make([]interface{}, 0, numFields) for i := 0; i < numFields; i++ { rtf := rt.Field(i) rvf := rv.Field(i) if rtf.Type.Kind() == reflect.Ptr { if rvf.IsNil() { break } rvf.Elem() } params = append(params, rvf.Interface()) } return params }
go
func makeParams(rt reflect.Type, rv reflect.Value) []interface{} { numFields := rt.NumField() params := make([]interface{}, 0, numFields) for i := 0; i < numFields; i++ { rtf := rt.Field(i) rvf := rv.Field(i) if rtf.Type.Kind() == reflect.Ptr { if rvf.IsNil() { break } rvf.Elem() } params = append(params, rvf.Interface()) } return params }
[ "func", "makeParams", "(", "rt", "reflect", ".", "Type", ",", "rv", "reflect", ".", "Value", ")", "[", "]", "interface", "{", "}", "{", "numFields", ":=", "rt", ".", "NumField", "(", ")", "\n", "params", ":=", "make", "(", "[", "]", "interface", "{...
// makeParams creates a slice of interface values for the given struct.
[ "makeParams", "creates", "a", "slice", "of", "interface", "values", "for", "the", "given", "struct", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/cmdparse.go#L16-L32
162,448
btcsuite/btcd
btcjson/cmdparse.go
MarshalCmd
func MarshalCmd(id interface{}, cmd interface{}) ([]byte, error) { // Look up the cmd type and error out if not registered. rt := reflect.TypeOf(cmd) registerLock.RLock() method, ok := concreteTypeToMethod[rt] registerLock.RUnlock() if !ok { str := fmt.Sprintf("%q is not registered", method) return nil, makeError(ErrUnregisteredMethod, str) } // The provided command must not be nil. rv := reflect.ValueOf(cmd) if rv.IsNil() { str := "the specified command is nil" return nil, makeError(ErrInvalidType, str) } // Create a slice of interface values in the order of the struct fields // while respecting pointer fields as optional params and only adding // them if they are non-nil. params := makeParams(rt.Elem(), rv.Elem()) // Generate and marshal the final JSON-RPC request. rawCmd, err := NewRequest(id, method, params) if err != nil { return nil, err } return json.Marshal(rawCmd) }
go
func MarshalCmd(id interface{}, cmd interface{}) ([]byte, error) { // Look up the cmd type and error out if not registered. rt := reflect.TypeOf(cmd) registerLock.RLock() method, ok := concreteTypeToMethod[rt] registerLock.RUnlock() if !ok { str := fmt.Sprintf("%q is not registered", method) return nil, makeError(ErrUnregisteredMethod, str) } // The provided command must not be nil. rv := reflect.ValueOf(cmd) if rv.IsNil() { str := "the specified command is nil" return nil, makeError(ErrInvalidType, str) } // Create a slice of interface values in the order of the struct fields // while respecting pointer fields as optional params and only adding // them if they are non-nil. params := makeParams(rt.Elem(), rv.Elem()) // Generate and marshal the final JSON-RPC request. rawCmd, err := NewRequest(id, method, params) if err != nil { return nil, err } return json.Marshal(rawCmd) }
[ "func", "MarshalCmd", "(", "id", "interface", "{", "}", ",", "cmd", "interface", "{", "}", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// Look up the cmd type and error out if not registered.", "rt", ":=", "reflect", ".", "TypeOf", "(", "cmd", ")", ...
// MarshalCmd marshals the passed command to a JSON-RPC request byte slice that // is suitable for transmission to an RPC server. The provided command type // must be a registered type. All commands provided by this package are // registered by default.
[ "MarshalCmd", "marshals", "the", "passed", "command", "to", "a", "JSON", "-", "RPC", "request", "byte", "slice", "that", "is", "suitable", "for", "transmission", "to", "an", "RPC", "server", ".", "The", "provided", "command", "type", "must", "be", "a", "re...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/cmdparse.go#L38-L67
162,449
btcsuite/btcd
btcjson/cmdparse.go
checkNumParams
func checkNumParams(numParams int, info *methodInfo) error { if numParams < info.numReqParams || numParams > info.maxParams { if info.numReqParams == info.maxParams { str := fmt.Sprintf("wrong number of params (expected "+ "%d, received %d)", info.numReqParams, numParams) return makeError(ErrNumParams, str) } str := fmt.Sprintf("wrong number of params (expected "+ "between %d and %d, received %d)", info.numReqParams, info.maxParams, numParams) return makeError(ErrNumParams, str) } return nil }
go
func checkNumParams(numParams int, info *methodInfo) error { if numParams < info.numReqParams || numParams > info.maxParams { if info.numReqParams == info.maxParams { str := fmt.Sprintf("wrong number of params (expected "+ "%d, received %d)", info.numReqParams, numParams) return makeError(ErrNumParams, str) } str := fmt.Sprintf("wrong number of params (expected "+ "between %d and %d, received %d)", info.numReqParams, info.maxParams, numParams) return makeError(ErrNumParams, str) } return nil }
[ "func", "checkNumParams", "(", "numParams", "int", ",", "info", "*", "methodInfo", ")", "error", "{", "if", "numParams", "<", "info", ".", "numReqParams", "||", "numParams", ">", "info", ".", "maxParams", "{", "if", "info", ".", "numReqParams", "==", "info...
// checkNumParams ensures the supplied number of params is at least the minimum // required number for the command and less than the maximum allowed.
[ "checkNumParams", "ensures", "the", "supplied", "number", "of", "params", "is", "at", "least", "the", "minimum", "required", "number", "for", "the", "command", "and", "less", "than", "the", "maximum", "allowed", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/cmdparse.go#L71-L87
162,450
btcsuite/btcd
btcjson/cmdparse.go
populateDefaults
func populateDefaults(numParams int, info *methodInfo, rv reflect.Value) { // When there are no more parameters left in the supplied parameters, // any remaining struct fields must be optional. Thus, populate them // with their associated default value as needed. for i := numParams; i < info.maxParams; i++ { rvf := rv.Field(i) if defaultVal, ok := info.defaults[i]; ok { rvf.Set(defaultVal) } } }
go
func populateDefaults(numParams int, info *methodInfo, rv reflect.Value) { // When there are no more parameters left in the supplied parameters, // any remaining struct fields must be optional. Thus, populate them // with their associated default value as needed. for i := numParams; i < info.maxParams; i++ { rvf := rv.Field(i) if defaultVal, ok := info.defaults[i]; ok { rvf.Set(defaultVal) } } }
[ "func", "populateDefaults", "(", "numParams", "int", ",", "info", "*", "methodInfo", ",", "rv", "reflect", ".", "Value", ")", "{", "// When there are no more parameters left in the supplied parameters,", "// any remaining struct fields must be optional. Thus, populate them", "//...
// populateDefaults populates default values into any remaining optional struct // fields that did not have parameters explicitly provided. The caller should // have previously checked that the number of parameters being passed is at // least the required number of parameters to avoid unnecessary work in this // function, but since required fields never have default values, it will work // properly even without the check.
[ "populateDefaults", "populates", "default", "values", "into", "any", "remaining", "optional", "struct", "fields", "that", "did", "not", "have", "parameters", "explicitly", "provided", ".", "The", "caller", "should", "have", "previously", "checked", "that", "the", ...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/cmdparse.go#L95-L105
162,451
btcsuite/btcd
btcjson/cmdparse.go
UnmarshalCmd
func UnmarshalCmd(r *Request) (interface{}, error) { registerLock.RLock() rtp, ok := methodToConcreteType[r.Method] info := methodToInfo[r.Method] registerLock.RUnlock() if !ok { str := fmt.Sprintf("%q is not registered", r.Method) return nil, makeError(ErrUnregisteredMethod, str) } rt := rtp.Elem() rvp := reflect.New(rt) rv := rvp.Elem() // Ensure the number of parameters are correct. numParams := len(r.Params) if err := checkNumParams(numParams, &info); err != nil { return nil, err } // Loop through each of the struct fields and unmarshal the associated // parameter into them. for i := 0; i < numParams; i++ { rvf := rv.Field(i) // Unmarshal the parameter into the struct field. concreteVal := rvf.Addr().Interface() if err := json.Unmarshal(r.Params[i], &concreteVal); err != nil { // The most common error is the wrong type, so // explicitly detect that error and make it nicer. fieldName := strings.ToLower(rt.Field(i).Name) if jerr, ok := err.(*json.UnmarshalTypeError); ok { str := fmt.Sprintf("parameter #%d '%s' must "+ "be type %v (got %v)", i+1, fieldName, jerr.Type, jerr.Value) return nil, makeError(ErrInvalidType, str) } // Fallback to showing the underlying error. str := fmt.Sprintf("parameter #%d '%s' failed to "+ "unmarshal: %v", i+1, fieldName, err) return nil, makeError(ErrInvalidType, str) } } // When there are less supplied parameters than the total number of // params, any remaining struct fields must be optional. Thus, populate // them with their associated default value as needed. if numParams < info.maxParams { populateDefaults(numParams, &info, rv) } return rvp.Interface(), nil }
go
func UnmarshalCmd(r *Request) (interface{}, error) { registerLock.RLock() rtp, ok := methodToConcreteType[r.Method] info := methodToInfo[r.Method] registerLock.RUnlock() if !ok { str := fmt.Sprintf("%q is not registered", r.Method) return nil, makeError(ErrUnregisteredMethod, str) } rt := rtp.Elem() rvp := reflect.New(rt) rv := rvp.Elem() // Ensure the number of parameters are correct. numParams := len(r.Params) if err := checkNumParams(numParams, &info); err != nil { return nil, err } // Loop through each of the struct fields and unmarshal the associated // parameter into them. for i := 0; i < numParams; i++ { rvf := rv.Field(i) // Unmarshal the parameter into the struct field. concreteVal := rvf.Addr().Interface() if err := json.Unmarshal(r.Params[i], &concreteVal); err != nil { // The most common error is the wrong type, so // explicitly detect that error and make it nicer. fieldName := strings.ToLower(rt.Field(i).Name) if jerr, ok := err.(*json.UnmarshalTypeError); ok { str := fmt.Sprintf("parameter #%d '%s' must "+ "be type %v (got %v)", i+1, fieldName, jerr.Type, jerr.Value) return nil, makeError(ErrInvalidType, str) } // Fallback to showing the underlying error. str := fmt.Sprintf("parameter #%d '%s' failed to "+ "unmarshal: %v", i+1, fieldName, err) return nil, makeError(ErrInvalidType, str) } } // When there are less supplied parameters than the total number of // params, any remaining struct fields must be optional. Thus, populate // them with their associated default value as needed. if numParams < info.maxParams { populateDefaults(numParams, &info, rv) } return rvp.Interface(), nil }
[ "func", "UnmarshalCmd", "(", "r", "*", "Request", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "registerLock", ".", "RLock", "(", ")", "\n", "rtp", ",", "ok", ":=", "methodToConcreteType", "[", "r", ".", "Method", "]", "\n", "info", ":=",...
// UnmarshalCmd unmarshals a JSON-RPC request into a suitable concrete command // so long as the method type contained within the marshalled request is // registered.
[ "UnmarshalCmd", "unmarshals", "a", "JSON", "-", "RPC", "request", "into", "a", "suitable", "concrete", "command", "so", "long", "as", "the", "method", "type", "contained", "within", "the", "marshalled", "request", "is", "registered", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/cmdparse.go#L110-L161
162,452
btcsuite/btcd
btcjson/cmdparse.go
isNumeric
func isNumeric(kind reflect.Kind) bool { switch kind { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64: return true } return false }
go
func isNumeric(kind reflect.Kind) bool { switch kind { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64: return true } return false }
[ "func", "isNumeric", "(", "kind", "reflect", ".", "Kind", ")", "bool", "{", "switch", "kind", "{", "case", "reflect", ".", "Int", ",", "reflect", ".", "Int8", ",", "reflect", ".", "Int16", ",", "reflect", ".", "Int32", ",", "reflect", ".", "Int64", "...
// isNumeric returns whether the passed reflect kind is a signed or unsigned // integer of any magnitude or a float of any magnitude.
[ "isNumeric", "returns", "whether", "the", "passed", "reflect", "kind", "is", "a", "signed", "or", "unsigned", "integer", "of", "any", "magnitude", "or", "a", "float", "of", "any", "magnitude", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/cmdparse.go#L165-L175
162,453
btcsuite/btcd
btcjson/cmdparse.go
typesMaybeCompatible
func typesMaybeCompatible(dest reflect.Type, src reflect.Type) bool { // The same types are obviously compatible. if dest == src { return true } // When both types are numeric, they are potentially compatible. srcKind := src.Kind() destKind := dest.Kind() if isNumeric(destKind) && isNumeric(srcKind) { return true } if srcKind == reflect.String { // Strings can potentially be converted to numeric types. if isNumeric(destKind) { return true } switch destKind { // Strings can potentially be converted to bools by // strconv.ParseBool. case reflect.Bool: return true // Strings can be converted to any other type which has as // underlying type of string. case reflect.String: return true // Strings can potentially be converted to arrays, slice, // structs, and maps via json.Unmarshal. case reflect.Array, reflect.Slice, reflect.Struct, reflect.Map: return true } } return false }
go
func typesMaybeCompatible(dest reflect.Type, src reflect.Type) bool { // The same types are obviously compatible. if dest == src { return true } // When both types are numeric, they are potentially compatible. srcKind := src.Kind() destKind := dest.Kind() if isNumeric(destKind) && isNumeric(srcKind) { return true } if srcKind == reflect.String { // Strings can potentially be converted to numeric types. if isNumeric(destKind) { return true } switch destKind { // Strings can potentially be converted to bools by // strconv.ParseBool. case reflect.Bool: return true // Strings can be converted to any other type which has as // underlying type of string. case reflect.String: return true // Strings can potentially be converted to arrays, slice, // structs, and maps via json.Unmarshal. case reflect.Array, reflect.Slice, reflect.Struct, reflect.Map: return true } } return false }
[ "func", "typesMaybeCompatible", "(", "dest", "reflect", ".", "Type", ",", "src", "reflect", ".", "Type", ")", "bool", "{", "// The same types are obviously compatible.", "if", "dest", "==", "src", "{", "return", "true", "\n", "}", "\n\n", "// When both types are n...
// typesMaybeCompatible returns whether the source type can possibly be // assigned to the destination type. This is intended as a relatively quick // check to weed out obviously invalid conversions.
[ "typesMaybeCompatible", "returns", "whether", "the", "source", "type", "can", "possibly", "be", "assigned", "to", "the", "destination", "type", ".", "This", "is", "intended", "as", "a", "relatively", "quick", "check", "to", "weed", "out", "obviously", "invalid",...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/cmdparse.go#L180-L218
162,454
btcsuite/btcd
btcjson/cmdparse.go
baseType
func baseType(arg reflect.Type) (reflect.Type, int) { var numIndirects int for arg.Kind() == reflect.Ptr { arg = arg.Elem() numIndirects++ } return arg, numIndirects }
go
func baseType(arg reflect.Type) (reflect.Type, int) { var numIndirects int for arg.Kind() == reflect.Ptr { arg = arg.Elem() numIndirects++ } return arg, numIndirects }
[ "func", "baseType", "(", "arg", "reflect", ".", "Type", ")", "(", "reflect", ".", "Type", ",", "int", ")", "{", "var", "numIndirects", "int", "\n", "for", "arg", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "arg", "=", "arg", ".", "El...
// baseType returns the type of the argument after indirecting through all // pointers along with how many indirections were necessary.
[ "baseType", "returns", "the", "type", "of", "the", "argument", "after", "indirecting", "through", "all", "pointers", "along", "with", "how", "many", "indirections", "were", "necessary", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/cmdparse.go#L222-L229
162,455
btcsuite/btcd
btcjson/chainsvrwscmds.go
NewAuthenticateCmd
func NewAuthenticateCmd(username, passphrase string) *AuthenticateCmd { return &AuthenticateCmd{ Username: username, Passphrase: passphrase, } }
go
func NewAuthenticateCmd(username, passphrase string) *AuthenticateCmd { return &AuthenticateCmd{ Username: username, Passphrase: passphrase, } }
[ "func", "NewAuthenticateCmd", "(", "username", ",", "passphrase", "string", ")", "*", "AuthenticateCmd", "{", "return", "&", "AuthenticateCmd", "{", "Username", ":", "username", ",", "Passphrase", ":", "passphrase", ",", "}", "\n", "}" ]
// NewAuthenticateCmd returns a new instance which can be used to issue an // authenticate JSON-RPC command.
[ "NewAuthenticateCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "an", "authenticate", "JSON", "-", "RPC", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/chainsvrwscmds.go#L19-L24
162,456
btcsuite/btcd
wire/protocol.go
String
func (f ServiceFlag) String() string { // No flags are set. if f == 0 { return "0x0" } // Add individual bit flags. s := "" for _, flag := range orderedSFStrings { if f&flag == flag { s += sfStrings[flag] + "|" f -= flag } } // Add any remaining flags which aren't accounted for as hex. s = strings.TrimRight(s, "|") if f != 0 { s += "|0x" + strconv.FormatUint(uint64(f), 16) } s = strings.TrimLeft(s, "|") return s }
go
func (f ServiceFlag) String() string { // No flags are set. if f == 0 { return "0x0" } // Add individual bit flags. s := "" for _, flag := range orderedSFStrings { if f&flag == flag { s += sfStrings[flag] + "|" f -= flag } } // Add any remaining flags which aren't accounted for as hex. s = strings.TrimRight(s, "|") if f != 0 { s += "|0x" + strconv.FormatUint(uint64(f), 16) } s = strings.TrimLeft(s, "|") return s }
[ "func", "(", "f", "ServiceFlag", ")", "String", "(", ")", "string", "{", "// No flags are set.", "if", "f", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n\n", "// Add individual bit flags.", "s", ":=", "\"", "\"", "\n", "for", "_", ",", "flag", "...
// String returns the ServiceFlag in human-readable form.
[ "String", "returns", "the", "ServiceFlag", "in", "human", "-", "readable", "form", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/protocol.go#L117-L139
162,457
btcsuite/btcd
wire/protocol.go
String
func (n BitcoinNet) String() string { if s, ok := bnStrings[n]; ok { return s } return fmt.Sprintf("Unknown BitcoinNet (%d)", uint32(n)) }
go
func (n BitcoinNet) String() string { if s, ok := bnStrings[n]; ok { return s } return fmt.Sprintf("Unknown BitcoinNet (%d)", uint32(n)) }
[ "func", "(", "n", "BitcoinNet", ")", "String", "(", ")", "string", "{", "if", "s", ",", "ok", ":=", "bnStrings", "[", "n", "]", ";", "ok", "{", "return", "s", "\n", "}", "\n\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "uint32", "...
// String returns the BitcoinNet in human-readable form.
[ "String", "returns", "the", "BitcoinNet", "in", "human", "-", "readable", "form", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/protocol.go#L172-L178
162,458
btcsuite/btcd
addrmgr/network.go
ipNet
func ipNet(ip string, ones, bits int) net.IPNet { return net.IPNet{IP: net.ParseIP(ip), Mask: net.CIDRMask(ones, bits)} }
go
func ipNet(ip string, ones, bits int) net.IPNet { return net.IPNet{IP: net.ParseIP(ip), Mask: net.CIDRMask(ones, bits)} }
[ "func", "ipNet", "(", "ip", "string", ",", "ones", ",", "bits", "int", ")", "net", ".", "IPNet", "{", "return", "net", ".", "IPNet", "{", "IP", ":", "net", ".", "ParseIP", "(", "ip", ")", ",", "Mask", ":", "net", ".", "CIDRMask", "(", "ones", "...
// ipNet returns a net.IPNet struct given the passed IP address string, number // of one bits to include at the start of the mask, and the total number of bits // for the mask.
[ "ipNet", "returns", "a", "net", ".", "IPNet", "struct", "given", "the", "passed", "IP", "address", "string", "number", "of", "one", "bits", "to", "include", "at", "the", "start", "of", "the", "mask", "and", "the", "total", "number", "of", "bits", "for", ...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/network.go#L98-L100
162,459
btcsuite/btcd
addrmgr/network.go
IsLocal
func IsLocal(na *wire.NetAddress) bool { return na.IP.IsLoopback() || zero4Net.Contains(na.IP) }
go
func IsLocal(na *wire.NetAddress) bool { return na.IP.IsLoopback() || zero4Net.Contains(na.IP) }
[ "func", "IsLocal", "(", "na", "*", "wire", ".", "NetAddress", ")", "bool", "{", "return", "na", ".", "IP", ".", "IsLoopback", "(", ")", "||", "zero4Net", ".", "Contains", "(", "na", ".", "IP", ")", "\n", "}" ]
// IsLocal returns whether or not the given address is a local address.
[ "IsLocal", "returns", "whether", "or", "not", "the", "given", "address", "is", "a", "local", "address", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/network.go#L108-L110
162,460
btcsuite/btcd
addrmgr/network.go
IsRoutable
func IsRoutable(na *wire.NetAddress) bool { return IsValid(na) && !(IsRFC1918(na) || IsRFC2544(na) || IsRFC3927(na) || IsRFC4862(na) || IsRFC3849(na) || IsRFC4843(na) || IsRFC5737(na) || IsRFC6598(na) || IsLocal(na) || (IsRFC4193(na) && !IsOnionCatTor(na))) }
go
func IsRoutable(na *wire.NetAddress) bool { return IsValid(na) && !(IsRFC1918(na) || IsRFC2544(na) || IsRFC3927(na) || IsRFC4862(na) || IsRFC3849(na) || IsRFC4843(na) || IsRFC5737(na) || IsRFC6598(na) || IsLocal(na) || (IsRFC4193(na) && !IsOnionCatTor(na))) }
[ "func", "IsRoutable", "(", "na", "*", "wire", ".", "NetAddress", ")", "bool", "{", "return", "IsValid", "(", "na", ")", "&&", "!", "(", "IsRFC1918", "(", "na", ")", "||", "IsRFC2544", "(", "na", ")", "||", "IsRFC3927", "(", "na", ")", "||", "IsRFC4...
// IsRoutable returns whether or not the passed address is routable over // the public internet. This is true as long as the address is valid and is not // in any reserved ranges.
[ "IsRoutable", "returns", "whether", "or", "not", "the", "passed", "address", "is", "routable", "over", "the", "public", "internet", ".", "This", "is", "true", "as", "long", "as", "the", "address", "is", "valid", "and", "is", "not", "in", "any", "reserved",...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/addrmgr/network.go#L225-L230
162,461
btcsuite/btcd
wire/msggetdata.go
AddInvVect
func (msg *MsgGetData) AddInvVect(iv *InvVect) error { if len(msg.InvList)+1 > MaxInvPerMsg { str := fmt.Sprintf("too many invvect in message [max %v]", MaxInvPerMsg) return messageError("MsgGetData.AddInvVect", str) } msg.InvList = append(msg.InvList, iv) return nil }
go
func (msg *MsgGetData) AddInvVect(iv *InvVect) error { if len(msg.InvList)+1 > MaxInvPerMsg { str := fmt.Sprintf("too many invvect in message [max %v]", MaxInvPerMsg) return messageError("MsgGetData.AddInvVect", str) } msg.InvList = append(msg.InvList, iv) return nil }
[ "func", "(", "msg", "*", "MsgGetData", ")", "AddInvVect", "(", "iv", "*", "InvVect", ")", "error", "{", "if", "len", "(", "msg", ".", "InvList", ")", "+", "1", ">", "MaxInvPerMsg", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "M...
// AddInvVect adds an inventory vector to the message.
[ "AddInvVect", "adds", "an", "inventory", "vector", "to", "the", "message", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msggetdata.go#L27-L36
162,462
btcsuite/btcd
cmd/btcctl/btcctl.go
commandUsage
func commandUsage(method string) { usage, err := btcjson.MethodUsageText(method) if err != nil { // This should never happen since the method was already checked // before calling this function, but be safe. fmt.Fprintln(os.Stderr, "Failed to obtain command usage:", err) return } fmt.Fprintln(os.Stderr, "Usage:") fmt.Fprintf(os.Stderr, " %s\n", usage) }
go
func commandUsage(method string) { usage, err := btcjson.MethodUsageText(method) if err != nil { // This should never happen since the method was already checked // before calling this function, but be safe. fmt.Fprintln(os.Stderr, "Failed to obtain command usage:", err) return } fmt.Fprintln(os.Stderr, "Usage:") fmt.Fprintf(os.Stderr, " %s\n", usage) }
[ "func", "commandUsage", "(", "method", "string", ")", "{", "usage", ",", "err", ":=", "btcjson", ".", "MethodUsageText", "(", "method", ")", "\n", "if", "err", "!=", "nil", "{", "// This should never happen since the method was already checked", "// before calling thi...
// commandUsage display the usage for a specific command.
[ "commandUsage", "display", "the", "usage", "for", "a", "specific", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/cmd/btcctl/btcctl.go#L22-L33
162,463
btcsuite/btcd
cmd/btcctl/btcctl.go
usage
func usage(errorMessage string) { appName := filepath.Base(os.Args[0]) appName = strings.TrimSuffix(appName, filepath.Ext(appName)) fmt.Fprintln(os.Stderr, errorMessage) fmt.Fprintln(os.Stderr, "Usage:") fmt.Fprintf(os.Stderr, " %s [OPTIONS] <command> <args...>\n\n", appName) fmt.Fprintln(os.Stderr, showHelpMessage) fmt.Fprintln(os.Stderr, listCmdMessage) }
go
func usage(errorMessage string) { appName := filepath.Base(os.Args[0]) appName = strings.TrimSuffix(appName, filepath.Ext(appName)) fmt.Fprintln(os.Stderr, errorMessage) fmt.Fprintln(os.Stderr, "Usage:") fmt.Fprintf(os.Stderr, " %s [OPTIONS] <command> <args...>\n\n", appName) fmt.Fprintln(os.Stderr, showHelpMessage) fmt.Fprintln(os.Stderr, listCmdMessage) }
[ "func", "usage", "(", "errorMessage", "string", ")", "{", "appName", ":=", "filepath", ".", "Base", "(", "os", ".", "Args", "[", "0", "]", ")", "\n", "appName", "=", "strings", ".", "TrimSuffix", "(", "appName", ",", "filepath", ".", "Ext", "(", "app...
// usage displays the general usage when the help flag is not displayed and // and an invalid command was specified. The commandUsage function is used // instead when a valid command was specified.
[ "usage", "displays", "the", "general", "usage", "when", "the", "help", "flag", "is", "not", "displayed", "and", "and", "an", "invalid", "command", "was", "specified", ".", "The", "commandUsage", "function", "is", "used", "instead", "when", "a", "valid", "com...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/cmd/btcctl/btcctl.go#L38-L47
162,464
btcsuite/btcd
cmd/addblock/import.go
readBlock
func (bi *blockImporter) readBlock() ([]byte, error) { // The block file format is: // <network> <block length> <serialized block> var net uint32 err := binary.Read(bi.r, binary.LittleEndian, &net) if err != nil { if err != io.EOF { return nil, err } // No block and no error means there are no more blocks to read. return nil, nil } if net != uint32(activeNetParams.Net) { return nil, fmt.Errorf("network mismatch -- got %x, want %x", net, uint32(activeNetParams.Net)) } // Read the block length and ensure it is sane. var blockLen uint32 if err := binary.Read(bi.r, binary.LittleEndian, &blockLen); err != nil { return nil, err } if blockLen > wire.MaxBlockPayload { return nil, fmt.Errorf("block payload of %d bytes is larger "+ "than the max allowed %d bytes", blockLen, wire.MaxBlockPayload) } serializedBlock := make([]byte, blockLen) if _, err := io.ReadFull(bi.r, serializedBlock); err != nil { return nil, err } return serializedBlock, nil }
go
func (bi *blockImporter) readBlock() ([]byte, error) { // The block file format is: // <network> <block length> <serialized block> var net uint32 err := binary.Read(bi.r, binary.LittleEndian, &net) if err != nil { if err != io.EOF { return nil, err } // No block and no error means there are no more blocks to read. return nil, nil } if net != uint32(activeNetParams.Net) { return nil, fmt.Errorf("network mismatch -- got %x, want %x", net, uint32(activeNetParams.Net)) } // Read the block length and ensure it is sane. var blockLen uint32 if err := binary.Read(bi.r, binary.LittleEndian, &blockLen); err != nil { return nil, err } if blockLen > wire.MaxBlockPayload { return nil, fmt.Errorf("block payload of %d bytes is larger "+ "than the max allowed %d bytes", blockLen, wire.MaxBlockPayload) } serializedBlock := make([]byte, blockLen) if _, err := io.ReadFull(bi.r, serializedBlock); err != nil { return nil, err } return serializedBlock, nil }
[ "func", "(", "bi", "*", "blockImporter", ")", "readBlock", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// The block file format is:", "// <network> <block length> <serialized block>", "var", "net", "uint32", "\n", "err", ":=", "binary", ".", "Read...
// readBlock reads the next block from the input file.
[ "readBlock", "reads", "the", "next", "block", "from", "the", "input", "file", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/cmd/addblock/import.go#L52-L87
162,465
btcsuite/btcd
cmd/addblock/import.go
processBlock
func (bi *blockImporter) processBlock(serializedBlock []byte) (bool, error) { // Deserialize the block which includes checks for malformed blocks. block, err := btcutil.NewBlockFromBytes(serializedBlock) if err != nil { return false, err } // update progress statistics bi.lastBlockTime = block.MsgBlock().Header.Timestamp bi.receivedLogTx += int64(len(block.MsgBlock().Transactions)) // Skip blocks that already exist. blockHash := block.Hash() exists, err := bi.chain.HaveBlock(blockHash) if err != nil { return false, err } if exists { return false, nil } // Don't bother trying to process orphans. prevHash := &block.MsgBlock().Header.PrevBlock if !prevHash.IsEqual(&zeroHash) { exists, err := bi.chain.HaveBlock(prevHash) if err != nil { return false, err } if !exists { return false, fmt.Errorf("import file contains block "+ "%v which does not link to the available "+ "block chain", prevHash) } } // Ensure the blocks follows all of the chain rules and match up to the // known checkpoints. isMainChain, isOrphan, err := bi.chain.ProcessBlock(block, blockchain.BFFastAdd) if err != nil { return false, err } if !isMainChain { return false, fmt.Errorf("import file contains an block that "+ "does not extend the main chain: %v", blockHash) } if isOrphan { return false, fmt.Errorf("import file contains an orphan "+ "block: %v", blockHash) } return true, nil }
go
func (bi *blockImporter) processBlock(serializedBlock []byte) (bool, error) { // Deserialize the block which includes checks for malformed blocks. block, err := btcutil.NewBlockFromBytes(serializedBlock) if err != nil { return false, err } // update progress statistics bi.lastBlockTime = block.MsgBlock().Header.Timestamp bi.receivedLogTx += int64(len(block.MsgBlock().Transactions)) // Skip blocks that already exist. blockHash := block.Hash() exists, err := bi.chain.HaveBlock(blockHash) if err != nil { return false, err } if exists { return false, nil } // Don't bother trying to process orphans. prevHash := &block.MsgBlock().Header.PrevBlock if !prevHash.IsEqual(&zeroHash) { exists, err := bi.chain.HaveBlock(prevHash) if err != nil { return false, err } if !exists { return false, fmt.Errorf("import file contains block "+ "%v which does not link to the available "+ "block chain", prevHash) } } // Ensure the blocks follows all of the chain rules and match up to the // known checkpoints. isMainChain, isOrphan, err := bi.chain.ProcessBlock(block, blockchain.BFFastAdd) if err != nil { return false, err } if !isMainChain { return false, fmt.Errorf("import file contains an block that "+ "does not extend the main chain: %v", blockHash) } if isOrphan { return false, fmt.Errorf("import file contains an orphan "+ "block: %v", blockHash) } return true, nil }
[ "func", "(", "bi", "*", "blockImporter", ")", "processBlock", "(", "serializedBlock", "[", "]", "byte", ")", "(", "bool", ",", "error", ")", "{", "// Deserialize the block which includes checks for malformed blocks.", "block", ",", "err", ":=", "btcutil", ".", "Ne...
// processBlock potentially imports the block into the database. It first // deserializes the raw block while checking for errors. Already known blocks // are skipped and orphan blocks are considered errors. Finally, it runs the // block through the chain rules to ensure it follows all rules and matches // up to the known checkpoint. Returns whether the block was imported along // with any potential errors.
[ "processBlock", "potentially", "imports", "the", "block", "into", "the", "database", ".", "It", "first", "deserializes", "the", "raw", "block", "while", "checking", "for", "errors", ".", "Already", "known", "blocks", "are", "skipped", "and", "orphan", "blocks", ...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/cmd/addblock/import.go#L95-L147
162,466
btcsuite/btcd
cmd/addblock/import.go
readHandler
func (bi *blockImporter) readHandler() { out: for { // Read the next block from the file and if anything goes wrong // notify the status handler with the error and bail. serializedBlock, err := bi.readBlock() if err != nil { bi.errChan <- fmt.Errorf("Error reading from input "+ "file: %v", err.Error()) break out } // A nil block with no error means we're done. if serializedBlock == nil { break out } // Send the block or quit if we've been signalled to exit by // the status handler due to an error elsewhere. select { case bi.processQueue <- serializedBlock: case <-bi.quit: break out } } // Close the processing channel to signal no more blocks are coming. close(bi.processQueue) bi.wg.Done() }
go
func (bi *blockImporter) readHandler() { out: for { // Read the next block from the file and if anything goes wrong // notify the status handler with the error and bail. serializedBlock, err := bi.readBlock() if err != nil { bi.errChan <- fmt.Errorf("Error reading from input "+ "file: %v", err.Error()) break out } // A nil block with no error means we're done. if serializedBlock == nil { break out } // Send the block or quit if we've been signalled to exit by // the status handler due to an error elsewhere. select { case bi.processQueue <- serializedBlock: case <-bi.quit: break out } } // Close the processing channel to signal no more blocks are coming. close(bi.processQueue) bi.wg.Done() }
[ "func", "(", "bi", "*", "blockImporter", ")", "readHandler", "(", ")", "{", "out", ":", "for", "{", "// Read the next block from the file and if anything goes wrong", "// notify the status handler with the error and bail.", "serializedBlock", ",", "err", ":=", "bi", ".", ...
// readHandler is the main handler for reading blocks from the import file. // This allows block processing to take place in parallel with block reads. // It must be run as a goroutine.
[ "readHandler", "is", "the", "main", "handler", "for", "reading", "blocks", "from", "the", "import", "file", ".", "This", "allows", "block", "processing", "to", "take", "place", "in", "parallel", "with", "block", "reads", ".", "It", "must", "be", "run", "as...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/cmd/addblock/import.go#L152-L181
162,467
btcsuite/btcd
cmd/addblock/import.go
logProgress
func (bi *blockImporter) logProgress() { bi.receivedLogBlocks++ now := time.Now() duration := now.Sub(bi.lastLogTime) if duration < time.Second*time.Duration(cfg.Progress) { return } // Truncate the duration to 10s of milliseconds. durationMillis := int64(duration / time.Millisecond) tDuration := 10 * time.Millisecond * time.Duration(durationMillis/10) // Log information about new block height. blockStr := "blocks" if bi.receivedLogBlocks == 1 { blockStr = "block" } txStr := "transactions" if bi.receivedLogTx == 1 { txStr = "transaction" } log.Infof("Processed %d %s in the last %s (%d %s, height %d, %s)", bi.receivedLogBlocks, blockStr, tDuration, bi.receivedLogTx, txStr, bi.lastHeight, bi.lastBlockTime) bi.receivedLogBlocks = 0 bi.receivedLogTx = 0 bi.lastLogTime = now }
go
func (bi *blockImporter) logProgress() { bi.receivedLogBlocks++ now := time.Now() duration := now.Sub(bi.lastLogTime) if duration < time.Second*time.Duration(cfg.Progress) { return } // Truncate the duration to 10s of milliseconds. durationMillis := int64(duration / time.Millisecond) tDuration := 10 * time.Millisecond * time.Duration(durationMillis/10) // Log information about new block height. blockStr := "blocks" if bi.receivedLogBlocks == 1 { blockStr = "block" } txStr := "transactions" if bi.receivedLogTx == 1 { txStr = "transaction" } log.Infof("Processed %d %s in the last %s (%d %s, height %d, %s)", bi.receivedLogBlocks, blockStr, tDuration, bi.receivedLogTx, txStr, bi.lastHeight, bi.lastBlockTime) bi.receivedLogBlocks = 0 bi.receivedLogTx = 0 bi.lastLogTime = now }
[ "func", "(", "bi", "*", "blockImporter", ")", "logProgress", "(", ")", "{", "bi", ".", "receivedLogBlocks", "++", "\n\n", "now", ":=", "time", ".", "Now", "(", ")", "\n", "duration", ":=", "now", ".", "Sub", "(", "bi", ".", "lastLogTime", ")", "\n", ...
// logProgress logs block progress as an information message. In order to // prevent spam, it limits logging to one message every cfg.Progress seconds // with duration and totals included.
[ "logProgress", "logs", "block", "progress", "as", "an", "information", "message", ".", "In", "order", "to", "prevent", "spam", "it", "limits", "logging", "to", "one", "message", "every", "cfg", ".", "Progress", "seconds", "with", "duration", "and", "totals", ...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/cmd/addblock/import.go#L186-L215
162,468
btcsuite/btcd
cmd/addblock/import.go
processHandler
func (bi *blockImporter) processHandler() { out: for { select { case serializedBlock, ok := <-bi.processQueue: // We're done when the channel is closed. if !ok { break out } bi.blocksProcessed++ bi.lastHeight++ imported, err := bi.processBlock(serializedBlock) if err != nil { bi.errChan <- err break out } if imported { bi.blocksImported++ } bi.logProgress() case <-bi.quit: break out } } bi.wg.Done() }
go
func (bi *blockImporter) processHandler() { out: for { select { case serializedBlock, ok := <-bi.processQueue: // We're done when the channel is closed. if !ok { break out } bi.blocksProcessed++ bi.lastHeight++ imported, err := bi.processBlock(serializedBlock) if err != nil { bi.errChan <- err break out } if imported { bi.blocksImported++ } bi.logProgress() case <-bi.quit: break out } } bi.wg.Done() }
[ "func", "(", "bi", "*", "blockImporter", ")", "processHandler", "(", ")", "{", "out", ":", "for", "{", "select", "{", "case", "serializedBlock", ",", "ok", ":=", "<-", "bi", ".", "processQueue", ":", "// We're done when the channel is closed.", "if", "!", "o...
// processHandler is the main handler for processing blocks. This allows block // processing to take place in parallel with block reads from the import file. // It must be run as a goroutine.
[ "processHandler", "is", "the", "main", "handler", "for", "processing", "blocks", ".", "This", "allows", "block", "processing", "to", "take", "place", "in", "parallel", "with", "block", "reads", "from", "the", "import", "file", ".", "It", "must", "be", "run",...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/cmd/addblock/import.go#L220-L249
162,469
btcsuite/btcd
cmd/addblock/import.go
statusHandler
func (bi *blockImporter) statusHandler(resultsChan chan *importResults) { select { // An error from either of the goroutines means we're done so signal // caller with the error and signal all goroutines to quit. case err := <-bi.errChan: resultsChan <- &importResults{ blocksProcessed: bi.blocksProcessed, blocksImported: bi.blocksImported, err: err, } close(bi.quit) // The import finished normally. case <-bi.doneChan: resultsChan <- &importResults{ blocksProcessed: bi.blocksProcessed, blocksImported: bi.blocksImported, err: nil, } } }
go
func (bi *blockImporter) statusHandler(resultsChan chan *importResults) { select { // An error from either of the goroutines means we're done so signal // caller with the error and signal all goroutines to quit. case err := <-bi.errChan: resultsChan <- &importResults{ blocksProcessed: bi.blocksProcessed, blocksImported: bi.blocksImported, err: err, } close(bi.quit) // The import finished normally. case <-bi.doneChan: resultsChan <- &importResults{ blocksProcessed: bi.blocksProcessed, blocksImported: bi.blocksImported, err: nil, } } }
[ "func", "(", "bi", "*", "blockImporter", ")", "statusHandler", "(", "resultsChan", "chan", "*", "importResults", ")", "{", "select", "{", "// An error from either of the goroutines means we're done so signal", "// caller with the error and signal all goroutines to quit.", "case",...
// statusHandler waits for updates from the import operation and notifies // the passed doneChan with the results of the import. It also causes all // goroutines to exit if an error is reported from any of them.
[ "statusHandler", "waits", "for", "updates", "from", "the", "import", "operation", "and", "notifies", "the", "passed", "doneChan", "with", "the", "results", "of", "the", "import", ".", "It", "also", "causes", "all", "goroutines", "to", "exit", "if", "an", "er...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/cmd/addblock/import.go#L254-L274
162,470
btcsuite/btcd
cmd/addblock/import.go
Import
func (bi *blockImporter) Import() chan *importResults { // Start up the read and process handling goroutines. This setup allows // blocks to be read from disk in parallel while being processed. bi.wg.Add(2) go bi.readHandler() go bi.processHandler() // Wait for the import to finish in a separate goroutine and signal // the status handler when done. go func() { bi.wg.Wait() bi.doneChan <- true }() // Start the status handler and return the result channel that it will // send the results on when the import is done. resultChan := make(chan *importResults) go bi.statusHandler(resultChan) return resultChan }
go
func (bi *blockImporter) Import() chan *importResults { // Start up the read and process handling goroutines. This setup allows // blocks to be read from disk in parallel while being processed. bi.wg.Add(2) go bi.readHandler() go bi.processHandler() // Wait for the import to finish in a separate goroutine and signal // the status handler when done. go func() { bi.wg.Wait() bi.doneChan <- true }() // Start the status handler and return the result channel that it will // send the results on when the import is done. resultChan := make(chan *importResults) go bi.statusHandler(resultChan) return resultChan }
[ "func", "(", "bi", "*", "blockImporter", ")", "Import", "(", ")", "chan", "*", "importResults", "{", "// Start up the read and process handling goroutines. This setup allows", "// blocks to be read from disk in parallel while being processed.", "bi", ".", "wg", ".", "Add", "...
// Import is the core function which handles importing the blocks from the file // associated with the block importer to the database. It returns a channel // on which the results will be returned when the operation has completed.
[ "Import", "is", "the", "core", "function", "which", "handles", "importing", "the", "blocks", "from", "the", "file", "associated", "with", "the", "block", "importer", "to", "the", "database", ".", "It", "returns", "a", "channel", "on", "which", "the", "result...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/cmd/addblock/import.go#L279-L298
162,471
btcsuite/btcd
wire/msggetblocks.go
AddBlockLocatorHash
func (msg *MsgGetBlocks) AddBlockLocatorHash(hash *chainhash.Hash) error { if len(msg.BlockLocatorHashes)+1 > MaxBlockLocatorsPerMsg { str := fmt.Sprintf("too many block locator hashes for message [max %v]", MaxBlockLocatorsPerMsg) return messageError("MsgGetBlocks.AddBlockLocatorHash", str) } msg.BlockLocatorHashes = append(msg.BlockLocatorHashes, hash) return nil }
go
func (msg *MsgGetBlocks) AddBlockLocatorHash(hash *chainhash.Hash) error { if len(msg.BlockLocatorHashes)+1 > MaxBlockLocatorsPerMsg { str := fmt.Sprintf("too many block locator hashes for message [max %v]", MaxBlockLocatorsPerMsg) return messageError("MsgGetBlocks.AddBlockLocatorHash", str) } msg.BlockLocatorHashes = append(msg.BlockLocatorHashes, hash) return nil }
[ "func", "(", "msg", "*", "MsgGetBlocks", ")", "AddBlockLocatorHash", "(", "hash", "*", "chainhash", ".", "Hash", ")", "error", "{", "if", "len", "(", "msg", ".", "BlockLocatorHashes", ")", "+", "1", ">", "MaxBlockLocatorsPerMsg", "{", "str", ":=", "fmt", ...
// AddBlockLocatorHash adds a new block locator hash to the message.
[ "AddBlockLocatorHash", "adds", "a", "new", "block", "locator", "hash", "to", "the", "message", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msggetblocks.go#L40-L49
162,472
btcsuite/btcd
wire/msggetblocks.go
NewMsgGetBlocks
func NewMsgGetBlocks(hashStop *chainhash.Hash) *MsgGetBlocks { return &MsgGetBlocks{ ProtocolVersion: ProtocolVersion, BlockLocatorHashes: make([]*chainhash.Hash, 0, MaxBlockLocatorsPerMsg), HashStop: *hashStop, } }
go
func NewMsgGetBlocks(hashStop *chainhash.Hash) *MsgGetBlocks { return &MsgGetBlocks{ ProtocolVersion: ProtocolVersion, BlockLocatorHashes: make([]*chainhash.Hash, 0, MaxBlockLocatorsPerMsg), HashStop: *hashStop, } }
[ "func", "NewMsgGetBlocks", "(", "hashStop", "*", "chainhash", ".", "Hash", ")", "*", "MsgGetBlocks", "{", "return", "&", "MsgGetBlocks", "{", "ProtocolVersion", ":", "ProtocolVersion", ",", "BlockLocatorHashes", ":", "make", "(", "[", "]", "*", "chainhash", "....
// NewMsgGetBlocks returns a new bitcoin getblocks message that conforms to the // Message interface using the passed parameters and defaults for the remaining // fields.
[ "NewMsgGetBlocks", "returns", "a", "new", "bitcoin", "getblocks", "message", "that", "conforms", "to", "the", "Message", "interface", "using", "the", "passed", "parameters", "and", "defaults", "for", "the", "remaining", "fields", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msggetblocks.go#L133-L139
162,473
btcsuite/btcd
peer/mrunoncemap.go
Exists
func (m *mruNonceMap) Exists(nonce uint64) bool { m.mtx.Lock() _, exists := m.nonceMap[nonce] m.mtx.Unlock() return exists }
go
func (m *mruNonceMap) Exists(nonce uint64) bool { m.mtx.Lock() _, exists := m.nonceMap[nonce] m.mtx.Unlock() return exists }
[ "func", "(", "m", "*", "mruNonceMap", ")", "Exists", "(", "nonce", "uint64", ")", "bool", "{", "m", ".", "mtx", ".", "Lock", "(", ")", "\n", "_", ",", "exists", ":=", "m", ".", "nonceMap", "[", "nonce", "]", "\n", "m", ".", "mtx", ".", "Unlock"...
// Exists returns whether or not the passed nonce is in the map. // // This function is safe for concurrent access.
[ "Exists", "returns", "whether", "or", "not", "the", "passed", "nonce", "is", "in", "the", "map", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/mrunoncemap.go#L49-L55
162,474
btcsuite/btcd
peer/mrunoncemap.go
Add
func (m *mruNonceMap) Add(nonce uint64) { m.mtx.Lock() defer m.mtx.Unlock() // When the limit is zero, nothing can be added to the map, so just // return. if m.limit == 0 { return } // When the entry already exists move it to the front of the list // thereby marking it most recently used. if node, exists := m.nonceMap[nonce]; exists { m.nonceList.MoveToFront(node) return } // Evict the least recently used entry (back of the list) if the the new // entry would exceed the size limit for the map. Also reuse the list // node so a new one doesn't have to be allocated. if uint(len(m.nonceMap))+1 > m.limit { node := m.nonceList.Back() lru := node.Value.(uint64) // Evict least recently used item. delete(m.nonceMap, lru) // Reuse the list node of the item that was just evicted for the // new item. node.Value = nonce m.nonceList.MoveToFront(node) m.nonceMap[nonce] = node return } // The limit hasn't been reached yet, so just add the new item. node := m.nonceList.PushFront(nonce) m.nonceMap[nonce] = node }
go
func (m *mruNonceMap) Add(nonce uint64) { m.mtx.Lock() defer m.mtx.Unlock() // When the limit is zero, nothing can be added to the map, so just // return. if m.limit == 0 { return } // When the entry already exists move it to the front of the list // thereby marking it most recently used. if node, exists := m.nonceMap[nonce]; exists { m.nonceList.MoveToFront(node) return } // Evict the least recently used entry (back of the list) if the the new // entry would exceed the size limit for the map. Also reuse the list // node so a new one doesn't have to be allocated. if uint(len(m.nonceMap))+1 > m.limit { node := m.nonceList.Back() lru := node.Value.(uint64) // Evict least recently used item. delete(m.nonceMap, lru) // Reuse the list node of the item that was just evicted for the // new item. node.Value = nonce m.nonceList.MoveToFront(node) m.nonceMap[nonce] = node return } // The limit hasn't been reached yet, so just add the new item. node := m.nonceList.PushFront(nonce) m.nonceMap[nonce] = node }
[ "func", "(", "m", "*", "mruNonceMap", ")", "Add", "(", "nonce", "uint64", ")", "{", "m", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "// When the limit is zero, nothing can be added to the map, so just"...
// Add adds the passed nonce to the map and handles eviction of the oldest item // if adding the new item would exceed the max limit. Adding an existing item // makes it the most recently used item. // // This function is safe for concurrent access.
[ "Add", "adds", "the", "passed", "nonce", "to", "the", "map", "and", "handles", "eviction", "of", "the", "oldest", "item", "if", "adding", "the", "new", "item", "would", "exceed", "the", "max", "limit", ".", "Adding", "an", "existing", "item", "makes", "i...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/mrunoncemap.go#L62-L100
162,475
btcsuite/btcd
txscript/hashcache.go
NewTxSigHashes
func NewTxSigHashes(tx *wire.MsgTx) *TxSigHashes { return &TxSigHashes{ HashPrevOuts: calcHashPrevOuts(tx), HashSequence: calcHashSequence(tx), HashOutputs: calcHashOutputs(tx), } }
go
func NewTxSigHashes(tx *wire.MsgTx) *TxSigHashes { return &TxSigHashes{ HashPrevOuts: calcHashPrevOuts(tx), HashSequence: calcHashSequence(tx), HashOutputs: calcHashOutputs(tx), } }
[ "func", "NewTxSigHashes", "(", "tx", "*", "wire", ".", "MsgTx", ")", "*", "TxSigHashes", "{", "return", "&", "TxSigHashes", "{", "HashPrevOuts", ":", "calcHashPrevOuts", "(", "tx", ")", ",", "HashSequence", ":", "calcHashSequence", "(", "tx", ")", ",", "Ha...
// NewTxSigHashes computes, and returns the cached sighashes of the given // transaction.
[ "NewTxSigHashes", "computes", "and", "returns", "the", "cached", "sighashes", "of", "the", "given", "transaction", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/hashcache.go#L26-L32
162,476
btcsuite/btcd
txscript/hashcache.go
NewHashCache
func NewHashCache(maxSize uint) *HashCache { return &HashCache{ sigHashes: make(map[chainhash.Hash]*TxSigHashes, maxSize), } }
go
func NewHashCache(maxSize uint) *HashCache { return &HashCache{ sigHashes: make(map[chainhash.Hash]*TxSigHashes, maxSize), } }
[ "func", "NewHashCache", "(", "maxSize", "uint", ")", "*", "HashCache", "{", "return", "&", "HashCache", "{", "sigHashes", ":", "make", "(", "map", "[", "chainhash", ".", "Hash", "]", "*", "TxSigHashes", ",", "maxSize", ")", ",", "}", "\n", "}" ]
// NewHashCache returns a new instance of the HashCache given a maximum number // of entries which may exist within it at anytime.
[ "NewHashCache", "returns", "a", "new", "instance", "of", "the", "HashCache", "given", "a", "maximum", "number", "of", "entries", "which", "may", "exist", "within", "it", "at", "anytime", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/hashcache.go#L47-L51
162,477
btcsuite/btcd
txscript/hashcache.go
AddSigHashes
func (h *HashCache) AddSigHashes(tx *wire.MsgTx) { h.Lock() h.sigHashes[tx.TxHash()] = NewTxSigHashes(tx) h.Unlock() }
go
func (h *HashCache) AddSigHashes(tx *wire.MsgTx) { h.Lock() h.sigHashes[tx.TxHash()] = NewTxSigHashes(tx) h.Unlock() }
[ "func", "(", "h", "*", "HashCache", ")", "AddSigHashes", "(", "tx", "*", "wire", ".", "MsgTx", ")", "{", "h", ".", "Lock", "(", ")", "\n", "h", ".", "sigHashes", "[", "tx", ".", "TxHash", "(", ")", "]", "=", "NewTxSigHashes", "(", "tx", ")", "\...
// AddSigHashes computes, then adds the partial sighashes for the passed // transaction.
[ "AddSigHashes", "computes", "then", "adds", "the", "partial", "sighashes", "for", "the", "passed", "transaction", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/hashcache.go#L55-L59
162,478
btcsuite/btcd
txscript/hashcache.go
ContainsHashes
func (h *HashCache) ContainsHashes(txid *chainhash.Hash) bool { h.RLock() _, found := h.sigHashes[*txid] h.RUnlock() return found }
go
func (h *HashCache) ContainsHashes(txid *chainhash.Hash) bool { h.RLock() _, found := h.sigHashes[*txid] h.RUnlock() return found }
[ "func", "(", "h", "*", "HashCache", ")", "ContainsHashes", "(", "txid", "*", "chainhash", ".", "Hash", ")", "bool", "{", "h", ".", "RLock", "(", ")", "\n", "_", ",", "found", ":=", "h", ".", "sigHashes", "[", "*", "txid", "]", "\n", "h", ".", "...
// ContainsHashes returns true if the partial sighashes for the passed // transaction currently exist within the HashCache, and false otherwise.
[ "ContainsHashes", "returns", "true", "if", "the", "partial", "sighashes", "for", "the", "passed", "transaction", "currently", "exist", "within", "the", "HashCache", "and", "false", "otherwise", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/hashcache.go#L63-L69
162,479
btcsuite/btcd
txscript/hashcache.go
GetSigHashes
func (h *HashCache) GetSigHashes(txid *chainhash.Hash) (*TxSigHashes, bool) { h.RLock() item, found := h.sigHashes[*txid] h.RUnlock() return item, found }
go
func (h *HashCache) GetSigHashes(txid *chainhash.Hash) (*TxSigHashes, bool) { h.RLock() item, found := h.sigHashes[*txid] h.RUnlock() return item, found }
[ "func", "(", "h", "*", "HashCache", ")", "GetSigHashes", "(", "txid", "*", "chainhash", ".", "Hash", ")", "(", "*", "TxSigHashes", ",", "bool", ")", "{", "h", ".", "RLock", "(", ")", "\n", "item", ",", "found", ":=", "h", ".", "sigHashes", "[", "...
// GetSigHashes possibly returns the previously cached partial sighashes for // the passed transaction. This function also returns an additional boolean // value indicating if the sighashes for the passed transaction were found to // be present within the HashCache.
[ "GetSigHashes", "possibly", "returns", "the", "previously", "cached", "partial", "sighashes", "for", "the", "passed", "transaction", ".", "This", "function", "also", "returns", "an", "additional", "boolean", "value", "indicating", "if", "the", "sighashes", "for", ...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/hashcache.go#L75-L81
162,480
btcsuite/btcd
txscript/hashcache.go
PurgeSigHashes
func (h *HashCache) PurgeSigHashes(txid *chainhash.Hash) { h.Lock() delete(h.sigHashes, *txid) h.Unlock() }
go
func (h *HashCache) PurgeSigHashes(txid *chainhash.Hash) { h.Lock() delete(h.sigHashes, *txid) h.Unlock() }
[ "func", "(", "h", "*", "HashCache", ")", "PurgeSigHashes", "(", "txid", "*", "chainhash", ".", "Hash", ")", "{", "h", ".", "Lock", "(", ")", "\n", "delete", "(", "h", ".", "sigHashes", ",", "*", "txid", ")", "\n", "h", ".", "Unlock", "(", ")", ...
// PurgeSigHashes removes all partial sighashes from the HashCache belonging to // the passed transaction.
[ "PurgeSigHashes", "removes", "all", "partial", "sighashes", "from", "the", "HashCache", "belonging", "to", "the", "passed", "transaction", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/hashcache.go#L85-L89
162,481
btcsuite/btcd
upnp.go
getChildDevice
func getChildDevice(d *device, deviceType string) *device { for i := range d.DeviceList.Device { if d.DeviceList.Device[i].DeviceType == deviceType { return &d.DeviceList.Device[i] } } return nil }
go
func getChildDevice(d *device, deviceType string) *device { for i := range d.DeviceList.Device { if d.DeviceList.Device[i].DeviceType == deviceType { return &d.DeviceList.Device[i] } } return nil }
[ "func", "getChildDevice", "(", "d", "*", "device", ",", "deviceType", "string", ")", "*", "device", "{", "for", "i", ":=", "range", "d", ".", "DeviceList", ".", "Device", "{", "if", "d", ".", "DeviceList", ".", "Device", "[", "i", "]", ".", "DeviceTy...
// getChildDevice searches the children of device for a device with the given // type.
[ "getChildDevice", "searches", "the", "children", "of", "device", "for", "a", "device", "with", "the", "given", "type", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/upnp.go#L194-L201
162,482
btcsuite/btcd
upnp.go
getChildService
func getChildService(d *device, serviceType string) *service { for i := range d.ServiceList.Service { if d.ServiceList.Service[i].ServiceType == serviceType { return &d.ServiceList.Service[i] } } return nil }
go
func getChildService(d *device, serviceType string) *service { for i := range d.ServiceList.Service { if d.ServiceList.Service[i].ServiceType == serviceType { return &d.ServiceList.Service[i] } } return nil }
[ "func", "getChildService", "(", "d", "*", "device", ",", "serviceType", "string", ")", "*", "service", "{", "for", "i", ":=", "range", "d", ".", "ServiceList", ".", "Service", "{", "if", "d", ".", "ServiceList", ".", "Service", "[", "i", "]", ".", "S...
// getChildDevice searches the service list of device for a service with the // given type.
[ "getChildDevice", "searches", "the", "service", "list", "of", "device", "for", "a", "service", "with", "the", "given", "type", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/upnp.go#L205-L212
162,483
btcsuite/btcd
upnp.go
getOurIP
func getOurIP() (ip string, err error) { hostname, err := os.Hostname() if err != nil { return } return net.LookupCNAME(hostname) }
go
func getOurIP() (ip string, err error) { hostname, err := os.Hostname() if err != nil { return } return net.LookupCNAME(hostname) }
[ "func", "getOurIP", "(", ")", "(", "ip", "string", ",", "err", "error", ")", "{", "hostname", ",", "err", ":=", "os", ".", "Hostname", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "return", "net", ".", "LookupCNAME", ...
// getOurIP returns a best guess at what the local IP is.
[ "getOurIP", "returns", "a", "best", "guess", "at", "what", "the", "local", "IP", "is", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/upnp.go#L215-L221
162,484
btcsuite/btcd
upnp.go
soapRequest
func soapRequest(url, function, message string) (replyXML []byte, err error) { fullMessage := "<?xml version=\"1.0\" ?>" + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\r\n" + "<s:Body>" + message + "</s:Body></s:Envelope>" req, err := http.NewRequest("POST", url, strings.NewReader(fullMessage)) if err != nil { return nil, err } req.Header.Set("Content-Type", "text/xml ; charset=\"utf-8\"") req.Header.Set("User-Agent", "Darwin/10.0.0, UPnP/1.0, MiniUPnPc/1.3") //req.Header.Set("Transfer-Encoding", "chunked") req.Header.Set("SOAPAction", "\"urn:schemas-upnp-org:service:WANIPConnection:1#"+function+"\"") req.Header.Set("Connection", "Close") req.Header.Set("Cache-Control", "no-cache") req.Header.Set("Pragma", "no-cache") r, err := http.DefaultClient.Do(req) if err != nil { return nil, err } if r.Body != nil { defer r.Body.Close() } if r.StatusCode >= 400 { // log.Stderr(function, r.StatusCode) err = errors.New("Error " + strconv.Itoa(r.StatusCode) + " for " + function) r = nil return } var reply soapEnvelope err = xml.NewDecoder(r.Body).Decode(&reply) if err != nil { return nil, err } return reply.Body.Data, nil }
go
func soapRequest(url, function, message string) (replyXML []byte, err error) { fullMessage := "<?xml version=\"1.0\" ?>" + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\r\n" + "<s:Body>" + message + "</s:Body></s:Envelope>" req, err := http.NewRequest("POST", url, strings.NewReader(fullMessage)) if err != nil { return nil, err } req.Header.Set("Content-Type", "text/xml ; charset=\"utf-8\"") req.Header.Set("User-Agent", "Darwin/10.0.0, UPnP/1.0, MiniUPnPc/1.3") //req.Header.Set("Transfer-Encoding", "chunked") req.Header.Set("SOAPAction", "\"urn:schemas-upnp-org:service:WANIPConnection:1#"+function+"\"") req.Header.Set("Connection", "Close") req.Header.Set("Cache-Control", "no-cache") req.Header.Set("Pragma", "no-cache") r, err := http.DefaultClient.Do(req) if err != nil { return nil, err } if r.Body != nil { defer r.Body.Close() } if r.StatusCode >= 400 { // log.Stderr(function, r.StatusCode) err = errors.New("Error " + strconv.Itoa(r.StatusCode) + " for " + function) r = nil return } var reply soapEnvelope err = xml.NewDecoder(r.Body).Decode(&reply) if err != nil { return nil, err } return reply.Body.Data, nil }
[ "func", "soapRequest", "(", "url", ",", "function", ",", "message", "string", ")", "(", "replyXML", "[", "]", "byte", ",", "err", "error", ")", "{", "fullMessage", ":=", "\"", "\\\"", "\\\"", "\"", "+", "\"", "\\\"", "\\\"", "\\\"", "\\\"", "\\r", "\...
// soapRequests performs a soap request with the given parameters and returns // the xml replied stripped of the soap headers. in the case that the request is // unsuccessful the an error is returned.
[ "soapRequests", "performs", "a", "soap", "request", "with", "the", "given", "parameters", "and", "returns", "the", "xml", "replied", "stripped", "of", "the", "soap", "headers", ".", "in", "the", "case", "that", "the", "request", "is", "unsuccessful", "the", ...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/upnp.go#L290-L327
162,485
btcsuite/btcd
upnp.go
GetExternalAddress
func (n *upnpNAT) GetExternalAddress() (addr net.IP, err error) { message := "<u:GetExternalIPAddress xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\"/>\r\n" response, err := soapRequest(n.serviceURL, "GetExternalIPAddress", message) if err != nil { return nil, err } var reply getExternalIPAddressResponse err = xml.Unmarshal(response, &reply) if err != nil { return nil, err } addr = net.ParseIP(reply.ExternalIPAddress) if addr == nil { return nil, errors.New("unable to parse ip address") } return addr, nil }
go
func (n *upnpNAT) GetExternalAddress() (addr net.IP, err error) { message := "<u:GetExternalIPAddress xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\"/>\r\n" response, err := soapRequest(n.serviceURL, "GetExternalIPAddress", message) if err != nil { return nil, err } var reply getExternalIPAddressResponse err = xml.Unmarshal(response, &reply) if err != nil { return nil, err } addr = net.ParseIP(reply.ExternalIPAddress) if addr == nil { return nil, errors.New("unable to parse ip address") } return addr, nil }
[ "func", "(", "n", "*", "upnpNAT", ")", "GetExternalAddress", "(", ")", "(", "addr", "net", ".", "IP", ",", "err", "error", ")", "{", "message", ":=", "\"", "\\\"", "\\\"", "\\r", "\\n", "\"", "\n", "response", ",", "err", ":=", "soapRequest", "(", ...
// GetExternalAddress implements the NAT interface by fetching the external IP // from the UPnP router.
[ "GetExternalAddress", "implements", "the", "NAT", "interface", "by", "fetching", "the", "external", "IP", "from", "the", "UPnP", "router", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/upnp.go#L338-L356
162,486
btcsuite/btcd
upnp.go
AddPortMapping
func (n *upnpNAT) AddPortMapping(protocol string, externalPort, internalPort int, description string, timeout int) (mappedExternalPort int, err error) { // A single concatenation would break ARM compilation. message := "<u:AddPortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">\r\n" + "<NewRemoteHost></NewRemoteHost><NewExternalPort>" + strconv.Itoa(externalPort) message += "</NewExternalPort><NewProtocol>" + strings.ToUpper(protocol) + "</NewProtocol>" message += "<NewInternalPort>" + strconv.Itoa(internalPort) + "</NewInternalPort>" + "<NewInternalClient>" + n.ourIP + "</NewInternalClient>" + "<NewEnabled>1</NewEnabled><NewPortMappingDescription>" message += description + "</NewPortMappingDescription><NewLeaseDuration>" + strconv.Itoa(timeout) + "</NewLeaseDuration></u:AddPortMapping>" response, err := soapRequest(n.serviceURL, "AddPortMapping", message) if err != nil { return } // TODO: check response to see if the port was forwarded // If the port was not wildcard we don't get an reply with the port in // it. Not sure about wildcard yet. miniupnpc just checks for error // codes here. mappedExternalPort = externalPort _ = response return }
go
func (n *upnpNAT) AddPortMapping(protocol string, externalPort, internalPort int, description string, timeout int) (mappedExternalPort int, err error) { // A single concatenation would break ARM compilation. message := "<u:AddPortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">\r\n" + "<NewRemoteHost></NewRemoteHost><NewExternalPort>" + strconv.Itoa(externalPort) message += "</NewExternalPort><NewProtocol>" + strings.ToUpper(protocol) + "</NewProtocol>" message += "<NewInternalPort>" + strconv.Itoa(internalPort) + "</NewInternalPort>" + "<NewInternalClient>" + n.ourIP + "</NewInternalClient>" + "<NewEnabled>1</NewEnabled><NewPortMappingDescription>" message += description + "</NewPortMappingDescription><NewLeaseDuration>" + strconv.Itoa(timeout) + "</NewLeaseDuration></u:AddPortMapping>" response, err := soapRequest(n.serviceURL, "AddPortMapping", message) if err != nil { return } // TODO: check response to see if the port was forwarded // If the port was not wildcard we don't get an reply with the port in // it. Not sure about wildcard yet. miniupnpc just checks for error // codes here. mappedExternalPort = externalPort _ = response return }
[ "func", "(", "n", "*", "upnpNAT", ")", "AddPortMapping", "(", "protocol", "string", ",", "externalPort", ",", "internalPort", "int", ",", "description", "string", ",", "timeout", "int", ")", "(", "mappedExternalPort", "int", ",", "err", "error", ")", "{", ...
// AddPortMapping implements the NAT interface by setting up a port forwarding // from the UPnP router to the local machine with the given ports and protocol.
[ "AddPortMapping", "implements", "the", "NAT", "interface", "by", "setting", "up", "a", "port", "forwarding", "from", "the", "UPnP", "router", "to", "the", "local", "machine", "with", "the", "given", "ports", "and", "protocol", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/upnp.go#L360-L384
162,487
btcsuite/btcd
upnp.go
DeletePortMapping
func (n *upnpNAT) DeletePortMapping(protocol string, externalPort, internalPort int) (err error) { message := "<u:DeletePortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">\r\n" + "<NewRemoteHost></NewRemoteHost><NewExternalPort>" + strconv.Itoa(externalPort) + "</NewExternalPort><NewProtocol>" + strings.ToUpper(protocol) + "</NewProtocol>" + "</u:DeletePortMapping>" response, err := soapRequest(n.serviceURL, "DeletePortMapping", message) if err != nil { return } // TODO: check response to see if the port was deleted // log.Println(message, response) _ = response return }
go
func (n *upnpNAT) DeletePortMapping(protocol string, externalPort, internalPort int) (err error) { message := "<u:DeletePortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">\r\n" + "<NewRemoteHost></NewRemoteHost><NewExternalPort>" + strconv.Itoa(externalPort) + "</NewExternalPort><NewProtocol>" + strings.ToUpper(protocol) + "</NewProtocol>" + "</u:DeletePortMapping>" response, err := soapRequest(n.serviceURL, "DeletePortMapping", message) if err != nil { return } // TODO: check response to see if the port was deleted // log.Println(message, response) _ = response return }
[ "func", "(", "n", "*", "upnpNAT", ")", "DeletePortMapping", "(", "protocol", "string", ",", "externalPort", ",", "internalPort", "int", ")", "(", "err", "error", ")", "{", "message", ":=", "\"", "\\\"", "\\\"", "\\r", "\\n", "\"", "+", "\"", "\"", "+",...
// DeletePortMapping implements the NAT interface by removing up a port forwarding // from the UPnP router to the local machine with the given ports and.
[ "DeletePortMapping", "implements", "the", "NAT", "interface", "by", "removing", "up", "a", "port", "forwarding", "from", "the", "UPnP", "router", "to", "the", "local", "machine", "with", "the", "given", "ports", "and", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/upnp.go#L388-L404
162,488
btcsuite/btcd
mining/cpuminer/cpuminer.go
speedMonitor
func (m *CPUMiner) speedMonitor() { log.Tracef("CPU miner speed monitor started") var hashesPerSec float64 var totalHashes uint64 ticker := time.NewTicker(time.Second * hpsUpdateSecs) defer ticker.Stop() out: for { select { // Periodic updates from the workers with how many hashes they // have performed. case numHashes := <-m.updateHashes: totalHashes += numHashes // Time to update the hashes per second. case <-ticker.C: curHashesPerSec := float64(totalHashes) / hpsUpdateSecs if hashesPerSec == 0 { hashesPerSec = curHashesPerSec } hashesPerSec = (hashesPerSec + curHashesPerSec) / 2 totalHashes = 0 if hashesPerSec != 0 { log.Debugf("Hash speed: %6.0f kilohashes/s", hashesPerSec/1000) } // Request for the number of hashes per second. case m.queryHashesPerSec <- hashesPerSec: // Nothing to do. case <-m.speedMonitorQuit: break out } } m.wg.Done() log.Tracef("CPU miner speed monitor done") }
go
func (m *CPUMiner) speedMonitor() { log.Tracef("CPU miner speed monitor started") var hashesPerSec float64 var totalHashes uint64 ticker := time.NewTicker(time.Second * hpsUpdateSecs) defer ticker.Stop() out: for { select { // Periodic updates from the workers with how many hashes they // have performed. case numHashes := <-m.updateHashes: totalHashes += numHashes // Time to update the hashes per second. case <-ticker.C: curHashesPerSec := float64(totalHashes) / hpsUpdateSecs if hashesPerSec == 0 { hashesPerSec = curHashesPerSec } hashesPerSec = (hashesPerSec + curHashesPerSec) / 2 totalHashes = 0 if hashesPerSec != 0 { log.Debugf("Hash speed: %6.0f kilohashes/s", hashesPerSec/1000) } // Request for the number of hashes per second. case m.queryHashesPerSec <- hashesPerSec: // Nothing to do. case <-m.speedMonitorQuit: break out } } m.wg.Done() log.Tracef("CPU miner speed monitor done") }
[ "func", "(", "m", "*", "CPUMiner", ")", "speedMonitor", "(", ")", "{", "log", ".", "Tracef", "(", "\"", "\"", ")", "\n\n", "var", "hashesPerSec", "float64", "\n", "var", "totalHashes", "uint64", "\n", "ticker", ":=", "time", ".", "NewTicker", "(", "tim...
// speedMonitor handles tracking the number of hashes per second the mining // process is performing. It must be run as a goroutine.
[ "speedMonitor", "handles", "tracking", "the", "number", "of", "hashes", "per", "second", "the", "mining", "process", "is", "performing", ".", "It", "must", "be", "run", "as", "a", "goroutine", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/cpuminer/cpuminer.go#L111-L151
162,489
btcsuite/btcd
mining/cpuminer/cpuminer.go
submitBlock
func (m *CPUMiner) submitBlock(block *btcutil.Block) bool { m.submitBlockLock.Lock() defer m.submitBlockLock.Unlock() // Ensure the block is not stale since a new block could have shown up // while the solution was being found. Typically that condition is // detected and all work on the stale block is halted to start work on // a new block, but the check only happens periodically, so it is // possible a block was found and submitted in between. msgBlock := block.MsgBlock() if !msgBlock.Header.PrevBlock.IsEqual(&m.g.BestSnapshot().Hash) { log.Debugf("Block submitted via CPU miner with previous "+ "block %s is stale", msgBlock.Header.PrevBlock) return false } // Process this block using the same rules as blocks coming from other // nodes. This will in turn relay it to the network like normal. isOrphan, err := m.cfg.ProcessBlock(block, blockchain.BFNone) if err != nil { // Anything other than a rule violation is an unexpected error, // so log that error as an internal error. if _, ok := err.(blockchain.RuleError); !ok { log.Errorf("Unexpected error while processing "+ "block submitted via CPU miner: %v", err) return false } log.Debugf("Block submitted via CPU miner rejected: %v", err) return false } if isOrphan { log.Debugf("Block submitted via CPU miner is an orphan") return false } // The block was accepted. coinbaseTx := block.MsgBlock().Transactions[0].TxOut[0] log.Infof("Block submitted via CPU miner accepted (hash %s, "+ "amount %v)", block.Hash(), btcutil.Amount(coinbaseTx.Value)) return true }
go
func (m *CPUMiner) submitBlock(block *btcutil.Block) bool { m.submitBlockLock.Lock() defer m.submitBlockLock.Unlock() // Ensure the block is not stale since a new block could have shown up // while the solution was being found. Typically that condition is // detected and all work on the stale block is halted to start work on // a new block, but the check only happens periodically, so it is // possible a block was found and submitted in between. msgBlock := block.MsgBlock() if !msgBlock.Header.PrevBlock.IsEqual(&m.g.BestSnapshot().Hash) { log.Debugf("Block submitted via CPU miner with previous "+ "block %s is stale", msgBlock.Header.PrevBlock) return false } // Process this block using the same rules as blocks coming from other // nodes. This will in turn relay it to the network like normal. isOrphan, err := m.cfg.ProcessBlock(block, blockchain.BFNone) if err != nil { // Anything other than a rule violation is an unexpected error, // so log that error as an internal error. if _, ok := err.(blockchain.RuleError); !ok { log.Errorf("Unexpected error while processing "+ "block submitted via CPU miner: %v", err) return false } log.Debugf("Block submitted via CPU miner rejected: %v", err) return false } if isOrphan { log.Debugf("Block submitted via CPU miner is an orphan") return false } // The block was accepted. coinbaseTx := block.MsgBlock().Transactions[0].TxOut[0] log.Infof("Block submitted via CPU miner accepted (hash %s, "+ "amount %v)", block.Hash(), btcutil.Amount(coinbaseTx.Value)) return true }
[ "func", "(", "m", "*", "CPUMiner", ")", "submitBlock", "(", "block", "*", "btcutil", ".", "Block", ")", "bool", "{", "m", ".", "submitBlockLock", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "submitBlockLock", ".", "Unlock", "(", ")", "\n\n", "// ...
// submitBlock submits the passed block to network after ensuring it passes all // of the consensus validation rules.
[ "submitBlock", "submits", "the", "passed", "block", "to", "network", "after", "ensuring", "it", "passes", "all", "of", "the", "consensus", "validation", "rules", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/cpuminer/cpuminer.go#L155-L196
162,490
btcsuite/btcd
mining/cpuminer/cpuminer.go
solveBlock
func (m *CPUMiner) solveBlock(msgBlock *wire.MsgBlock, blockHeight int32, ticker *time.Ticker, quit chan struct{}) bool { // Choose a random extra nonce offset for this block template and // worker. enOffset, err := wire.RandomUint64() if err != nil { log.Errorf("Unexpected error while generating random "+ "extra nonce offset: %v", err) enOffset = 0 } // Create some convenience variables. header := &msgBlock.Header targetDifficulty := blockchain.CompactToBig(header.Bits) // Initial state. lastGenerated := time.Now() lastTxUpdate := m.g.TxSource().LastUpdated() hashesCompleted := uint64(0) // Note that the entire extra nonce range is iterated and the offset is // added relying on the fact that overflow will wrap around 0 as // provided by the Go spec. for extraNonce := uint64(0); extraNonce < maxExtraNonce; extraNonce++ { // Update the extra nonce in the block template with the // new value by regenerating the coinbase script and // setting the merkle root to the new value. m.g.UpdateExtraNonce(msgBlock, blockHeight, extraNonce+enOffset) // Search through the entire nonce range for a solution while // periodically checking for early quit and stale block // conditions along with updates to the speed monitor. for i := uint32(0); i <= maxNonce; i++ { select { case <-quit: return false case <-ticker.C: m.updateHashes <- hashesCompleted hashesCompleted = 0 // The current block is stale if the best block // has changed. best := m.g.BestSnapshot() if !header.PrevBlock.IsEqual(&best.Hash) { return false } // The current block is stale if the memory pool // has been updated since the block template was // generated and it has been at least one // minute. if lastTxUpdate != m.g.TxSource().LastUpdated() && time.Now().After(lastGenerated.Add(time.Minute)) { return false } m.g.UpdateBlockTime(msgBlock) default: // Non-blocking select to fall through } // Update the nonce and hash the block header. Each // hash is actually a double sha256 (two hashes), so // increment the number of hashes completed for each // attempt accordingly. header.Nonce = i hash := header.BlockHash() hashesCompleted += 2 // The block is solved when the new block hash is less // than the target difficulty. Yay! if blockchain.HashToBig(&hash).Cmp(targetDifficulty) <= 0 { m.updateHashes <- hashesCompleted return true } } } return false }
go
func (m *CPUMiner) solveBlock(msgBlock *wire.MsgBlock, blockHeight int32, ticker *time.Ticker, quit chan struct{}) bool { // Choose a random extra nonce offset for this block template and // worker. enOffset, err := wire.RandomUint64() if err != nil { log.Errorf("Unexpected error while generating random "+ "extra nonce offset: %v", err) enOffset = 0 } // Create some convenience variables. header := &msgBlock.Header targetDifficulty := blockchain.CompactToBig(header.Bits) // Initial state. lastGenerated := time.Now() lastTxUpdate := m.g.TxSource().LastUpdated() hashesCompleted := uint64(0) // Note that the entire extra nonce range is iterated and the offset is // added relying on the fact that overflow will wrap around 0 as // provided by the Go spec. for extraNonce := uint64(0); extraNonce < maxExtraNonce; extraNonce++ { // Update the extra nonce in the block template with the // new value by regenerating the coinbase script and // setting the merkle root to the new value. m.g.UpdateExtraNonce(msgBlock, blockHeight, extraNonce+enOffset) // Search through the entire nonce range for a solution while // periodically checking for early quit and stale block // conditions along with updates to the speed monitor. for i := uint32(0); i <= maxNonce; i++ { select { case <-quit: return false case <-ticker.C: m.updateHashes <- hashesCompleted hashesCompleted = 0 // The current block is stale if the best block // has changed. best := m.g.BestSnapshot() if !header.PrevBlock.IsEqual(&best.Hash) { return false } // The current block is stale if the memory pool // has been updated since the block template was // generated and it has been at least one // minute. if lastTxUpdate != m.g.TxSource().LastUpdated() && time.Now().After(lastGenerated.Add(time.Minute)) { return false } m.g.UpdateBlockTime(msgBlock) default: // Non-blocking select to fall through } // Update the nonce and hash the block header. Each // hash is actually a double sha256 (two hashes), so // increment the number of hashes completed for each // attempt accordingly. header.Nonce = i hash := header.BlockHash() hashesCompleted += 2 // The block is solved when the new block hash is less // than the target difficulty. Yay! if blockchain.HashToBig(&hash).Cmp(targetDifficulty) <= 0 { m.updateHashes <- hashesCompleted return true } } } return false }
[ "func", "(", "m", "*", "CPUMiner", ")", "solveBlock", "(", "msgBlock", "*", "wire", ".", "MsgBlock", ",", "blockHeight", "int32", ",", "ticker", "*", "time", ".", "Ticker", ",", "quit", "chan", "struct", "{", "}", ")", "bool", "{", "// Choose a random ex...
// solveBlock attempts to find some combination of a nonce, extra nonce, and // current timestamp which makes the passed block hash to a value less than the // target difficulty. The timestamp is updated periodically and the passed // block is modified with all tweaks during this process. This means that // when the function returns true, the block is ready for submission. // // This function will return early with false when conditions that trigger a // stale block such as a new block showing up or periodically when there are // new transactions and enough time has elapsed without finding a solution.
[ "solveBlock", "attempts", "to", "find", "some", "combination", "of", "a", "nonce", "extra", "nonce", "and", "current", "timestamp", "which", "makes", "the", "passed", "block", "hash", "to", "a", "value", "less", "than", "the", "target", "difficulty", ".", "T...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/cpuminer/cpuminer.go#L207-L290
162,491
btcsuite/btcd
mining/cpuminer/cpuminer.go
generateBlocks
func (m *CPUMiner) generateBlocks(quit chan struct{}) { log.Tracef("Starting generate blocks worker") // Start a ticker which is used to signal checks for stale work and // updates to the speed monitor. ticker := time.NewTicker(time.Second * hashUpdateSecs) defer ticker.Stop() out: for { // Quit when the miner is stopped. select { case <-quit: break out default: // Non-blocking select to fall through } // Wait until there is a connection to at least one other peer // since there is no way to relay a found block or receive // transactions to work on when there are no connected peers. if m.cfg.ConnectedCount() == 0 { time.Sleep(time.Second) continue } // No point in searching for a solution before the chain is // synced. Also, grab the same lock as used for block // submission, since the current block will be changing and // this would otherwise end up building a new block template on // a block that is in the process of becoming stale. m.submitBlockLock.Lock() curHeight := m.g.BestSnapshot().Height if curHeight != 0 && !m.cfg.IsCurrent() { m.submitBlockLock.Unlock() time.Sleep(time.Second) continue } // Choose a payment address at random. rand.Seed(time.Now().UnixNano()) payToAddr := m.cfg.MiningAddrs[rand.Intn(len(m.cfg.MiningAddrs))] // Create a new block template using the available transactions // in the memory pool as a source of transactions to potentially // include in the block. template, err := m.g.NewBlockTemplate(payToAddr) m.submitBlockLock.Unlock() if err != nil { errStr := fmt.Sprintf("Failed to create new block "+ "template: %v", err) log.Errorf(errStr) continue } // Attempt to solve the block. The function will exit early // with false when conditions that trigger a stale block, so // a new block template can be generated. When the return is // true a solution was found, so submit the solved block. if m.solveBlock(template.Block, curHeight+1, ticker, quit) { block := btcutil.NewBlock(template.Block) m.submitBlock(block) } } m.workerWg.Done() log.Tracef("Generate blocks worker done") }
go
func (m *CPUMiner) generateBlocks(quit chan struct{}) { log.Tracef("Starting generate blocks worker") // Start a ticker which is used to signal checks for stale work and // updates to the speed monitor. ticker := time.NewTicker(time.Second * hashUpdateSecs) defer ticker.Stop() out: for { // Quit when the miner is stopped. select { case <-quit: break out default: // Non-blocking select to fall through } // Wait until there is a connection to at least one other peer // since there is no way to relay a found block or receive // transactions to work on when there are no connected peers. if m.cfg.ConnectedCount() == 0 { time.Sleep(time.Second) continue } // No point in searching for a solution before the chain is // synced. Also, grab the same lock as used for block // submission, since the current block will be changing and // this would otherwise end up building a new block template on // a block that is in the process of becoming stale. m.submitBlockLock.Lock() curHeight := m.g.BestSnapshot().Height if curHeight != 0 && !m.cfg.IsCurrent() { m.submitBlockLock.Unlock() time.Sleep(time.Second) continue } // Choose a payment address at random. rand.Seed(time.Now().UnixNano()) payToAddr := m.cfg.MiningAddrs[rand.Intn(len(m.cfg.MiningAddrs))] // Create a new block template using the available transactions // in the memory pool as a source of transactions to potentially // include in the block. template, err := m.g.NewBlockTemplate(payToAddr) m.submitBlockLock.Unlock() if err != nil { errStr := fmt.Sprintf("Failed to create new block "+ "template: %v", err) log.Errorf(errStr) continue } // Attempt to solve the block. The function will exit early // with false when conditions that trigger a stale block, so // a new block template can be generated. When the return is // true a solution was found, so submit the solved block. if m.solveBlock(template.Block, curHeight+1, ticker, quit) { block := btcutil.NewBlock(template.Block) m.submitBlock(block) } } m.workerWg.Done() log.Tracef("Generate blocks worker done") }
[ "func", "(", "m", "*", "CPUMiner", ")", "generateBlocks", "(", "quit", "chan", "struct", "{", "}", ")", "{", "log", ".", "Tracef", "(", "\"", "\"", ")", "\n\n", "// Start a ticker which is used to signal checks for stale work and", "// updates to the speed monitor.", ...
// generateBlocks is a worker that is controlled by the miningWorkerController. // It is self contained in that it creates block templates and attempts to solve // them while detecting when it is performing stale work and reacting // accordingly by generating a new block template. When a block is solved, it // is submitted. // // It must be run as a goroutine.
[ "generateBlocks", "is", "a", "worker", "that", "is", "controlled", "by", "the", "miningWorkerController", ".", "It", "is", "self", "contained", "in", "that", "it", "creates", "block", "templates", "and", "attempts", "to", "solve", "them", "while", "detecting", ...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/cpuminer/cpuminer.go#L299-L365
162,492
btcsuite/btcd
mining/cpuminer/cpuminer.go
miningWorkerController
func (m *CPUMiner) miningWorkerController() { // launchWorkers groups common code to launch a specified number of // workers for generating blocks. var runningWorkers []chan struct{} launchWorkers := func(numWorkers uint32) { for i := uint32(0); i < numWorkers; i++ { quit := make(chan struct{}) runningWorkers = append(runningWorkers, quit) m.workerWg.Add(1) go m.generateBlocks(quit) } } // Launch the current number of workers by default. runningWorkers = make([]chan struct{}, 0, m.numWorkers) launchWorkers(m.numWorkers) out: for { select { // Update the number of running workers. case <-m.updateNumWorkers: // No change. numRunning := uint32(len(runningWorkers)) if m.numWorkers == numRunning { continue } // Add new workers. if m.numWorkers > numRunning { launchWorkers(m.numWorkers - numRunning) continue } // Signal the most recently created goroutines to exit. for i := numRunning - 1; i >= m.numWorkers; i-- { close(runningWorkers[i]) runningWorkers[i] = nil runningWorkers = runningWorkers[:i] } case <-m.quit: for _, quit := range runningWorkers { close(quit) } break out } } // Wait until all workers shut down to stop the speed monitor since // they rely on being able to send updates to it. m.workerWg.Wait() close(m.speedMonitorQuit) m.wg.Done() }
go
func (m *CPUMiner) miningWorkerController() { // launchWorkers groups common code to launch a specified number of // workers for generating blocks. var runningWorkers []chan struct{} launchWorkers := func(numWorkers uint32) { for i := uint32(0); i < numWorkers; i++ { quit := make(chan struct{}) runningWorkers = append(runningWorkers, quit) m.workerWg.Add(1) go m.generateBlocks(quit) } } // Launch the current number of workers by default. runningWorkers = make([]chan struct{}, 0, m.numWorkers) launchWorkers(m.numWorkers) out: for { select { // Update the number of running workers. case <-m.updateNumWorkers: // No change. numRunning := uint32(len(runningWorkers)) if m.numWorkers == numRunning { continue } // Add new workers. if m.numWorkers > numRunning { launchWorkers(m.numWorkers - numRunning) continue } // Signal the most recently created goroutines to exit. for i := numRunning - 1; i >= m.numWorkers; i-- { close(runningWorkers[i]) runningWorkers[i] = nil runningWorkers = runningWorkers[:i] } case <-m.quit: for _, quit := range runningWorkers { close(quit) } break out } } // Wait until all workers shut down to stop the speed monitor since // they rely on being able to send updates to it. m.workerWg.Wait() close(m.speedMonitorQuit) m.wg.Done() }
[ "func", "(", "m", "*", "CPUMiner", ")", "miningWorkerController", "(", ")", "{", "// launchWorkers groups common code to launch a specified number of", "// workers for generating blocks.", "var", "runningWorkers", "[", "]", "chan", "struct", "{", "}", "\n", "launchWorkers",...
// miningWorkerController launches the worker goroutines that are used to // generate block templates and solve them. It also provides the ability to // dynamically adjust the number of running worker goroutines. // // It must be run as a goroutine.
[ "miningWorkerController", "launches", "the", "worker", "goroutines", "that", "are", "used", "to", "generate", "block", "templates", "and", "solve", "them", ".", "It", "also", "provides", "the", "ability", "to", "dynamically", "adjust", "the", "number", "of", "ru...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/cpuminer/cpuminer.go#L372-L427
162,493
btcsuite/btcd
mining/cpuminer/cpuminer.go
Start
func (m *CPUMiner) Start() { m.Lock() defer m.Unlock() // Nothing to do if the miner is already running or if running in // discrete mode (using GenerateNBlocks). if m.started || m.discreteMining { return } m.quit = make(chan struct{}) m.speedMonitorQuit = make(chan struct{}) m.wg.Add(2) go m.speedMonitor() go m.miningWorkerController() m.started = true log.Infof("CPU miner started") }
go
func (m *CPUMiner) Start() { m.Lock() defer m.Unlock() // Nothing to do if the miner is already running or if running in // discrete mode (using GenerateNBlocks). if m.started || m.discreteMining { return } m.quit = make(chan struct{}) m.speedMonitorQuit = make(chan struct{}) m.wg.Add(2) go m.speedMonitor() go m.miningWorkerController() m.started = true log.Infof("CPU miner started") }
[ "func", "(", "m", "*", "CPUMiner", ")", "Start", "(", ")", "{", "m", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "Unlock", "(", ")", "\n\n", "// Nothing to do if the miner is already running or if running in", "// discrete mode (using GenerateNBlocks).", "if", ...
// Start begins the CPU mining process as well as the speed monitor used to // track hashing metrics. Calling this function when the CPU miner has // already been started will have no effect. // // This function is safe for concurrent access.
[ "Start", "begins", "the", "CPU", "mining", "process", "as", "well", "as", "the", "speed", "monitor", "used", "to", "track", "hashing", "metrics", ".", "Calling", "this", "function", "when", "the", "CPU", "miner", "has", "already", "been", "started", "will", ...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/cpuminer/cpuminer.go#L434-L452
162,494
btcsuite/btcd
mining/cpuminer/cpuminer.go
Stop
func (m *CPUMiner) Stop() { m.Lock() defer m.Unlock() // Nothing to do if the miner is not currently running or if running in // discrete mode (using GenerateNBlocks). if !m.started || m.discreteMining { return } close(m.quit) m.wg.Wait() m.started = false log.Infof("CPU miner stopped") }
go
func (m *CPUMiner) Stop() { m.Lock() defer m.Unlock() // Nothing to do if the miner is not currently running or if running in // discrete mode (using GenerateNBlocks). if !m.started || m.discreteMining { return } close(m.quit) m.wg.Wait() m.started = false log.Infof("CPU miner stopped") }
[ "func", "(", "m", "*", "CPUMiner", ")", "Stop", "(", ")", "{", "m", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "Unlock", "(", ")", "\n\n", "// Nothing to do if the miner is not currently running or if running in", "// discrete mode (using GenerateNBlocks).", "i...
// Stop gracefully stops the mining process by signalling all workers, and the // speed monitor to quit. Calling this function when the CPU miner has not // already been started will have no effect. // // This function is safe for concurrent access.
[ "Stop", "gracefully", "stops", "the", "mining", "process", "by", "signalling", "all", "workers", "and", "the", "speed", "monitor", "to", "quit", ".", "Calling", "this", "function", "when", "the", "CPU", "miner", "has", "not", "already", "been", "started", "w...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/cpuminer/cpuminer.go#L459-L473
162,495
btcsuite/btcd
mining/cpuminer/cpuminer.go
IsMining
func (m *CPUMiner) IsMining() bool { m.Lock() defer m.Unlock() return m.started }
go
func (m *CPUMiner) IsMining() bool { m.Lock() defer m.Unlock() return m.started }
[ "func", "(", "m", "*", "CPUMiner", ")", "IsMining", "(", ")", "bool", "{", "m", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "Unlock", "(", ")", "\n\n", "return", "m", ".", "started", "\n", "}" ]
// IsMining returns whether or not the CPU miner has been started and is // therefore currenting mining. // // This function is safe for concurrent access.
[ "IsMining", "returns", "whether", "or", "not", "the", "CPU", "miner", "has", "been", "started", "and", "is", "therefore", "currenting", "mining", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/cpuminer/cpuminer.go#L479-L484
162,496
btcsuite/btcd
mining/cpuminer/cpuminer.go
HashesPerSecond
func (m *CPUMiner) HashesPerSecond() float64 { m.Lock() defer m.Unlock() // Nothing to do if the miner is not currently running. if !m.started { return 0 } return <-m.queryHashesPerSec }
go
func (m *CPUMiner) HashesPerSecond() float64 { m.Lock() defer m.Unlock() // Nothing to do if the miner is not currently running. if !m.started { return 0 } return <-m.queryHashesPerSec }
[ "func", "(", "m", "*", "CPUMiner", ")", "HashesPerSecond", "(", ")", "float64", "{", "m", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "Unlock", "(", ")", "\n\n", "// Nothing to do if the miner is not currently running.", "if", "!", "m", ".", "started", ...
// HashesPerSecond returns the number of hashes per second the mining process // is performing. 0 is returned if the miner is not currently running. // // This function is safe for concurrent access.
[ "HashesPerSecond", "returns", "the", "number", "of", "hashes", "per", "second", "the", "mining", "process", "is", "performing", ".", "0", "is", "returned", "if", "the", "miner", "is", "not", "currently", "running", ".", "This", "function", "is", "safe", "for...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/cpuminer/cpuminer.go#L490-L500
162,497
btcsuite/btcd
mining/cpuminer/cpuminer.go
SetNumWorkers
func (m *CPUMiner) SetNumWorkers(numWorkers int32) { if numWorkers == 0 { m.Stop() } // Don't lock until after the first check since Stop does its own // locking. m.Lock() defer m.Unlock() // Use default if provided value is negative. if numWorkers < 0 { m.numWorkers = defaultNumWorkers } else { m.numWorkers = uint32(numWorkers) } // When the miner is already running, notify the controller about the // the change. if m.started { m.updateNumWorkers <- struct{}{} } }
go
func (m *CPUMiner) SetNumWorkers(numWorkers int32) { if numWorkers == 0 { m.Stop() } // Don't lock until after the first check since Stop does its own // locking. m.Lock() defer m.Unlock() // Use default if provided value is negative. if numWorkers < 0 { m.numWorkers = defaultNumWorkers } else { m.numWorkers = uint32(numWorkers) } // When the miner is already running, notify the controller about the // the change. if m.started { m.updateNumWorkers <- struct{}{} } }
[ "func", "(", "m", "*", "CPUMiner", ")", "SetNumWorkers", "(", "numWorkers", "int32", ")", "{", "if", "numWorkers", "==", "0", "{", "m", ".", "Stop", "(", ")", "\n", "}", "\n\n", "// Don't lock until after the first check since Stop does its own", "// locking.", ...
// SetNumWorkers sets the number of workers to create which solve blocks. Any // negative values will cause a default number of workers to be used which is // based on the number of processor cores in the system. A value of 0 will // cause all CPU mining to be stopped. // // This function is safe for concurrent access.
[ "SetNumWorkers", "sets", "the", "number", "of", "workers", "to", "create", "which", "solve", "blocks", ".", "Any", "negative", "values", "will", "cause", "a", "default", "number", "of", "workers", "to", "be", "used", "which", "is", "based", "on", "the", "n...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/cpuminer/cpuminer.go#L508-L530
162,498
btcsuite/btcd
mining/cpuminer/cpuminer.go
NumWorkers
func (m *CPUMiner) NumWorkers() int32 { m.Lock() defer m.Unlock() return int32(m.numWorkers) }
go
func (m *CPUMiner) NumWorkers() int32 { m.Lock() defer m.Unlock() return int32(m.numWorkers) }
[ "func", "(", "m", "*", "CPUMiner", ")", "NumWorkers", "(", ")", "int32", "{", "m", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "Unlock", "(", ")", "\n\n", "return", "int32", "(", "m", ".", "numWorkers", ")", "\n", "}" ]
// NumWorkers returns the number of workers which are running to solve blocks. // // This function is safe for concurrent access.
[ "NumWorkers", "returns", "the", "number", "of", "workers", "which", "are", "running", "to", "solve", "blocks", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/cpuminer/cpuminer.go#L535-L540
162,499
btcsuite/btcd
mining/cpuminer/cpuminer.go
GenerateNBlocks
func (m *CPUMiner) GenerateNBlocks(n uint32) ([]*chainhash.Hash, error) { m.Lock() // Respond with an error if server is already mining. if m.started || m.discreteMining { m.Unlock() return nil, errors.New("Server is already CPU mining. Please call " + "`setgenerate 0` before calling discrete `generate` commands.") } m.started = true m.discreteMining = true m.speedMonitorQuit = make(chan struct{}) m.wg.Add(1) go m.speedMonitor() m.Unlock() log.Tracef("Generating %d blocks", n) i := uint32(0) blockHashes := make([]*chainhash.Hash, n) // Start a ticker which is used to signal checks for stale work and // updates to the speed monitor. ticker := time.NewTicker(time.Second * hashUpdateSecs) defer ticker.Stop() for { // Read updateNumWorkers in case someone tries a `setgenerate` while // we're generating. We can ignore it as the `generate` RPC call only // uses 1 worker. select { case <-m.updateNumWorkers: default: } // Grab the lock used for block submission, since the current block will // be changing and this would otherwise end up building a new block // template on a block that is in the process of becoming stale. m.submitBlockLock.Lock() curHeight := m.g.BestSnapshot().Height // Choose a payment address at random. rand.Seed(time.Now().UnixNano()) payToAddr := m.cfg.MiningAddrs[rand.Intn(len(m.cfg.MiningAddrs))] // Create a new block template using the available transactions // in the memory pool as a source of transactions to potentially // include in the block. template, err := m.g.NewBlockTemplate(payToAddr) m.submitBlockLock.Unlock() if err != nil { errStr := fmt.Sprintf("Failed to create new block "+ "template: %v", err) log.Errorf(errStr) continue } // Attempt to solve the block. The function will exit early // with false when conditions that trigger a stale block, so // a new block template can be generated. When the return is // true a solution was found, so submit the solved block. if m.solveBlock(template.Block, curHeight+1, ticker, nil) { block := btcutil.NewBlock(template.Block) m.submitBlock(block) blockHashes[i] = block.Hash() i++ if i == n { log.Tracef("Generated %d blocks", i) m.Lock() close(m.speedMonitorQuit) m.wg.Wait() m.started = false m.discreteMining = false m.Unlock() return blockHashes, nil } } } }
go
func (m *CPUMiner) GenerateNBlocks(n uint32) ([]*chainhash.Hash, error) { m.Lock() // Respond with an error if server is already mining. if m.started || m.discreteMining { m.Unlock() return nil, errors.New("Server is already CPU mining. Please call " + "`setgenerate 0` before calling discrete `generate` commands.") } m.started = true m.discreteMining = true m.speedMonitorQuit = make(chan struct{}) m.wg.Add(1) go m.speedMonitor() m.Unlock() log.Tracef("Generating %d blocks", n) i := uint32(0) blockHashes := make([]*chainhash.Hash, n) // Start a ticker which is used to signal checks for stale work and // updates to the speed monitor. ticker := time.NewTicker(time.Second * hashUpdateSecs) defer ticker.Stop() for { // Read updateNumWorkers in case someone tries a `setgenerate` while // we're generating. We can ignore it as the `generate` RPC call only // uses 1 worker. select { case <-m.updateNumWorkers: default: } // Grab the lock used for block submission, since the current block will // be changing and this would otherwise end up building a new block // template on a block that is in the process of becoming stale. m.submitBlockLock.Lock() curHeight := m.g.BestSnapshot().Height // Choose a payment address at random. rand.Seed(time.Now().UnixNano()) payToAddr := m.cfg.MiningAddrs[rand.Intn(len(m.cfg.MiningAddrs))] // Create a new block template using the available transactions // in the memory pool as a source of transactions to potentially // include in the block. template, err := m.g.NewBlockTemplate(payToAddr) m.submitBlockLock.Unlock() if err != nil { errStr := fmt.Sprintf("Failed to create new block "+ "template: %v", err) log.Errorf(errStr) continue } // Attempt to solve the block. The function will exit early // with false when conditions that trigger a stale block, so // a new block template can be generated. When the return is // true a solution was found, so submit the solved block. if m.solveBlock(template.Block, curHeight+1, ticker, nil) { block := btcutil.NewBlock(template.Block) m.submitBlock(block) blockHashes[i] = block.Hash() i++ if i == n { log.Tracef("Generated %d blocks", i) m.Lock() close(m.speedMonitorQuit) m.wg.Wait() m.started = false m.discreteMining = false m.Unlock() return blockHashes, nil } } } }
[ "func", "(", "m", "*", "CPUMiner", ")", "GenerateNBlocks", "(", "n", "uint32", ")", "(", "[", "]", "*", "chainhash", ".", "Hash", ",", "error", ")", "{", "m", ".", "Lock", "(", ")", "\n\n", "// Respond with an error if server is already mining.", "if", "m"...
// GenerateNBlocks generates the requested number of blocks. It is self // contained in that it creates block templates and attempts to solve them while // detecting when it is performing stale work and reacting accordingly by // generating a new block template. When a block is solved, it is submitted. // The function returns a list of the hashes of generated blocks.
[ "GenerateNBlocks", "generates", "the", "requested", "number", "of", "blocks", ".", "It", "is", "self", "contained", "in", "that", "it", "creates", "block", "templates", "and", "attempts", "to", "solve", "them", "while", "detecting", "when", "it", "is", "perfor...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/cpuminer/cpuminer.go#L547-L628