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,900
btcsuite/btcd
mempool/estimatefee.go
newEstimateFeeSet
func (ef *FeeEstimator) newEstimateFeeSet() *estimateFeeSet { set := &estimateFeeSet{} capacity := 0 for i, b := range ef.bin { l := len(b) set.bin[i] = uint32(l) capacity += l } set.feeRate = make([]SatoshiPerByte, capacity) i := 0 for _, b := range ef.bin { for _, o := range b { set.feeRate[i] = o.feeRate i++ } } sort.Sort(set) return set }
go
func (ef *FeeEstimator) newEstimateFeeSet() *estimateFeeSet { set := &estimateFeeSet{} capacity := 0 for i, b := range ef.bin { l := len(b) set.bin[i] = uint32(l) capacity += l } set.feeRate = make([]SatoshiPerByte, capacity) i := 0 for _, b := range ef.bin { for _, o := range b { set.feeRate[i] = o.feeRate i++ } } sort.Sort(set) return set }
[ "func", "(", "ef", "*", "FeeEstimator", ")", "newEstimateFeeSet", "(", ")", "*", "estimateFeeSet", "{", "set", ":=", "&", "estimateFeeSet", "{", "}", "\n\n", "capacity", ":=", "0", "\n", "for", "i", ",", "b", ":=", "range", "ef", ".", "bin", "{", "l"...
// newEstimateFeeSet creates a temporary data structure that // can be used to find all fee estimates.
[ "newEstimateFeeSet", "creates", "a", "temporary", "data", "structure", "that", "can", "be", "used", "to", "find", "all", "fee", "estimates", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/estimatefee.go#L509-L532
162,901
btcsuite/btcd
mempool/estimatefee.go
estimates
func (ef *FeeEstimator) estimates() []SatoshiPerByte { set := ef.newEstimateFeeSet() estimates := make([]SatoshiPerByte, estimateFeeDepth) for i := 0; i < estimateFeeDepth; i++ { estimates[i] = set.estimateFee(i + 1) } return estimates }
go
func (ef *FeeEstimator) estimates() []SatoshiPerByte { set := ef.newEstimateFeeSet() estimates := make([]SatoshiPerByte, estimateFeeDepth) for i := 0; i < estimateFeeDepth; i++ { estimates[i] = set.estimateFee(i + 1) } return estimates }
[ "func", "(", "ef", "*", "FeeEstimator", ")", "estimates", "(", ")", "[", "]", "SatoshiPerByte", "{", "set", ":=", "ef", ".", "newEstimateFeeSet", "(", ")", "\n\n", "estimates", ":=", "make", "(", "[", "]", "SatoshiPerByte", ",", "estimateFeeDepth", ")", ...
// estimates returns the set of all fee estimates from 1 to estimateFeeDepth // confirmations from now.
[ "estimates", "returns", "the", "set", "of", "all", "fee", "estimates", "from", "1", "to", "estimateFeeDepth", "confirmations", "from", "now", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/estimatefee.go#L536-L545
162,902
btcsuite/btcd
mempool/estimatefee.go
EstimateFee
func (ef *FeeEstimator) EstimateFee(numBlocks uint32) (BtcPerKilobyte, error) { ef.mtx.Lock() defer ef.mtx.Unlock() // If the number of registered blocks is below the minimum, return // an error. if ef.numBlocksRegistered < ef.minRegisteredBlocks { return -1, errors.New("not enough blocks have been observed") } if numBlocks == 0 { return -1, errors.New("cannot confirm transaction in zero blocks") } if numBlocks > estimateFeeDepth { return -1, fmt.Errorf( "can only estimate fees for up to %d blocks from now", estimateFeeBinSize) } // If there are no cached results, generate them. if ef.cached == nil { ef.cached = ef.estimates() } return ef.cached[int(numBlocks)-1].ToBtcPerKb(), nil }
go
func (ef *FeeEstimator) EstimateFee(numBlocks uint32) (BtcPerKilobyte, error) { ef.mtx.Lock() defer ef.mtx.Unlock() // If the number of registered blocks is below the minimum, return // an error. if ef.numBlocksRegistered < ef.minRegisteredBlocks { return -1, errors.New("not enough blocks have been observed") } if numBlocks == 0 { return -1, errors.New("cannot confirm transaction in zero blocks") } if numBlocks > estimateFeeDepth { return -1, fmt.Errorf( "can only estimate fees for up to %d blocks from now", estimateFeeBinSize) } // If there are no cached results, generate them. if ef.cached == nil { ef.cached = ef.estimates() } return ef.cached[int(numBlocks)-1].ToBtcPerKb(), nil }
[ "func", "(", "ef", "*", "FeeEstimator", ")", "EstimateFee", "(", "numBlocks", "uint32", ")", "(", "BtcPerKilobyte", ",", "error", ")", "{", "ef", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "ef", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "...
// EstimateFee estimates the fee per byte to have a tx confirmed a given // number of blocks from now.
[ "EstimateFee", "estimates", "the", "fee", "per", "byte", "to", "have", "a", "tx", "confirmed", "a", "given", "number", "of", "blocks", "from", "now", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/estimatefee.go#L549-L575
162,903
btcsuite/btcd
mempool/estimatefee.go
RestoreFeeEstimator
func RestoreFeeEstimator(data FeeEstimatorState) (*FeeEstimator, error) { r := bytes.NewReader([]byte(data)) // Check version var version uint32 err := binary.Read(r, binary.BigEndian, &version) if err != nil { return nil, err } if version != estimateFeeSaveVersion { return nil, fmt.Errorf("Incorrect version: expected %d found %d", estimateFeeSaveVersion, version) } ef := &FeeEstimator{ observed: make(map[chainhash.Hash]*observedTransaction), } // Read basic parameters. binary.Read(r, binary.BigEndian, &ef.maxRollback) binary.Read(r, binary.BigEndian, &ef.binSize) binary.Read(r, binary.BigEndian, &ef.maxReplacements) binary.Read(r, binary.BigEndian, &ef.minRegisteredBlocks) binary.Read(r, binary.BigEndian, &ef.lastKnownHeight) binary.Read(r, binary.BigEndian, &ef.numBlocksRegistered) // Read transactions. var numObserved uint32 observed := make(map[uint32]*observedTransaction) binary.Read(r, binary.BigEndian, &numObserved) for i := uint32(0); i < numObserved; i++ { ot, err := deserializeObservedTransaction(r) if err != nil { return nil, err } observed[i] = ot ef.observed[ot.hash] = ot } // Read bins. for i := 0; i < estimateFeeDepth; i++ { var numTransactions uint32 binary.Read(r, binary.BigEndian, &numTransactions) bin := make([]*observedTransaction, numTransactions) for j := uint32(0); j < numTransactions; j++ { var index uint32 binary.Read(r, binary.BigEndian, &index) var exists bool bin[j], exists = observed[index] if !exists { return nil, fmt.Errorf("Invalid transaction reference %d", index) } } ef.bin[i] = bin } // Read dropped transactions. var numDropped uint32 binary.Read(r, binary.BigEndian, &numDropped) ef.dropped = make([]*registeredBlock, numDropped) for i := uint32(0); i < numDropped; i++ { var err error ef.dropped[int(i)], err = deserializeRegisteredBlock(r, observed) if err != nil { return nil, err } } return ef, nil }
go
func RestoreFeeEstimator(data FeeEstimatorState) (*FeeEstimator, error) { r := bytes.NewReader([]byte(data)) // Check version var version uint32 err := binary.Read(r, binary.BigEndian, &version) if err != nil { return nil, err } if version != estimateFeeSaveVersion { return nil, fmt.Errorf("Incorrect version: expected %d found %d", estimateFeeSaveVersion, version) } ef := &FeeEstimator{ observed: make(map[chainhash.Hash]*observedTransaction), } // Read basic parameters. binary.Read(r, binary.BigEndian, &ef.maxRollback) binary.Read(r, binary.BigEndian, &ef.binSize) binary.Read(r, binary.BigEndian, &ef.maxReplacements) binary.Read(r, binary.BigEndian, &ef.minRegisteredBlocks) binary.Read(r, binary.BigEndian, &ef.lastKnownHeight) binary.Read(r, binary.BigEndian, &ef.numBlocksRegistered) // Read transactions. var numObserved uint32 observed := make(map[uint32]*observedTransaction) binary.Read(r, binary.BigEndian, &numObserved) for i := uint32(0); i < numObserved; i++ { ot, err := deserializeObservedTransaction(r) if err != nil { return nil, err } observed[i] = ot ef.observed[ot.hash] = ot } // Read bins. for i := 0; i < estimateFeeDepth; i++ { var numTransactions uint32 binary.Read(r, binary.BigEndian, &numTransactions) bin := make([]*observedTransaction, numTransactions) for j := uint32(0); j < numTransactions; j++ { var index uint32 binary.Read(r, binary.BigEndian, &index) var exists bool bin[j], exists = observed[index] if !exists { return nil, fmt.Errorf("Invalid transaction reference %d", index) } } ef.bin[i] = bin } // Read dropped transactions. var numDropped uint32 binary.Read(r, binary.BigEndian, &numDropped) ef.dropped = make([]*registeredBlock, numDropped) for i := uint32(0); i < numDropped; i++ { var err error ef.dropped[int(i)], err = deserializeRegisteredBlock(r, observed) if err != nil { return nil, err } } return ef, nil }
[ "func", "RestoreFeeEstimator", "(", "data", "FeeEstimatorState", ")", "(", "*", "FeeEstimator", ",", "error", ")", "{", "r", ":=", "bytes", ".", "NewReader", "(", "[", "]", "byte", "(", "data", ")", ")", "\n\n", "// Check version", "var", "version", "uint3...
// RestoreFeeEstimator takes a FeeEstimatorState that was previously // returned by Save and restores it to a FeeEstimator
[ "RestoreFeeEstimator", "takes", "a", "FeeEstimatorState", "that", "was", "previously", "returned", "by", "Save", "and", "restores", "it", "to", "a", "FeeEstimator" ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/estimatefee.go#L680-L749
162,904
btcsuite/btcd
connmgr/seed.go
SeedFromDNS
func SeedFromDNS(chainParams *chaincfg.Params, reqServices wire.ServiceFlag, lookupFn LookupFunc, seedFn OnSeed) { for _, dnsseed := range chainParams.DNSSeeds { var host string if !dnsseed.HasFiltering || reqServices == wire.SFNodeNetwork { host = dnsseed.Host } else { host = fmt.Sprintf("x%x.%s", uint64(reqServices), dnsseed.Host) } go func(host string) { randSource := mrand.New(mrand.NewSource(time.Now().UnixNano())) seedpeers, err := lookupFn(host) if err != nil { log.Infof("DNS discovery failed on seed %s: %v", host, err) return } numPeers := len(seedpeers) log.Infof("%d addresses found from DNS seed %s", numPeers, host) if numPeers == 0 { return } addresses := make([]*wire.NetAddress, len(seedpeers)) // if this errors then we have *real* problems intPort, _ := strconv.Atoi(chainParams.DefaultPort) for i, peer := range seedpeers { addresses[i] = wire.NewNetAddressTimestamp( // bitcoind seeds with addresses from // a time randomly selected between 3 // and 7 days ago. time.Now().Add(-1*time.Second*time.Duration(secondsIn3Days+ randSource.Int31n(secondsIn4Days))), 0, peer, uint16(intPort)) } seedFn(addresses) }(host) } }
go
func SeedFromDNS(chainParams *chaincfg.Params, reqServices wire.ServiceFlag, lookupFn LookupFunc, seedFn OnSeed) { for _, dnsseed := range chainParams.DNSSeeds { var host string if !dnsseed.HasFiltering || reqServices == wire.SFNodeNetwork { host = dnsseed.Host } else { host = fmt.Sprintf("x%x.%s", uint64(reqServices), dnsseed.Host) } go func(host string) { randSource := mrand.New(mrand.NewSource(time.Now().UnixNano())) seedpeers, err := lookupFn(host) if err != nil { log.Infof("DNS discovery failed on seed %s: %v", host, err) return } numPeers := len(seedpeers) log.Infof("%d addresses found from DNS seed %s", numPeers, host) if numPeers == 0 { return } addresses := make([]*wire.NetAddress, len(seedpeers)) // if this errors then we have *real* problems intPort, _ := strconv.Atoi(chainParams.DefaultPort) for i, peer := range seedpeers { addresses[i] = wire.NewNetAddressTimestamp( // bitcoind seeds with addresses from // a time randomly selected between 3 // and 7 days ago. time.Now().Add(-1*time.Second*time.Duration(secondsIn3Days+ randSource.Int31n(secondsIn4Days))), 0, peer, uint16(intPort)) } seedFn(addresses) }(host) } }
[ "func", "SeedFromDNS", "(", "chainParams", "*", "chaincfg", ".", "Params", ",", "reqServices", "wire", ".", "ServiceFlag", ",", "lookupFn", "LookupFunc", ",", "seedFn", "OnSeed", ")", "{", "for", "_", ",", "dnsseed", ":=", "range", "chainParams", ".", "DNSSe...
// SeedFromDNS uses DNS seeding to populate the address manager with peers.
[ "SeedFromDNS", "uses", "DNS", "seeding", "to", "populate", "the", "address", "manager", "with", "peers", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/connmgr/seed.go#L33-L75
162,905
btcsuite/btcd
btcec/field.go
String
func (f fieldVal) String() string { t := new(fieldVal).Set(&f).Normalize() return hex.EncodeToString(t.Bytes()[:]) }
go
func (f fieldVal) String() string { t := new(fieldVal).Set(&f).Normalize() return hex.EncodeToString(t.Bytes()[:]) }
[ "func", "(", "f", "fieldVal", ")", "String", "(", ")", "string", "{", "t", ":=", "new", "(", "fieldVal", ")", ".", "Set", "(", "&", "f", ")", ".", "Normalize", "(", ")", "\n", "return", "hex", ".", "EncodeToString", "(", "t", ".", "Bytes", "(", ...
// String returns the field value as a human-readable hex string.
[ "String", "returns", "the", "field", "value", "as", "a", "human", "-", "readable", "hex", "string", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/field.go#L140-L143
162,906
btcsuite/btcd
btcec/field.go
Zero
func (f *fieldVal) Zero() { f.n[0] = 0 f.n[1] = 0 f.n[2] = 0 f.n[3] = 0 f.n[4] = 0 f.n[5] = 0 f.n[6] = 0 f.n[7] = 0 f.n[8] = 0 f.n[9] = 0 }
go
func (f *fieldVal) Zero() { f.n[0] = 0 f.n[1] = 0 f.n[2] = 0 f.n[3] = 0 f.n[4] = 0 f.n[5] = 0 f.n[6] = 0 f.n[7] = 0 f.n[8] = 0 f.n[9] = 0 }
[ "func", "(", "f", "*", "fieldVal", ")", "Zero", "(", ")", "{", "f", ".", "n", "[", "0", "]", "=", "0", "\n", "f", ".", "n", "[", "1", "]", "=", "0", "\n", "f", ".", "n", "[", "2", "]", "=", "0", "\n", "f", ".", "n", "[", "3", "]", ...
// Zero sets the field value to zero. A newly created field value is already // set to zero. This function can be useful to clear an existing field value // for reuse.
[ "Zero", "sets", "the", "field", "value", "to", "zero", ".", "A", "newly", "created", "field", "value", "is", "already", "set", "to", "zero", ".", "This", "function", "can", "be", "useful", "to", "clear", "an", "existing", "field", "value", "for", "reuse"...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/field.go#L148-L159
162,907
btcsuite/btcd
btcec/field.go
Bytes
func (f *fieldVal) Bytes() *[32]byte { b := new([32]byte) f.PutBytes(b) return b }
go
func (f *fieldVal) Bytes() *[32]byte { b := new([32]byte) f.PutBytes(b) return b }
[ "func", "(", "f", "*", "fieldVal", ")", "Bytes", "(", ")", "*", "[", "32", "]", "byte", "{", "b", ":=", "new", "(", "[", "32", "]", "byte", ")", "\n", "f", ".", "PutBytes", "(", "b", ")", "\n", "return", "b", "\n", "}" ]
// Bytes unpacks the field value to a 32-byte big-endian value. See PutBytes // for a variant that allows the a buffer to be passed which can be useful to // to cut down on the number of allocations by allowing the caller to reuse a // buffer. // // The field value must be normalized for this function to return correct // result.
[ "Bytes", "unpacks", "the", "field", "value", "to", "a", "32", "-", "byte", "big", "-", "endian", "value", ".", "See", "PutBytes", "for", "a", "variant", "that", "allows", "the", "a", "buffer", "to", "be", "passed", "which", "can", "be", "useful", "to",...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/field.go#L423-L427
162,908
btcsuite/btcd
btcec/field.go
IsZero
func (f *fieldVal) IsZero() bool { // The value can only be zero if no bits are set in any of the words. // This is a constant time implementation. bits := f.n[0] | f.n[1] | f.n[2] | f.n[3] | f.n[4] | f.n[5] | f.n[6] | f.n[7] | f.n[8] | f.n[9] return bits == 0 }
go
func (f *fieldVal) IsZero() bool { // The value can only be zero if no bits are set in any of the words. // This is a constant time implementation. bits := f.n[0] | f.n[1] | f.n[2] | f.n[3] | f.n[4] | f.n[5] | f.n[6] | f.n[7] | f.n[8] | f.n[9] return bits == 0 }
[ "func", "(", "f", "*", "fieldVal", ")", "IsZero", "(", ")", "bool", "{", "// The value can only be zero if no bits are set in any of the words.", "// This is a constant time implementation.", "bits", ":=", "f", ".", "n", "[", "0", "]", "|", "f", ".", "n", "[", "1"...
// IsZero returns whether or not the field value is equal to zero.
[ "IsZero", "returns", "whether", "or", "not", "the", "field", "value", "is", "equal", "to", "zero", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/field.go#L430-L437
162,909
btcsuite/btcd
btcec/field.go
Equals
func (f *fieldVal) Equals(val *fieldVal) bool { // Xor only sets bits when they are different, so the two field values // can only be the same if no bits are set after xoring each word. // This is a constant time implementation. bits := (f.n[0] ^ val.n[0]) | (f.n[1] ^ val.n[1]) | (f.n[2] ^ val.n[2]) | (f.n[3] ^ val.n[3]) | (f.n[4] ^ val.n[4]) | (f.n[5] ^ val.n[5]) | (f.n[6] ^ val.n[6]) | (f.n[7] ^ val.n[7]) | (f.n[8] ^ val.n[8]) | (f.n[9] ^ val.n[9]) return bits == 0 }
go
func (f *fieldVal) Equals(val *fieldVal) bool { // Xor only sets bits when they are different, so the two field values // can only be the same if no bits are set after xoring each word. // This is a constant time implementation. bits := (f.n[0] ^ val.n[0]) | (f.n[1] ^ val.n[1]) | (f.n[2] ^ val.n[2]) | (f.n[3] ^ val.n[3]) | (f.n[4] ^ val.n[4]) | (f.n[5] ^ val.n[5]) | (f.n[6] ^ val.n[6]) | (f.n[7] ^ val.n[7]) | (f.n[8] ^ val.n[8]) | (f.n[9] ^ val.n[9]) return bits == 0 }
[ "func", "(", "f", "*", "fieldVal", ")", "Equals", "(", "val", "*", "fieldVal", ")", "bool", "{", "// Xor only sets bits when they are different, so the two field values", "// can only be the same if no bits are set after xoring each word.", "// This is a constant time implementation....
// Equals returns whether or not the two field values are the same. Both // field values being compared must be normalized for this function to return // the correct result.
[ "Equals", "returns", "whether", "or", "not", "the", "two", "field", "values", "are", "the", "same", ".", "Both", "field", "values", "being", "compared", "must", "be", "normalized", "for", "this", "function", "to", "return", "the", "correct", "result", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/field.go#L451-L461
162,910
btcsuite/btcd
service_windows.go
logServiceStartOfDay
func logServiceStartOfDay(srvr *server) { var message string message += fmt.Sprintf("Version %s\n", version()) message += fmt.Sprintf("Configuration directory: %s\n", defaultHomeDir) message += fmt.Sprintf("Configuration file: %s\n", cfg.ConfigFile) message += fmt.Sprintf("Data directory: %s\n", cfg.DataDir) elog.Info(1, message) }
go
func logServiceStartOfDay(srvr *server) { var message string message += fmt.Sprintf("Version %s\n", version()) message += fmt.Sprintf("Configuration directory: %s\n", defaultHomeDir) message += fmt.Sprintf("Configuration file: %s\n", cfg.ConfigFile) message += fmt.Sprintf("Data directory: %s\n", cfg.DataDir) elog.Info(1, message) }
[ "func", "logServiceStartOfDay", "(", "srvr", "*", "server", ")", "{", "var", "message", "string", "\n", "message", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "version", "(", ")", ")", "\n", "message", "+=", "fmt", ".", "Sprintf", "(", ...
// logServiceStartOfDay logs information about btcd when the main server has // been started to the Windows event log.
[ "logServiceStartOfDay", "logs", "information", "about", "btcd", "when", "the", "main", "server", "has", "been", "started", "to", "the", "Windows", "event", "log", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/service_windows.go#L37-L45
162,911
btcsuite/btcd
service_windows.go
installService
func installService() error { // Get the path of the current executable. This is needed because // os.Args[0] can vary depending on how the application was launched. // For example, under cmd.exe it will only be the name of the app // without the path or extension, but under mingw it will be the full // path including the extension. exePath, err := filepath.Abs(os.Args[0]) if err != nil { return err } if filepath.Ext(exePath) == "" { exePath += ".exe" } // Connect to the windows service manager. serviceManager, err := mgr.Connect() if err != nil { return err } defer serviceManager.Disconnect() // Ensure the service doesn't already exist. service, err := serviceManager.OpenService(svcName) if err == nil { service.Close() return fmt.Errorf("service %s already exists", svcName) } // Install the service. service, err = serviceManager.CreateService(svcName, exePath, mgr.Config{ DisplayName: svcDisplayName, Description: svcDesc, }) if err != nil { return err } defer service.Close() // Support events to the event log using the standard "standard" Windows // EventCreate.exe message file. This allows easy logging of custom // messges instead of needing to create our own message catalog. eventlog.Remove(svcName) eventsSupported := uint32(eventlog.Error | eventlog.Warning | eventlog.Info) return eventlog.InstallAsEventCreate(svcName, eventsSupported) }
go
func installService() error { // Get the path of the current executable. This is needed because // os.Args[0] can vary depending on how the application was launched. // For example, under cmd.exe it will only be the name of the app // without the path or extension, but under mingw it will be the full // path including the extension. exePath, err := filepath.Abs(os.Args[0]) if err != nil { return err } if filepath.Ext(exePath) == "" { exePath += ".exe" } // Connect to the windows service manager. serviceManager, err := mgr.Connect() if err != nil { return err } defer serviceManager.Disconnect() // Ensure the service doesn't already exist. service, err := serviceManager.OpenService(svcName) if err == nil { service.Close() return fmt.Errorf("service %s already exists", svcName) } // Install the service. service, err = serviceManager.CreateService(svcName, exePath, mgr.Config{ DisplayName: svcDisplayName, Description: svcDesc, }) if err != nil { return err } defer service.Close() // Support events to the event log using the standard "standard" Windows // EventCreate.exe message file. This allows easy logging of custom // messges instead of needing to create our own message catalog. eventlog.Remove(svcName) eventsSupported := uint32(eventlog.Error | eventlog.Warning | eventlog.Info) return eventlog.InstallAsEventCreate(svcName, eventsSupported) }
[ "func", "installService", "(", ")", "error", "{", "// Get the path of the current executable. This is needed because", "// os.Args[0] can vary depending on how the application was launched.", "// For example, under cmd.exe it will only be the name of the app", "// without the path or extension, b...
// installService attempts to install the btcd service. Typically this should // be done by the msi installer, but it is provided here since it can be useful // for development.
[ "installService", "attempts", "to", "install", "the", "btcd", "service", ".", "Typically", "this", "should", "be", "done", "by", "the", "msi", "installer", "but", "it", "is", "provided", "here", "since", "it", "can", "be", "useful", "for", "development", "."...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/service_windows.go#L116-L160
162,912
btcsuite/btcd
service_windows.go
removeService
func removeService() error { // Connect to the windows service manager. serviceManager, err := mgr.Connect() if err != nil { return err } defer serviceManager.Disconnect() // Ensure the service exists. service, err := serviceManager.OpenService(svcName) if err != nil { return fmt.Errorf("service %s is not installed", svcName) } defer service.Close() // Remove the service. return service.Delete() }
go
func removeService() error { // Connect to the windows service manager. serviceManager, err := mgr.Connect() if err != nil { return err } defer serviceManager.Disconnect() // Ensure the service exists. service, err := serviceManager.OpenService(svcName) if err != nil { return fmt.Errorf("service %s is not installed", svcName) } defer service.Close() // Remove the service. return service.Delete() }
[ "func", "removeService", "(", ")", "error", "{", "// Connect to the windows service manager.", "serviceManager", ",", "err", ":=", "mgr", ".", "Connect", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "serviceManager"...
// removeService attempts to uninstall the btcd service. Typically this should // be done by the msi uninstaller, but it is provided here since it can be // useful for development. Not the eventlog entry is intentionally not removed // since it would invalidate any existing event log messages.
[ "removeService", "attempts", "to", "uninstall", "the", "btcd", "service", ".", "Typically", "this", "should", "be", "done", "by", "the", "msi", "uninstaller", "but", "it", "is", "provided", "here", "since", "it", "can", "be", "useful", "for", "development", ...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/service_windows.go#L166-L183
162,913
btcsuite/btcd
service_windows.go
startService
func startService() error { // Connect to the windows service manager. serviceManager, err := mgr.Connect() if err != nil { return err } defer serviceManager.Disconnect() service, err := serviceManager.OpenService(svcName) if err != nil { return fmt.Errorf("could not access service: %v", err) } defer service.Close() err = service.Start(os.Args) if err != nil { return fmt.Errorf("could not start service: %v", err) } return nil }
go
func startService() error { // Connect to the windows service manager. serviceManager, err := mgr.Connect() if err != nil { return err } defer serviceManager.Disconnect() service, err := serviceManager.OpenService(svcName) if err != nil { return fmt.Errorf("could not access service: %v", err) } defer service.Close() err = service.Start(os.Args) if err != nil { return fmt.Errorf("could not start service: %v", err) } return nil }
[ "func", "startService", "(", ")", "error", "{", "// Connect to the windows service manager.", "serviceManager", ",", "err", ":=", "mgr", ".", "Connect", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "serviceManager",...
// startService attempts to start the btcd service.
[ "startService", "attempts", "to", "start", "the", "btcd", "service", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/service_windows.go#L186-L206
162,914
btcsuite/btcd
service_windows.go
controlService
func controlService(c svc.Cmd, to svc.State) error { // Connect to the windows service manager. serviceManager, err := mgr.Connect() if err != nil { return err } defer serviceManager.Disconnect() service, err := serviceManager.OpenService(svcName) if err != nil { return fmt.Errorf("could not access service: %v", err) } defer service.Close() status, err := service.Control(c) if err != nil { return fmt.Errorf("could not send control=%d: %v", c, err) } // Send the control message. timeout := time.Now().Add(10 * time.Second) for status.State != to { if timeout.Before(time.Now()) { return fmt.Errorf("timeout waiting for service to go "+ "to state=%d", to) } time.Sleep(300 * time.Millisecond) status, err = service.Query() if err != nil { return fmt.Errorf("could not retrieve service "+ "status: %v", err) } } return nil }
go
func controlService(c svc.Cmd, to svc.State) error { // Connect to the windows service manager. serviceManager, err := mgr.Connect() if err != nil { return err } defer serviceManager.Disconnect() service, err := serviceManager.OpenService(svcName) if err != nil { return fmt.Errorf("could not access service: %v", err) } defer service.Close() status, err := service.Control(c) if err != nil { return fmt.Errorf("could not send control=%d: %v", c, err) } // Send the control message. timeout := time.Now().Add(10 * time.Second) for status.State != to { if timeout.Before(time.Now()) { return fmt.Errorf("timeout waiting for service to go "+ "to state=%d", to) } time.Sleep(300 * time.Millisecond) status, err = service.Query() if err != nil { return fmt.Errorf("could not retrieve service "+ "status: %v", err) } } return nil }
[ "func", "controlService", "(", "c", "svc", ".", "Cmd", ",", "to", "svc", ".", "State", ")", "error", "{", "// Connect to the windows service manager.", "serviceManager", ",", "err", ":=", "mgr", ".", "Connect", "(", ")", "\n", "if", "err", "!=", "nil", "{"...
// controlService allows commands which change the status of the service. It // also waits for up to 10 seconds for the service to change to the passed // state.
[ "controlService", "allows", "commands", "which", "change", "the", "status", "of", "the", "service", ".", "It", "also", "waits", "for", "up", "to", "10", "seconds", "for", "the", "service", "to", "change", "to", "the", "passed", "state", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/service_windows.go#L211-L246
162,915
btcsuite/btcd
service_windows.go
performServiceCommand
func performServiceCommand(command string) error { var err error switch command { case "install": err = installService() case "remove": err = removeService() case "start": err = startService() case "stop": err = controlService(svc.Stop, svc.Stopped) default: err = fmt.Errorf("invalid service command [%s]", command) } return err }
go
func performServiceCommand(command string) error { var err error switch command { case "install": err = installService() case "remove": err = removeService() case "start": err = startService() case "stop": err = controlService(svc.Stop, svc.Stopped) default: err = fmt.Errorf("invalid service command [%s]", command) } return err }
[ "func", "performServiceCommand", "(", "command", "string", ")", "error", "{", "var", "err", "error", "\n", "switch", "command", "{", "case", "\"", "\"", ":", "err", "=", "installService", "(", ")", "\n\n", "case", "\"", "\"", ":", "err", "=", "removeServ...
// performServiceCommand attempts to run one of the supported service commands // provided on the command line via the service command flag. An appropriate // error is returned if an invalid command is specified.
[ "performServiceCommand", "attempts", "to", "run", "one", "of", "the", "supported", "service", "commands", "provided", "on", "the", "command", "line", "via", "the", "service", "command", "flag", ".", "An", "appropriate", "error", "is", "returned", "if", "an", "...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/service_windows.go#L251-L271
162,916
btcsuite/btcd
cmd/findcheckpoint/config.go
validDbType
func validDbType(dbType string) bool { for _, knownType := range knownDbTypes { if dbType == knownType { return true } } return false }
go
func validDbType(dbType string) bool { for _, knownType := range knownDbTypes { if dbType == knownType { return true } } return false }
[ "func", "validDbType", "(", "dbType", "string", ")", "bool", "{", "for", "_", ",", "knownType", ":=", "range", "knownDbTypes", "{", "if", "dbType", "==", "knownType", "{", "return", "true", "\n", "}", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// validDbType returns whether or not dbType is a supported database type.
[ "validDbType", "returns", "whether", "or", "not", "dbType", "is", "a", "supported", "database", "type", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/cmd/findcheckpoint/config.go#L48-L56
162,917
btcsuite/btcd
cmd/findcheckpoint/config.go
loadConfig
func loadConfig() (*config, []string, error) { // Default config. cfg := config{ DataDir: defaultDataDir, DbType: defaultDbType, NumCandidates: defaultNumCandidates, } // Parse command line options. parser := flags.NewParser(&cfg, flags.Default) remainingArgs, err := parser.Parse() if err != nil { if e, ok := err.(*flags.Error); !ok || e.Type != flags.ErrHelp { parser.WriteHelp(os.Stderr) } return nil, nil, err } // Multiple networks can't be selected simultaneously. funcName := "loadConfig" numNets := 0 // Count number of network flags passed; assign active network params // while we're at it if cfg.TestNet3 { numNets++ activeNetParams = &chaincfg.TestNet3Params } if cfg.RegressionTest { numNets++ activeNetParams = &chaincfg.RegressionNetParams } if cfg.SimNet { numNets++ activeNetParams = &chaincfg.SimNetParams } if numNets > 1 { str := "%s: The testnet, regtest, and simnet params can't be " + "used together -- choose one of the three" err := fmt.Errorf(str, funcName) fmt.Fprintln(os.Stderr, err) parser.WriteHelp(os.Stderr) return nil, nil, err } // Validate database type. if !validDbType(cfg.DbType) { str := "%s: The specified database type [%v] is invalid -- " + "supported types %v" err := fmt.Errorf(str, "loadConfig", cfg.DbType, knownDbTypes) fmt.Fprintln(os.Stderr, err) parser.WriteHelp(os.Stderr) return nil, nil, err } // Append the network type to the data directory so it is "namespaced" // per network. In addition to the block database, there are other // pieces of data that are saved to disk such as address manager state. // All data is specific to a network, so namespacing the data directory // means each individual piece of serialized data does not have to // worry about changing names per network and such. cfg.DataDir = filepath.Join(cfg.DataDir, netName(activeNetParams)) // Validate the number of candidates. if cfg.NumCandidates < minCandidates || cfg.NumCandidates > maxCandidates { str := "%s: The specified number of candidates is out of " + "range -- parsed [%v]" err = fmt.Errorf(str, "loadConfig", cfg.NumCandidates) fmt.Fprintln(os.Stderr, err) parser.WriteHelp(os.Stderr) return nil, nil, err } return &cfg, remainingArgs, nil }
go
func loadConfig() (*config, []string, error) { // Default config. cfg := config{ DataDir: defaultDataDir, DbType: defaultDbType, NumCandidates: defaultNumCandidates, } // Parse command line options. parser := flags.NewParser(&cfg, flags.Default) remainingArgs, err := parser.Parse() if err != nil { if e, ok := err.(*flags.Error); !ok || e.Type != flags.ErrHelp { parser.WriteHelp(os.Stderr) } return nil, nil, err } // Multiple networks can't be selected simultaneously. funcName := "loadConfig" numNets := 0 // Count number of network flags passed; assign active network params // while we're at it if cfg.TestNet3 { numNets++ activeNetParams = &chaincfg.TestNet3Params } if cfg.RegressionTest { numNets++ activeNetParams = &chaincfg.RegressionNetParams } if cfg.SimNet { numNets++ activeNetParams = &chaincfg.SimNetParams } if numNets > 1 { str := "%s: The testnet, regtest, and simnet params can't be " + "used together -- choose one of the three" err := fmt.Errorf(str, funcName) fmt.Fprintln(os.Stderr, err) parser.WriteHelp(os.Stderr) return nil, nil, err } // Validate database type. if !validDbType(cfg.DbType) { str := "%s: The specified database type [%v] is invalid -- " + "supported types %v" err := fmt.Errorf(str, "loadConfig", cfg.DbType, knownDbTypes) fmt.Fprintln(os.Stderr, err) parser.WriteHelp(os.Stderr) return nil, nil, err } // Append the network type to the data directory so it is "namespaced" // per network. In addition to the block database, there are other // pieces of data that are saved to disk such as address manager state. // All data is specific to a network, so namespacing the data directory // means each individual piece of serialized data does not have to // worry about changing names per network and such. cfg.DataDir = filepath.Join(cfg.DataDir, netName(activeNetParams)) // Validate the number of candidates. if cfg.NumCandidates < minCandidates || cfg.NumCandidates > maxCandidates { str := "%s: The specified number of candidates is out of " + "range -- parsed [%v]" err = fmt.Errorf(str, "loadConfig", cfg.NumCandidates) fmt.Fprintln(os.Stderr, err) parser.WriteHelp(os.Stderr) return nil, nil, err } return &cfg, remainingArgs, nil }
[ "func", "loadConfig", "(", ")", "(", "*", "config", ",", "[", "]", "string", ",", "error", ")", "{", "// Default config.", "cfg", ":=", "config", "{", "DataDir", ":", "defaultDataDir", ",", "DbType", ":", "defaultDbType", ",", "NumCandidates", ":", "defaul...
// loadConfig initializes and parses the config using command line options.
[ "loadConfig", "initializes", "and", "parses", "the", "config", "using", "command", "line", "options", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/cmd/findcheckpoint/config.go#L77-L150
162,918
btcsuite/btcd
mempool/mempool.go
RemoveOrphan
func (mp *TxPool) RemoveOrphan(tx *btcutil.Tx) { mp.mtx.Lock() mp.removeOrphan(tx, false) mp.mtx.Unlock() }
go
func (mp *TxPool) RemoveOrphan(tx *btcutil.Tx) { mp.mtx.Lock() mp.removeOrphan(tx, false) mp.mtx.Unlock() }
[ "func", "(", "mp", "*", "TxPool", ")", "RemoveOrphan", "(", "tx", "*", "btcutil", ".", "Tx", ")", "{", "mp", ".", "mtx", ".", "Lock", "(", ")", "\n", "mp", ".", "removeOrphan", "(", "tx", ",", "false", ")", "\n", "mp", ".", "mtx", ".", "Unlock"...
// RemoveOrphan removes the passed orphan transaction from the orphan pool and // previous orphan index. // // This function is safe for concurrent access.
[ "RemoveOrphan", "removes", "the", "passed", "orphan", "transaction", "from", "the", "orphan", "pool", "and", "previous", "orphan", "index", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/mempool.go#L228-L232
162,919
btcsuite/btcd
mempool/mempool.go
RemoveOrphansByTag
func (mp *TxPool) RemoveOrphansByTag(tag Tag) uint64 { var numEvicted uint64 mp.mtx.Lock() for _, otx := range mp.orphans { if otx.tag == tag { mp.removeOrphan(otx.tx, true) numEvicted++ } } mp.mtx.Unlock() return numEvicted }
go
func (mp *TxPool) RemoveOrphansByTag(tag Tag) uint64 { var numEvicted uint64 mp.mtx.Lock() for _, otx := range mp.orphans { if otx.tag == tag { mp.removeOrphan(otx.tx, true) numEvicted++ } } mp.mtx.Unlock() return numEvicted }
[ "func", "(", "mp", "*", "TxPool", ")", "RemoveOrphansByTag", "(", "tag", "Tag", ")", "uint64", "{", "var", "numEvicted", "uint64", "\n", "mp", ".", "mtx", ".", "Lock", "(", ")", "\n", "for", "_", ",", "otx", ":=", "range", "mp", ".", "orphans", "{"...
// RemoveOrphansByTag removes all orphan transactions tagged with the provided // identifier. // // This function is safe for concurrent access.
[ "RemoveOrphansByTag", "removes", "all", "orphan", "transactions", "tagged", "with", "the", "provided", "identifier", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/mempool.go#L238-L249
162,920
btcsuite/btcd
mempool/mempool.go
IsTransactionInPool
func (mp *TxPool) IsTransactionInPool(hash *chainhash.Hash) bool { // Protect concurrent access. mp.mtx.RLock() inPool := mp.isTransactionInPool(hash) mp.mtx.RUnlock() return inPool }
go
func (mp *TxPool) IsTransactionInPool(hash *chainhash.Hash) bool { // Protect concurrent access. mp.mtx.RLock() inPool := mp.isTransactionInPool(hash) mp.mtx.RUnlock() return inPool }
[ "func", "(", "mp", "*", "TxPool", ")", "IsTransactionInPool", "(", "hash", "*", "chainhash", ".", "Hash", ")", "bool", "{", "// Protect concurrent access.", "mp", ".", "mtx", ".", "RLock", "(", ")", "\n", "inPool", ":=", "mp", ".", "isTransactionInPool", "...
// IsTransactionInPool returns whether or not the passed transaction already // exists in the main pool. // // This function is safe for concurrent access.
[ "IsTransactionInPool", "returns", "whether", "or", "not", "the", "passed", "transaction", "already", "exists", "in", "the", "main", "pool", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/mempool.go#L395-L402
162,921
btcsuite/btcd
mempool/mempool.go
IsOrphanInPool
func (mp *TxPool) IsOrphanInPool(hash *chainhash.Hash) bool { // Protect concurrent access. mp.mtx.RLock() inPool := mp.isOrphanInPool(hash) mp.mtx.RUnlock() return inPool }
go
func (mp *TxPool) IsOrphanInPool(hash *chainhash.Hash) bool { // Protect concurrent access. mp.mtx.RLock() inPool := mp.isOrphanInPool(hash) mp.mtx.RUnlock() return inPool }
[ "func", "(", "mp", "*", "TxPool", ")", "IsOrphanInPool", "(", "hash", "*", "chainhash", ".", "Hash", ")", "bool", "{", "// Protect concurrent access.", "mp", ".", "mtx", ".", "RLock", "(", ")", "\n", "inPool", ":=", "mp", ".", "isOrphanInPool", "(", "has...
// IsOrphanInPool returns whether or not the passed transaction already exists // in the orphan pool. // // This function is safe for concurrent access.
[ "IsOrphanInPool", "returns", "whether", "or", "not", "the", "passed", "transaction", "already", "exists", "in", "the", "orphan", "pool", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/mempool.go#L420-L427
162,922
btcsuite/btcd
mempool/mempool.go
HaveTransaction
func (mp *TxPool) HaveTransaction(hash *chainhash.Hash) bool { // Protect concurrent access. mp.mtx.RLock() haveTx := mp.haveTransaction(hash) mp.mtx.RUnlock() return haveTx }
go
func (mp *TxPool) HaveTransaction(hash *chainhash.Hash) bool { // Protect concurrent access. mp.mtx.RLock() haveTx := mp.haveTransaction(hash) mp.mtx.RUnlock() return haveTx }
[ "func", "(", "mp", "*", "TxPool", ")", "HaveTransaction", "(", "hash", "*", "chainhash", ".", "Hash", ")", "bool", "{", "// Protect concurrent access.", "mp", ".", "mtx", ".", "RLock", "(", ")", "\n", "haveTx", ":=", "mp", ".", "haveTransaction", "(", "h...
// HaveTransaction returns whether or not the passed transaction already exists // in the main pool or in the orphan pool. // // This function is safe for concurrent access.
[ "HaveTransaction", "returns", "whether", "or", "not", "the", "passed", "transaction", "already", "exists", "in", "the", "main", "pool", "or", "in", "the", "orphan", "pool", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/mempool.go#L441-L448
162,923
btcsuite/btcd
mempool/mempool.go
RemoveTransaction
func (mp *TxPool) RemoveTransaction(tx *btcutil.Tx, removeRedeemers bool) { // Protect concurrent access. mp.mtx.Lock() mp.removeTransaction(tx, removeRedeemers) mp.mtx.Unlock() }
go
func (mp *TxPool) RemoveTransaction(tx *btcutil.Tx, removeRedeemers bool) { // Protect concurrent access. mp.mtx.Lock() mp.removeTransaction(tx, removeRedeemers) mp.mtx.Unlock() }
[ "func", "(", "mp", "*", "TxPool", ")", "RemoveTransaction", "(", "tx", "*", "btcutil", ".", "Tx", ",", "removeRedeemers", "bool", ")", "{", "// Protect concurrent access.", "mp", ".", "mtx", ".", "Lock", "(", ")", "\n", "mp", ".", "removeTransaction", "(",...
// RemoveTransaction removes the passed transaction from the mempool. When the // removeRedeemers flag is set, any transactions that redeem outputs from the // removed transaction will also be removed recursively from the mempool, as // they would otherwise become orphans. // // This function is safe for concurrent access.
[ "RemoveTransaction", "removes", "the", "passed", "transaction", "from", "the", "mempool", ".", "When", "the", "removeRedeemers", "flag", "is", "set", "any", "transactions", "that", "redeem", "outputs", "from", "the", "removed", "transaction", "will", "also", "be",...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/mempool.go#L489-L494
162,924
btcsuite/btcd
mempool/mempool.go
RemoveDoubleSpends
func (mp *TxPool) RemoveDoubleSpends(tx *btcutil.Tx) { // Protect concurrent access. mp.mtx.Lock() for _, txIn := range tx.MsgTx().TxIn { if txRedeemer, ok := mp.outpoints[txIn.PreviousOutPoint]; ok { if !txRedeemer.Hash().IsEqual(tx.Hash()) { mp.removeTransaction(txRedeemer, true) } } } mp.mtx.Unlock() }
go
func (mp *TxPool) RemoveDoubleSpends(tx *btcutil.Tx) { // Protect concurrent access. mp.mtx.Lock() for _, txIn := range tx.MsgTx().TxIn { if txRedeemer, ok := mp.outpoints[txIn.PreviousOutPoint]; ok { if !txRedeemer.Hash().IsEqual(tx.Hash()) { mp.removeTransaction(txRedeemer, true) } } } mp.mtx.Unlock() }
[ "func", "(", "mp", "*", "TxPool", ")", "RemoveDoubleSpends", "(", "tx", "*", "btcutil", ".", "Tx", ")", "{", "// Protect concurrent access.", "mp", ".", "mtx", ".", "Lock", "(", ")", "\n", "for", "_", ",", "txIn", ":=", "range", "tx", ".", "MsgTx", "...
// RemoveDoubleSpends removes all transactions which spend outputs spent by the // passed transaction from the memory pool. Removing those transactions then // leads to removing all transactions which rely on them, recursively. This is // necessary when a block is connected to the main chain because the block may // contain transactions which were previously unknown to the memory pool. // // This function is safe for concurrent access.
[ "RemoveDoubleSpends", "removes", "all", "transactions", "which", "spend", "outputs", "spent", "by", "the", "passed", "transaction", "from", "the", "memory", "pool", ".", "Removing", "those", "transactions", "then", "leads", "to", "removing", "all", "transactions", ...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/mempool.go#L503-L514
162,925
btcsuite/btcd
mempool/mempool.go
CheckSpend
func (mp *TxPool) CheckSpend(op wire.OutPoint) *btcutil.Tx { mp.mtx.RLock() txR := mp.outpoints[op] mp.mtx.RUnlock() return txR }
go
func (mp *TxPool) CheckSpend(op wire.OutPoint) *btcutil.Tx { mp.mtx.RLock() txR := mp.outpoints[op] mp.mtx.RUnlock() return txR }
[ "func", "(", "mp", "*", "TxPool", ")", "CheckSpend", "(", "op", "wire", ".", "OutPoint", ")", "*", "btcutil", ".", "Tx", "{", "mp", ".", "mtx", ".", "RLock", "(", ")", "\n", "txR", ":=", "mp", ".", "outpoints", "[", "op", "]", "\n", "mp", ".", ...
// CheckSpend checks whether the passed outpoint is already spent by a // transaction in the mempool. If that's the case the spending transaction will // be returned, if not nil will be returned.
[ "CheckSpend", "checks", "whether", "the", "passed", "outpoint", "is", "already", "spent", "by", "a", "transaction", "in", "the", "mempool", ".", "If", "that", "s", "the", "case", "the", "spending", "transaction", "will", "be", "returned", "if", "not", "nil",...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/mempool.go#L577-L583
162,926
btcsuite/btcd
mempool/mempool.go
FetchTransaction
func (mp *TxPool) FetchTransaction(txHash *chainhash.Hash) (*btcutil.Tx, error) { // Protect concurrent access. mp.mtx.RLock() txDesc, exists := mp.pool[*txHash] mp.mtx.RUnlock() if exists { return txDesc.Tx, nil } return nil, fmt.Errorf("transaction is not in the pool") }
go
func (mp *TxPool) FetchTransaction(txHash *chainhash.Hash) (*btcutil.Tx, error) { // Protect concurrent access. mp.mtx.RLock() txDesc, exists := mp.pool[*txHash] mp.mtx.RUnlock() if exists { return txDesc.Tx, nil } return nil, fmt.Errorf("transaction is not in the pool") }
[ "func", "(", "mp", "*", "TxPool", ")", "FetchTransaction", "(", "txHash", "*", "chainhash", ".", "Hash", ")", "(", "*", "btcutil", ".", "Tx", ",", "error", ")", "{", "// Protect concurrent access.", "mp", ".", "mtx", ".", "RLock", "(", ")", "\n", "txDe...
// FetchTransaction returns the requested transaction from the transaction pool. // This only fetches from the main transaction pool and does not include // orphans. // // This function is safe for concurrent access.
[ "FetchTransaction", "returns", "the", "requested", "transaction", "from", "the", "transaction", "pool", ".", "This", "only", "fetches", "from", "the", "main", "transaction", "pool", "and", "does", "not", "include", "orphans", ".", "This", "function", "is", "safe...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/mempool.go#L621-L632
162,927
btcsuite/btcd
mempool/mempool.go
ProcessTransaction
func (mp *TxPool) ProcessTransaction(tx *btcutil.Tx, allowOrphan, rateLimit bool, tag Tag) ([]*TxDesc, error) { log.Tracef("Processing transaction %v", tx.Hash()) // Protect concurrent access. mp.mtx.Lock() defer mp.mtx.Unlock() // Potentially accept the transaction to the memory pool. missingParents, txD, err := mp.maybeAcceptTransaction(tx, true, rateLimit, true) if err != nil { return nil, err } if len(missingParents) == 0 { // Accept any orphan transactions that depend on this // transaction (they may no longer be orphans if all inputs // are now available) and repeat for those accepted // transactions until there are no more. newTxs := mp.processOrphans(tx) acceptedTxs := make([]*TxDesc, len(newTxs)+1) // Add the parent transaction first so remote nodes // do not add orphans. acceptedTxs[0] = txD copy(acceptedTxs[1:], newTxs) return acceptedTxs, nil } // The transaction is an orphan (has inputs missing). Reject // it if the flag to allow orphans is not set. if !allowOrphan { // Only use the first missing parent transaction in // the error message. // // NOTE: RejectDuplicate is really not an accurate // reject code here, but it matches the reference // implementation and there isn't a better choice due // to the limited number of reject codes. Missing // inputs is assumed to mean they are already spent // which is not really always the case. str := fmt.Sprintf("orphan transaction %v references "+ "outputs of unknown or fully-spent "+ "transaction %v", tx.Hash(), missingParents[0]) return nil, txRuleError(wire.RejectDuplicate, str) } // Potentially add the orphan transaction to the orphan pool. err = mp.maybeAddOrphan(tx, tag) return nil, err }
go
func (mp *TxPool) ProcessTransaction(tx *btcutil.Tx, allowOrphan, rateLimit bool, tag Tag) ([]*TxDesc, error) { log.Tracef("Processing transaction %v", tx.Hash()) // Protect concurrent access. mp.mtx.Lock() defer mp.mtx.Unlock() // Potentially accept the transaction to the memory pool. missingParents, txD, err := mp.maybeAcceptTransaction(tx, true, rateLimit, true) if err != nil { return nil, err } if len(missingParents) == 0 { // Accept any orphan transactions that depend on this // transaction (they may no longer be orphans if all inputs // are now available) and repeat for those accepted // transactions until there are no more. newTxs := mp.processOrphans(tx) acceptedTxs := make([]*TxDesc, len(newTxs)+1) // Add the parent transaction first so remote nodes // do not add orphans. acceptedTxs[0] = txD copy(acceptedTxs[1:], newTxs) return acceptedTxs, nil } // The transaction is an orphan (has inputs missing). Reject // it if the flag to allow orphans is not set. if !allowOrphan { // Only use the first missing parent transaction in // the error message. // // NOTE: RejectDuplicate is really not an accurate // reject code here, but it matches the reference // implementation and there isn't a better choice due // to the limited number of reject codes. Missing // inputs is assumed to mean they are already spent // which is not really always the case. str := fmt.Sprintf("orphan transaction %v references "+ "outputs of unknown or fully-spent "+ "transaction %v", tx.Hash(), missingParents[0]) return nil, txRuleError(wire.RejectDuplicate, str) } // Potentially add the orphan transaction to the orphan pool. err = mp.maybeAddOrphan(tx, tag) return nil, err }
[ "func", "(", "mp", "*", "TxPool", ")", "ProcessTransaction", "(", "tx", "*", "btcutil", ".", "Tx", ",", "allowOrphan", ",", "rateLimit", "bool", ",", "tag", "Tag", ")", "(", "[", "]", "*", "TxDesc", ",", "error", ")", "{", "log", ".", "Tracef", "("...
// ProcessTransaction is the main workhorse for handling insertion of new // free-standing transactions into the memory pool. It includes functionality // such as rejecting duplicate transactions, ensuring transactions follow all // rules, orphan transaction handling, and insertion into the memory pool. // // It returns a slice of transactions added to the mempool. When the // error is nil, the list will include the passed transaction itself along // with any additional orphan transaactions that were added as a result of // the passed one being accepted. // // This function is safe for concurrent access.
[ "ProcessTransaction", "is", "the", "main", "workhorse", "for", "handling", "insertion", "of", "new", "free", "-", "standing", "transactions", "into", "the", "memory", "pool", ".", "It", "includes", "functionality", "such", "as", "rejecting", "duplicate", "transact...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/mempool.go#L1055-L1106
162,928
btcsuite/btcd
mempool/mempool.go
Count
func (mp *TxPool) Count() int { mp.mtx.RLock() count := len(mp.pool) mp.mtx.RUnlock() return count }
go
func (mp *TxPool) Count() int { mp.mtx.RLock() count := len(mp.pool) mp.mtx.RUnlock() return count }
[ "func", "(", "mp", "*", "TxPool", ")", "Count", "(", ")", "int", "{", "mp", ".", "mtx", ".", "RLock", "(", ")", "\n", "count", ":=", "len", "(", "mp", ".", "pool", ")", "\n", "mp", ".", "mtx", ".", "RUnlock", "(", ")", "\n\n", "return", "coun...
// Count returns the number of transactions in the main pool. It does not // include the orphan pool. // // This function is safe for concurrent access.
[ "Count", "returns", "the", "number", "of", "transactions", "in", "the", "main", "pool", ".", "It", "does", "not", "include", "the", "orphan", "pool", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/mempool.go#L1112-L1118
162,929
btcsuite/btcd
mempool/mempool.go
TxHashes
func (mp *TxPool) TxHashes() []*chainhash.Hash { mp.mtx.RLock() hashes := make([]*chainhash.Hash, len(mp.pool)) i := 0 for hash := range mp.pool { hashCopy := hash hashes[i] = &hashCopy i++ } mp.mtx.RUnlock() return hashes }
go
func (mp *TxPool) TxHashes() []*chainhash.Hash { mp.mtx.RLock() hashes := make([]*chainhash.Hash, len(mp.pool)) i := 0 for hash := range mp.pool { hashCopy := hash hashes[i] = &hashCopy i++ } mp.mtx.RUnlock() return hashes }
[ "func", "(", "mp", "*", "TxPool", ")", "TxHashes", "(", ")", "[", "]", "*", "chainhash", ".", "Hash", "{", "mp", ".", "mtx", ".", "RLock", "(", ")", "\n", "hashes", ":=", "make", "(", "[", "]", "*", "chainhash", ".", "Hash", ",", "len", "(", ...
// TxHashes returns a slice of hashes for all of the transactions in the memory // pool. // // This function is safe for concurrent access.
[ "TxHashes", "returns", "a", "slice", "of", "hashes", "for", "all", "of", "the", "transactions", "in", "the", "memory", "pool", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/mempool.go#L1124-L1136
162,930
btcsuite/btcd
mempool/mempool.go
TxDescs
func (mp *TxPool) TxDescs() []*TxDesc { mp.mtx.RLock() descs := make([]*TxDesc, len(mp.pool)) i := 0 for _, desc := range mp.pool { descs[i] = desc i++ } mp.mtx.RUnlock() return descs }
go
func (mp *TxPool) TxDescs() []*TxDesc { mp.mtx.RLock() descs := make([]*TxDesc, len(mp.pool)) i := 0 for _, desc := range mp.pool { descs[i] = desc i++ } mp.mtx.RUnlock() return descs }
[ "func", "(", "mp", "*", "TxPool", ")", "TxDescs", "(", ")", "[", "]", "*", "TxDesc", "{", "mp", ".", "mtx", ".", "RLock", "(", ")", "\n", "descs", ":=", "make", "(", "[", "]", "*", "TxDesc", ",", "len", "(", "mp", ".", "pool", ")", ")", "\n...
// TxDescs returns a slice of descriptors for all the transactions in the pool. // The descriptors are to be treated as read only. // // This function is safe for concurrent access.
[ "TxDescs", "returns", "a", "slice", "of", "descriptors", "for", "all", "the", "transactions", "in", "the", "pool", ".", "The", "descriptors", "are", "to", "be", "treated", "as", "read", "only", ".", "This", "function", "is", "safe", "for", "concurrent", "a...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/mempool.go#L1142-L1153
162,931
btcsuite/btcd
mempool/mempool.go
RawMempoolVerbose
func (mp *TxPool) RawMempoolVerbose() map[string]*btcjson.GetRawMempoolVerboseResult { mp.mtx.RLock() defer mp.mtx.RUnlock() result := make(map[string]*btcjson.GetRawMempoolVerboseResult, len(mp.pool)) bestHeight := mp.cfg.BestHeight() for _, desc := range mp.pool { // Calculate the current priority based on the inputs to // the transaction. Use zero if one or more of the // input transactions can't be found for some reason. tx := desc.Tx var currentPriority float64 utxos, err := mp.fetchInputUtxos(tx) if err == nil { currentPriority = mining.CalcPriority(tx.MsgTx(), utxos, bestHeight+1) } mpd := &btcjson.GetRawMempoolVerboseResult{ Size: int32(tx.MsgTx().SerializeSize()), Vsize: int32(GetTxVirtualSize(tx)), Fee: btcutil.Amount(desc.Fee).ToBTC(), Time: desc.Added.Unix(), Height: int64(desc.Height), StartingPriority: desc.StartingPriority, CurrentPriority: currentPriority, Depends: make([]string, 0), } for _, txIn := range tx.MsgTx().TxIn { hash := &txIn.PreviousOutPoint.Hash if mp.haveTransaction(hash) { mpd.Depends = append(mpd.Depends, hash.String()) } } result[tx.Hash().String()] = mpd } return result }
go
func (mp *TxPool) RawMempoolVerbose() map[string]*btcjson.GetRawMempoolVerboseResult { mp.mtx.RLock() defer mp.mtx.RUnlock() result := make(map[string]*btcjson.GetRawMempoolVerboseResult, len(mp.pool)) bestHeight := mp.cfg.BestHeight() for _, desc := range mp.pool { // Calculate the current priority based on the inputs to // the transaction. Use zero if one or more of the // input transactions can't be found for some reason. tx := desc.Tx var currentPriority float64 utxos, err := mp.fetchInputUtxos(tx) if err == nil { currentPriority = mining.CalcPriority(tx.MsgTx(), utxos, bestHeight+1) } mpd := &btcjson.GetRawMempoolVerboseResult{ Size: int32(tx.MsgTx().SerializeSize()), Vsize: int32(GetTxVirtualSize(tx)), Fee: btcutil.Amount(desc.Fee).ToBTC(), Time: desc.Added.Unix(), Height: int64(desc.Height), StartingPriority: desc.StartingPriority, CurrentPriority: currentPriority, Depends: make([]string, 0), } for _, txIn := range tx.MsgTx().TxIn { hash := &txIn.PreviousOutPoint.Hash if mp.haveTransaction(hash) { mpd.Depends = append(mpd.Depends, hash.String()) } } result[tx.Hash().String()] = mpd } return result }
[ "func", "(", "mp", "*", "TxPool", ")", "RawMempoolVerbose", "(", ")", "map", "[", "string", "]", "*", "btcjson", ".", "GetRawMempoolVerboseResult", "{", "mp", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "mp", ".", "mtx", ".", "RUnlock", "(", "...
// RawMempoolVerbose returns all of the entries in the mempool as a fully // populated btcjson result. // // This function is safe for concurrent access.
[ "RawMempoolVerbose", "returns", "all", "of", "the", "entries", "in", "the", "mempool", "as", "a", "fully", "populated", "btcjson", "result", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/mempool.go#L1177-L1219
162,932
btcsuite/btcd
mempool/mempool.go
LastUpdated
func (mp *TxPool) LastUpdated() time.Time { return time.Unix(atomic.LoadInt64(&mp.lastUpdated), 0) }
go
func (mp *TxPool) LastUpdated() time.Time { return time.Unix(atomic.LoadInt64(&mp.lastUpdated), 0) }
[ "func", "(", "mp", "*", "TxPool", ")", "LastUpdated", "(", ")", "time", ".", "Time", "{", "return", "time", ".", "Unix", "(", "atomic", ".", "LoadInt64", "(", "&", "mp", ".", "lastUpdated", ")", ",", "0", ")", "\n", "}" ]
// LastUpdated returns the last time a transaction was added to or removed from // the main pool. It does not include the orphan pool. // // This function is safe for concurrent access.
[ "LastUpdated", "returns", "the", "last", "time", "a", "transaction", "was", "added", "to", "or", "removed", "from", "the", "main", "pool", ".", "It", "does", "not", "include", "the", "orphan", "pool", ".", "This", "function", "is", "safe", "for", "concurre...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/mempool.go#L1225-L1227
162,933
btcsuite/btcd
mempool/mempool.go
New
func New(cfg *Config) *TxPool { return &TxPool{ cfg: *cfg, pool: make(map[chainhash.Hash]*TxDesc), orphans: make(map[chainhash.Hash]*orphanTx), orphansByPrev: make(map[wire.OutPoint]map[chainhash.Hash]*btcutil.Tx), nextExpireScan: time.Now().Add(orphanExpireScanInterval), outpoints: make(map[wire.OutPoint]*btcutil.Tx), } }
go
func New(cfg *Config) *TxPool { return &TxPool{ cfg: *cfg, pool: make(map[chainhash.Hash]*TxDesc), orphans: make(map[chainhash.Hash]*orphanTx), orphansByPrev: make(map[wire.OutPoint]map[chainhash.Hash]*btcutil.Tx), nextExpireScan: time.Now().Add(orphanExpireScanInterval), outpoints: make(map[wire.OutPoint]*btcutil.Tx), } }
[ "func", "New", "(", "cfg", "*", "Config", ")", "*", "TxPool", "{", "return", "&", "TxPool", "{", "cfg", ":", "*", "cfg", ",", "pool", ":", "make", "(", "map", "[", "chainhash", ".", "Hash", "]", "*", "TxDesc", ")", ",", "orphans", ":", "make", ...
// New returns a new memory pool for validating and storing standalone // transactions until they are mined into a block.
[ "New", "returns", "a", "new", "memory", "pool", "for", "validating", "and", "storing", "standalone", "transactions", "until", "they", "are", "mined", "into", "a", "block", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/mempool.go#L1231-L1240
162,934
btcsuite/btcd
btcjson/jsonrpc.go
NewRPCError
func NewRPCError(code RPCErrorCode, message string) *RPCError { return &RPCError{ Code: code, Message: message, } }
go
func NewRPCError(code RPCErrorCode, message string) *RPCError { return &RPCError{ Code: code, Message: message, } }
[ "func", "NewRPCError", "(", "code", "RPCErrorCode", ",", "message", "string", ")", "*", "RPCError", "{", "return", "&", "RPCError", "{", "Code", ":", "code", ",", "Message", ":", "message", ",", "}", "\n", "}" ]
// NewRPCError constructs and returns a new JSON-RPC error that is suitable // for use in a JSON-RPC Response object.
[ "NewRPCError", "constructs", "and", "returns", "a", "new", "JSON", "-", "RPC", "error", "that", "is", "suitable", "for", "use", "in", "a", "JSON", "-", "RPC", "Response", "object", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/jsonrpc.go#L36-L41
162,935
btcsuite/btcd
btcjson/jsonrpc.go
NewResponse
func NewResponse(id interface{}, marshalledResult []byte, rpcErr *RPCError) (*Response, error) { if !IsValidIDType(id) { str := fmt.Sprintf("the id of type '%T' is invalid", id) return nil, makeError(ErrInvalidType, str) } pid := &id return &Response{ Result: marshalledResult, Error: rpcErr, ID: pid, }, nil }
go
func NewResponse(id interface{}, marshalledResult []byte, rpcErr *RPCError) (*Response, error) { if !IsValidIDType(id) { str := fmt.Sprintf("the id of type '%T' is invalid", id) return nil, makeError(ErrInvalidType, str) } pid := &id return &Response{ Result: marshalledResult, Error: rpcErr, ID: pid, }, nil }
[ "func", "NewResponse", "(", "id", "interface", "{", "}", ",", "marshalledResult", "[", "]", "byte", ",", "rpcErr", "*", "RPCError", ")", "(", "*", "Response", ",", "error", ")", "{", "if", "!", "IsValidIDType", "(", "id", ")", "{", "str", ":=", "fmt"...
// NewResponse returns a new JSON-RPC response object given the provided id, // marshalled result, and RPC error. This function is only provided in case the // caller wants to construct raw responses for some reason. // // Typically callers will instead want to create the fully marshalled JSON-RPC // response to send over the wire with the MarshalResponse function.
[ "NewResponse", "returns", "a", "new", "JSON", "-", "RPC", "response", "object", "given", "the", "provided", "id", "marshalled", "result", "and", "RPC", "error", ".", "This", "function", "is", "only", "provided", "in", "case", "the", "caller", "wants", "to", ...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/jsonrpc.go#L124-L136
162,936
btcsuite/btcd
btcjson/jsonrpc.go
MarshalResponse
func MarshalResponse(id interface{}, result interface{}, rpcErr *RPCError) ([]byte, error) { marshalledResult, err := json.Marshal(result) if err != nil { return nil, err } response, err := NewResponse(id, marshalledResult, rpcErr) if err != nil { return nil, err } return json.Marshal(&response) }
go
func MarshalResponse(id interface{}, result interface{}, rpcErr *RPCError) ([]byte, error) { marshalledResult, err := json.Marshal(result) if err != nil { return nil, err } response, err := NewResponse(id, marshalledResult, rpcErr) if err != nil { return nil, err } return json.Marshal(&response) }
[ "func", "MarshalResponse", "(", "id", "interface", "{", "}", ",", "result", "interface", "{", "}", ",", "rpcErr", "*", "RPCError", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "marshalledResult", ",", "err", ":=", "json", ".", "Marshal", "(", ...
// MarshalResponse marshals the passed id, result, and RPCError to a JSON-RPC // response byte slice that is suitable for transmission to a JSON-RPC client.
[ "MarshalResponse", "marshals", "the", "passed", "id", "result", "and", "RPCError", "to", "a", "JSON", "-", "RPC", "response", "byte", "slice", "that", "is", "suitable", "for", "transmission", "to", "a", "JSON", "-", "RPC", "client", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/jsonrpc.go#L140-L150
162,937
btcsuite/btcd
rpcserver.go
builderScript
func builderScript(builder *txscript.ScriptBuilder) []byte { script, err := builder.Script() if err != nil { panic(err) } return script }
go
func builderScript(builder *txscript.ScriptBuilder) []byte { script, err := builder.Script() if err != nil { panic(err) } return script }
[ "func", "builderScript", "(", "builder", "*", "txscript", ".", "ScriptBuilder", ")", "[", "]", "byte", "{", "script", ",", "err", ":=", "builder", ".", "Script", "(", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\...
// builderScript is a convenience function which is used for hard-coded scripts // built with the script builder. Any errors are converted to a panic since it // is only, and must only, be used with hard-coded, and therefore, known good, // scripts.
[ "builderScript", "is", "a", "convenience", "function", "which", "is", "used", "for", "hard", "-", "coded", "scripts", "built", "with", "the", "script", "builder", ".", "Any", "errors", "are", "converted", "to", "a", "panic", "since", "it", "is", "only", "a...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L288-L294
162,938
btcsuite/btcd
rpcserver.go
internalRPCError
func internalRPCError(errStr, context string) *btcjson.RPCError { logStr := errStr if context != "" { logStr = context + ": " + errStr } rpcsLog.Error(logStr) return btcjson.NewRPCError(btcjson.ErrRPCInternal.Code, errStr) }
go
func internalRPCError(errStr, context string) *btcjson.RPCError { logStr := errStr if context != "" { logStr = context + ": " + errStr } rpcsLog.Error(logStr) return btcjson.NewRPCError(btcjson.ErrRPCInternal.Code, errStr) }
[ "func", "internalRPCError", "(", "errStr", ",", "context", "string", ")", "*", "btcjson", ".", "RPCError", "{", "logStr", ":=", "errStr", "\n", "if", "context", "!=", "\"", "\"", "{", "logStr", "=", "context", "+", "\"", "\"", "+", "errStr", "\n", "}",...
// internalRPCError is a convenience function to convert an internal error to // an RPC error with the appropriate code set. It also logs the error to the // RPC server subsystem since internal errors really should not occur. The // context parameter is only used in the log message and may be empty if it's // not needed.
[ "internalRPCError", "is", "a", "convenience", "function", "to", "convert", "an", "internal", "error", "to", "an", "RPC", "error", "with", "the", "appropriate", "code", "set", ".", "It", "also", "logs", "the", "error", "to", "the", "RPC", "server", "subsystem...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L301-L308
162,939
btcsuite/btcd
rpcserver.go
rpcDecodeHexError
func rpcDecodeHexError(gotHex string) *btcjson.RPCError { return btcjson.NewRPCError(btcjson.ErrRPCDecodeHexString, fmt.Sprintf("Argument must be hexadecimal string (not %q)", gotHex)) }
go
func rpcDecodeHexError(gotHex string) *btcjson.RPCError { return btcjson.NewRPCError(btcjson.ErrRPCDecodeHexString, fmt.Sprintf("Argument must be hexadecimal string (not %q)", gotHex)) }
[ "func", "rpcDecodeHexError", "(", "gotHex", "string", ")", "*", "btcjson", ".", "RPCError", "{", "return", "btcjson", ".", "NewRPCError", "(", "btcjson", ".", "ErrRPCDecodeHexString", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "gotHex", ")", ")", "\...
// rpcDecodeHexError is a convenience function for returning a nicely formatted // RPC error which indicates the provided hex string failed to decode.
[ "rpcDecodeHexError", "is", "a", "convenience", "function", "for", "returning", "a", "nicely", "formatted", "RPC", "error", "which", "indicates", "the", "provided", "hex", "string", "failed", "to", "decode", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L312-L316
162,940
btcsuite/btcd
rpcserver.go
rpcNoTxInfoError
func rpcNoTxInfoError(txHash *chainhash.Hash) *btcjson.RPCError { return btcjson.NewRPCError(btcjson.ErrRPCNoTxInfo, fmt.Sprintf("No information available about transaction %v", txHash)) }
go
func rpcNoTxInfoError(txHash *chainhash.Hash) *btcjson.RPCError { return btcjson.NewRPCError(btcjson.ErrRPCNoTxInfo, fmt.Sprintf("No information available about transaction %v", txHash)) }
[ "func", "rpcNoTxInfoError", "(", "txHash", "*", "chainhash", ".", "Hash", ")", "*", "btcjson", ".", "RPCError", "{", "return", "btcjson", ".", "NewRPCError", "(", "btcjson", ".", "ErrRPCNoTxInfo", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "txHash",...
// rpcNoTxInfoError is a convenience function for returning a nicely formatted // RPC error which indicates there is no information available for the provided // transaction hash.
[ "rpcNoTxInfoError", "is", "a", "convenience", "function", "for", "returning", "a", "nicely", "formatted", "RPC", "error", "which", "indicates", "there", "is", "no", "information", "available", "for", "the", "provided", "transaction", "hash", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L321-L325
162,941
btcsuite/btcd
rpcserver.go
newGbtWorkState
func newGbtWorkState(timeSource blockchain.MedianTimeSource) *gbtWorkState { return &gbtWorkState{ notifyMap: make(map[chainhash.Hash]map[int64]chan struct{}), timeSource: timeSource, } }
go
func newGbtWorkState(timeSource blockchain.MedianTimeSource) *gbtWorkState { return &gbtWorkState{ notifyMap: make(map[chainhash.Hash]map[int64]chan struct{}), timeSource: timeSource, } }
[ "func", "newGbtWorkState", "(", "timeSource", "blockchain", ".", "MedianTimeSource", ")", "*", "gbtWorkState", "{", "return", "&", "gbtWorkState", "{", "notifyMap", ":", "make", "(", "map", "[", "chainhash", ".", "Hash", "]", "map", "[", "int64", "]", "chan"...
// newGbtWorkState returns a new instance of a gbtWorkState with all internal // fields initialized and ready to use.
[ "newGbtWorkState", "returns", "a", "new", "instance", "of", "a", "gbtWorkState", "with", "all", "internal", "fields", "initialized", "and", "ready", "to", "use", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L342-L347
162,942
btcsuite/btcd
rpcserver.go
handleAddNode
func handleAddNode(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.AddNodeCmd) addr := normalizeAddress(c.Addr, s.cfg.ChainParams.DefaultPort) var err error switch c.SubCmd { case "add": err = s.cfg.ConnMgr.Connect(addr, true) case "remove": err = s.cfg.ConnMgr.RemoveByAddr(addr) case "onetry": err = s.cfg.ConnMgr.Connect(addr, false) default: return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInvalidParameter, Message: "invalid subcommand for addnode", } } if err != nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInvalidParameter, Message: err.Error(), } } // no data returned unless an error. return nil, nil }
go
func handleAddNode(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.AddNodeCmd) addr := normalizeAddress(c.Addr, s.cfg.ChainParams.DefaultPort) var err error switch c.SubCmd { case "add": err = s.cfg.ConnMgr.Connect(addr, true) case "remove": err = s.cfg.ConnMgr.RemoveByAddr(addr) case "onetry": err = s.cfg.ConnMgr.Connect(addr, false) default: return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInvalidParameter, Message: "invalid subcommand for addnode", } } if err != nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInvalidParameter, Message: err.Error(), } } // no data returned unless an error. return nil, nil }
[ "func", "handleAddNode", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "c", ":=", "cmd", ".", "(", "*", "btcjson", ".", ...
// handleAddNode handles addnode commands.
[ "handleAddNode", "handles", "addnode", "commands", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L363-L391
162,943
btcsuite/btcd
rpcserver.go
peerExists
func peerExists(connMgr rpcserverConnManager, addr string, nodeID int32) bool { for _, p := range connMgr.ConnectedPeers() { if p.ToPeer().ID() == nodeID || p.ToPeer().Addr() == addr { return true } } return false }
go
func peerExists(connMgr rpcserverConnManager, addr string, nodeID int32) bool { for _, p := range connMgr.ConnectedPeers() { if p.ToPeer().ID() == nodeID || p.ToPeer().Addr() == addr { return true } } return false }
[ "func", "peerExists", "(", "connMgr", "rpcserverConnManager", ",", "addr", "string", ",", "nodeID", "int32", ")", "bool", "{", "for", "_", ",", "p", ":=", "range", "connMgr", ".", "ConnectedPeers", "(", ")", "{", "if", "p", ".", "ToPeer", "(", ")", "."...
// peerExists determines if a certain peer is currently connected given // information about all currently connected peers. Peer existence is // determined using either a target address or node id.
[ "peerExists", "determines", "if", "a", "certain", "peer", "is", "currently", "connected", "given", "information", "about", "all", "currently", "connected", "peers", ".", "Peer", "existence", "is", "determined", "using", "either", "a", "target", "address", "or", ...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L490-L497
162,944
btcsuite/btcd
rpcserver.go
messageToHex
func messageToHex(msg wire.Message) (string, error) { var buf bytes.Buffer if err := msg.BtcEncode(&buf, maxProtocolVersion, wire.WitnessEncoding); err != nil { context := fmt.Sprintf("Failed to encode msg of type %T", msg) return "", internalRPCError(err.Error(), context) } return hex.EncodeToString(buf.Bytes()), nil }
go
func messageToHex(msg wire.Message) (string, error) { var buf bytes.Buffer if err := msg.BtcEncode(&buf, maxProtocolVersion, wire.WitnessEncoding); err != nil { context := fmt.Sprintf("Failed to encode msg of type %T", msg) return "", internalRPCError(err.Error(), context) } return hex.EncodeToString(buf.Bytes()), nil }
[ "func", "messageToHex", "(", "msg", "wire", ".", "Message", ")", "(", "string", ",", "error", ")", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "if", "err", ":=", "msg", ".", "BtcEncode", "(", "&", "buf", ",", "maxProtocolVersion", ",", "wire", "...
// messageToHex serializes a message to the wire protocol encoding using the // latest protocol version and returns a hex-encoded string of the result.
[ "messageToHex", "serializes", "a", "message", "to", "the", "wire", "protocol", "encoding", "using", "the", "latest", "protocol", "version", "and", "returns", "a", "hex", "-", "encoded", "string", "of", "the", "result", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L501-L509
162,945
btcsuite/btcd
rpcserver.go
handleDebugLevel
func handleDebugLevel(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.DebugLevelCmd) // Special show command to list supported subsystems. if c.LevelSpec == "show" { return fmt.Sprintf("Supported subsystems %v", supportedSubsystems()), nil } err := parseAndSetDebugLevels(c.LevelSpec) if err != nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInvalidParams.Code, Message: err.Error(), } } return "Done.", nil }
go
func handleDebugLevel(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.DebugLevelCmd) // Special show command to list supported subsystems. if c.LevelSpec == "show" { return fmt.Sprintf("Supported subsystems %v", supportedSubsystems()), nil } err := parseAndSetDebugLevels(c.LevelSpec) if err != nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInvalidParams.Code, Message: err.Error(), } } return "Done.", nil }
[ "func", "handleDebugLevel", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "c", ":=", "cmd", ".", "(", "*", "btcjson", ".",...
// handleDebugLevel handles debuglevel commands.
[ "handleDebugLevel", "handles", "debuglevel", "commands", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L617-L635
162,946
btcsuite/btcd
rpcserver.go
witnessToHex
func witnessToHex(witness wire.TxWitness) []string { // Ensure nil is returned when there are no entries versus an empty // slice so it can properly be omitted as necessary. if len(witness) == 0 { return nil } result := make([]string, 0, len(witness)) for _, wit := range witness { result = append(result, hex.EncodeToString(wit)) } return result }
go
func witnessToHex(witness wire.TxWitness) []string { // Ensure nil is returned when there are no entries versus an empty // slice so it can properly be omitted as necessary. if len(witness) == 0 { return nil } result := make([]string, 0, len(witness)) for _, wit := range witness { result = append(result, hex.EncodeToString(wit)) } return result }
[ "func", "witnessToHex", "(", "witness", "wire", ".", "TxWitness", ")", "[", "]", "string", "{", "// Ensure nil is returned when there are no entries versus an empty", "// slice so it can properly be omitted as necessary.", "if", "len", "(", "witness", ")", "==", "0", "{", ...
// witnessToHex formats the passed witness stack as a slice of hex-encoded // strings to be used in a JSON response.
[ "witnessToHex", "formats", "the", "passed", "witness", "stack", "as", "a", "slice", "of", "hex", "-", "encoded", "strings", "to", "be", "used", "in", "a", "JSON", "response", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L639-L652
162,947
btcsuite/btcd
rpcserver.go
createVinList
func createVinList(mtx *wire.MsgTx) []btcjson.Vin { // Coinbase transactions only have a single txin by definition. vinList := make([]btcjson.Vin, len(mtx.TxIn)) if blockchain.IsCoinBaseTx(mtx) { txIn := mtx.TxIn[0] vinList[0].Coinbase = hex.EncodeToString(txIn.SignatureScript) vinList[0].Sequence = txIn.Sequence vinList[0].Witness = witnessToHex(txIn.Witness) return vinList } for i, txIn := range mtx.TxIn { // The disassembled string will contain [error] inline // if the script doesn't fully parse, so ignore the // error here. disbuf, _ := txscript.DisasmString(txIn.SignatureScript) vinEntry := &vinList[i] vinEntry.Txid = txIn.PreviousOutPoint.Hash.String() vinEntry.Vout = txIn.PreviousOutPoint.Index vinEntry.Sequence = txIn.Sequence vinEntry.ScriptSig = &btcjson.ScriptSig{ Asm: disbuf, Hex: hex.EncodeToString(txIn.SignatureScript), } if mtx.HasWitness() { vinEntry.Witness = witnessToHex(txIn.Witness) } } return vinList }
go
func createVinList(mtx *wire.MsgTx) []btcjson.Vin { // Coinbase transactions only have a single txin by definition. vinList := make([]btcjson.Vin, len(mtx.TxIn)) if blockchain.IsCoinBaseTx(mtx) { txIn := mtx.TxIn[0] vinList[0].Coinbase = hex.EncodeToString(txIn.SignatureScript) vinList[0].Sequence = txIn.Sequence vinList[0].Witness = witnessToHex(txIn.Witness) return vinList } for i, txIn := range mtx.TxIn { // The disassembled string will contain [error] inline // if the script doesn't fully parse, so ignore the // error here. disbuf, _ := txscript.DisasmString(txIn.SignatureScript) vinEntry := &vinList[i] vinEntry.Txid = txIn.PreviousOutPoint.Hash.String() vinEntry.Vout = txIn.PreviousOutPoint.Index vinEntry.Sequence = txIn.Sequence vinEntry.ScriptSig = &btcjson.ScriptSig{ Asm: disbuf, Hex: hex.EncodeToString(txIn.SignatureScript), } if mtx.HasWitness() { vinEntry.Witness = witnessToHex(txIn.Witness) } } return vinList }
[ "func", "createVinList", "(", "mtx", "*", "wire", ".", "MsgTx", ")", "[", "]", "btcjson", ".", "Vin", "{", "// Coinbase transactions only have a single txin by definition.", "vinList", ":=", "make", "(", "[", "]", "btcjson", ".", "Vin", ",", "len", "(", "mtx",...
// createVinList returns a slice of JSON objects for the inputs of the passed // transaction.
[ "createVinList", "returns", "a", "slice", "of", "JSON", "objects", "for", "the", "inputs", "of", "the", "passed", "transaction", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L656-L688
162,948
btcsuite/btcd
rpcserver.go
createVoutList
func createVoutList(mtx *wire.MsgTx, chainParams *chaincfg.Params, filterAddrMap map[string]struct{}) []btcjson.Vout { voutList := make([]btcjson.Vout, 0, len(mtx.TxOut)) for i, v := range mtx.TxOut { // The disassembled string will contain [error] inline if the // script doesn't fully parse, so ignore the error here. disbuf, _ := txscript.DisasmString(v.PkScript) // Ignore the error here since an error means the script // couldn't parse and there is no additional information about // it anyways. scriptClass, addrs, reqSigs, _ := txscript.ExtractPkScriptAddrs( v.PkScript, chainParams) // Encode the addresses while checking if the address passes the // filter when needed. passesFilter := len(filterAddrMap) == 0 encodedAddrs := make([]string, len(addrs)) for j, addr := range addrs { encodedAddr := addr.EncodeAddress() encodedAddrs[j] = encodedAddr // No need to check the map again if the filter already // passes. if passesFilter { continue } if _, exists := filterAddrMap[encodedAddr]; exists { passesFilter = true } } if !passesFilter { continue } var vout btcjson.Vout vout.N = uint32(i) vout.Value = btcutil.Amount(v.Value).ToBTC() vout.ScriptPubKey.Addresses = encodedAddrs vout.ScriptPubKey.Asm = disbuf vout.ScriptPubKey.Hex = hex.EncodeToString(v.PkScript) vout.ScriptPubKey.Type = scriptClass.String() vout.ScriptPubKey.ReqSigs = int32(reqSigs) voutList = append(voutList, vout) } return voutList }
go
func createVoutList(mtx *wire.MsgTx, chainParams *chaincfg.Params, filterAddrMap map[string]struct{}) []btcjson.Vout { voutList := make([]btcjson.Vout, 0, len(mtx.TxOut)) for i, v := range mtx.TxOut { // The disassembled string will contain [error] inline if the // script doesn't fully parse, so ignore the error here. disbuf, _ := txscript.DisasmString(v.PkScript) // Ignore the error here since an error means the script // couldn't parse and there is no additional information about // it anyways. scriptClass, addrs, reqSigs, _ := txscript.ExtractPkScriptAddrs( v.PkScript, chainParams) // Encode the addresses while checking if the address passes the // filter when needed. passesFilter := len(filterAddrMap) == 0 encodedAddrs := make([]string, len(addrs)) for j, addr := range addrs { encodedAddr := addr.EncodeAddress() encodedAddrs[j] = encodedAddr // No need to check the map again if the filter already // passes. if passesFilter { continue } if _, exists := filterAddrMap[encodedAddr]; exists { passesFilter = true } } if !passesFilter { continue } var vout btcjson.Vout vout.N = uint32(i) vout.Value = btcutil.Amount(v.Value).ToBTC() vout.ScriptPubKey.Addresses = encodedAddrs vout.ScriptPubKey.Asm = disbuf vout.ScriptPubKey.Hex = hex.EncodeToString(v.PkScript) vout.ScriptPubKey.Type = scriptClass.String() vout.ScriptPubKey.ReqSigs = int32(reqSigs) voutList = append(voutList, vout) } return voutList }
[ "func", "createVoutList", "(", "mtx", "*", "wire", ".", "MsgTx", ",", "chainParams", "*", "chaincfg", ".", "Params", ",", "filterAddrMap", "map", "[", "string", "]", "struct", "{", "}", ")", "[", "]", "btcjson", ".", "Vout", "{", "voutList", ":=", "mak...
// createVoutList returns a slice of JSON objects for the outputs of the passed // transaction.
[ "createVoutList", "returns", "a", "slice", "of", "JSON", "objects", "for", "the", "outputs", "of", "the", "passed", "transaction", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L692-L740
162,949
btcsuite/btcd
rpcserver.go
createTxRawResult
func createTxRawResult(chainParams *chaincfg.Params, mtx *wire.MsgTx, txHash string, blkHeader *wire.BlockHeader, blkHash string, blkHeight int32, chainHeight int32) (*btcjson.TxRawResult, error) { mtxHex, err := messageToHex(mtx) if err != nil { return nil, err } txReply := &btcjson.TxRawResult{ Hex: mtxHex, Txid: txHash, Hash: mtx.WitnessHash().String(), Size: int32(mtx.SerializeSize()), Vsize: int32(mempool.GetTxVirtualSize(btcutil.NewTx(mtx))), Vin: createVinList(mtx), Vout: createVoutList(mtx, chainParams, nil), Version: mtx.Version, LockTime: mtx.LockTime, } if blkHeader != nil { // This is not a typo, they are identical in bitcoind as well. txReply.Time = blkHeader.Timestamp.Unix() txReply.Blocktime = blkHeader.Timestamp.Unix() txReply.BlockHash = blkHash txReply.Confirmations = uint64(1 + chainHeight - blkHeight) } return txReply, nil }
go
func createTxRawResult(chainParams *chaincfg.Params, mtx *wire.MsgTx, txHash string, blkHeader *wire.BlockHeader, blkHash string, blkHeight int32, chainHeight int32) (*btcjson.TxRawResult, error) { mtxHex, err := messageToHex(mtx) if err != nil { return nil, err } txReply := &btcjson.TxRawResult{ Hex: mtxHex, Txid: txHash, Hash: mtx.WitnessHash().String(), Size: int32(mtx.SerializeSize()), Vsize: int32(mempool.GetTxVirtualSize(btcutil.NewTx(mtx))), Vin: createVinList(mtx), Vout: createVoutList(mtx, chainParams, nil), Version: mtx.Version, LockTime: mtx.LockTime, } if blkHeader != nil { // This is not a typo, they are identical in bitcoind as well. txReply.Time = blkHeader.Timestamp.Unix() txReply.Blocktime = blkHeader.Timestamp.Unix() txReply.BlockHash = blkHash txReply.Confirmations = uint64(1 + chainHeight - blkHeight) } return txReply, nil }
[ "func", "createTxRawResult", "(", "chainParams", "*", "chaincfg", ".", "Params", ",", "mtx", "*", "wire", ".", "MsgTx", ",", "txHash", "string", ",", "blkHeader", "*", "wire", ".", "BlockHeader", ",", "blkHash", "string", ",", "blkHeight", "int32", ",", "c...
// createTxRawResult converts the passed transaction and associated parameters // to a raw transaction JSON object.
[ "createTxRawResult", "converts", "the", "passed", "transaction", "and", "associated", "parameters", "to", "a", "raw", "transaction", "JSON", "object", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L744-L774
162,950
btcsuite/btcd
rpcserver.go
handleDecodeRawTransaction
func handleDecodeRawTransaction(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.DecodeRawTransactionCmd) // Deserialize the transaction. hexStr := c.HexTx if len(hexStr)%2 != 0 { hexStr = "0" + hexStr } serializedTx, err := hex.DecodeString(hexStr) if err != nil { return nil, rpcDecodeHexError(hexStr) } var mtx wire.MsgTx err = mtx.Deserialize(bytes.NewReader(serializedTx)) if err != nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCDeserialization, Message: "TX decode failed: " + err.Error(), } } // Create and return the result. txReply := btcjson.TxRawDecodeResult{ Txid: mtx.TxHash().String(), Version: mtx.Version, Locktime: mtx.LockTime, Vin: createVinList(&mtx), Vout: createVoutList(&mtx, s.cfg.ChainParams, nil), } return txReply, nil }
go
func handleDecodeRawTransaction(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.DecodeRawTransactionCmd) // Deserialize the transaction. hexStr := c.HexTx if len(hexStr)%2 != 0 { hexStr = "0" + hexStr } serializedTx, err := hex.DecodeString(hexStr) if err != nil { return nil, rpcDecodeHexError(hexStr) } var mtx wire.MsgTx err = mtx.Deserialize(bytes.NewReader(serializedTx)) if err != nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCDeserialization, Message: "TX decode failed: " + err.Error(), } } // Create and return the result. txReply := btcjson.TxRawDecodeResult{ Txid: mtx.TxHash().String(), Version: mtx.Version, Locktime: mtx.LockTime, Vin: createVinList(&mtx), Vout: createVoutList(&mtx, s.cfg.ChainParams, nil), } return txReply, nil }
[ "func", "handleDecodeRawTransaction", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "c", ":=", "cmd", ".", "(", "*", "btcjso...
// handleDecodeRawTransaction handles decoderawtransaction commands.
[ "handleDecodeRawTransaction", "handles", "decoderawtransaction", "commands", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L777-L807
162,951
btcsuite/btcd
rpcserver.go
handleDecodeScript
func handleDecodeScript(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.DecodeScriptCmd) // Convert the hex script to bytes. hexStr := c.HexScript if len(hexStr)%2 != 0 { hexStr = "0" + hexStr } script, err := hex.DecodeString(hexStr) if err != nil { return nil, rpcDecodeHexError(hexStr) } // The disassembled string will contain [error] inline if the script // doesn't fully parse, so ignore the error here. disbuf, _ := txscript.DisasmString(script) // Get information about the script. // Ignore the error here since an error means the script couldn't parse // and there is no additinal information about it anyways. scriptClass, addrs, reqSigs, _ := txscript.ExtractPkScriptAddrs(script, s.cfg.ChainParams) addresses := make([]string, len(addrs)) for i, addr := range addrs { addresses[i] = addr.EncodeAddress() } // Convert the script itself to a pay-to-script-hash address. p2sh, err := btcutil.NewAddressScriptHash(script, s.cfg.ChainParams) if err != nil { context := "Failed to convert script to pay-to-script-hash" return nil, internalRPCError(err.Error(), context) } // Generate and return the reply. reply := btcjson.DecodeScriptResult{ Asm: disbuf, ReqSigs: int32(reqSigs), Type: scriptClass.String(), Addresses: addresses, } if scriptClass != txscript.ScriptHashTy { reply.P2sh = p2sh.EncodeAddress() } return reply, nil }
go
func handleDecodeScript(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.DecodeScriptCmd) // Convert the hex script to bytes. hexStr := c.HexScript if len(hexStr)%2 != 0 { hexStr = "0" + hexStr } script, err := hex.DecodeString(hexStr) if err != nil { return nil, rpcDecodeHexError(hexStr) } // The disassembled string will contain [error] inline if the script // doesn't fully parse, so ignore the error here. disbuf, _ := txscript.DisasmString(script) // Get information about the script. // Ignore the error here since an error means the script couldn't parse // and there is no additinal information about it anyways. scriptClass, addrs, reqSigs, _ := txscript.ExtractPkScriptAddrs(script, s.cfg.ChainParams) addresses := make([]string, len(addrs)) for i, addr := range addrs { addresses[i] = addr.EncodeAddress() } // Convert the script itself to a pay-to-script-hash address. p2sh, err := btcutil.NewAddressScriptHash(script, s.cfg.ChainParams) if err != nil { context := "Failed to convert script to pay-to-script-hash" return nil, internalRPCError(err.Error(), context) } // Generate and return the reply. reply := btcjson.DecodeScriptResult{ Asm: disbuf, ReqSigs: int32(reqSigs), Type: scriptClass.String(), Addresses: addresses, } if scriptClass != txscript.ScriptHashTy { reply.P2sh = p2sh.EncodeAddress() } return reply, nil }
[ "func", "handleDecodeScript", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "c", ":=", "cmd", ".", "(", "*", "btcjson", "....
// handleDecodeScript handles decodescript commands.
[ "handleDecodeScript", "handles", "decodescript", "commands", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L810-L855
162,952
btcsuite/btcd
rpcserver.go
handleEstimateFee
func handleEstimateFee(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.EstimateFeeCmd) if s.cfg.FeeEstimator == nil { return nil, errors.New("Fee estimation disabled") } if c.NumBlocks <= 0 { return -1.0, errors.New("Parameter NumBlocks must be positive") } feeRate, err := s.cfg.FeeEstimator.EstimateFee(uint32(c.NumBlocks)) if err != nil { return -1.0, err } // Convert to satoshis per kb. return float64(feeRate), nil }
go
func handleEstimateFee(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.EstimateFeeCmd) if s.cfg.FeeEstimator == nil { return nil, errors.New("Fee estimation disabled") } if c.NumBlocks <= 0 { return -1.0, errors.New("Parameter NumBlocks must be positive") } feeRate, err := s.cfg.FeeEstimator.EstimateFee(uint32(c.NumBlocks)) if err != nil { return -1.0, err } // Convert to satoshis per kb. return float64(feeRate), nil }
[ "func", "handleEstimateFee", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "c", ":=", "cmd", ".", "(", "*", "btcjson", "."...
// handleEstimateFee handles estimatefee commands.
[ "handleEstimateFee", "handles", "estimatefee", "commands", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L858-L877
162,953
btcsuite/btcd
rpcserver.go
handleGenerate
func handleGenerate(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { // Respond with an error if there are no addresses to pay the // created blocks to. if len(cfg.miningAddrs) == 0 { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInternal.Code, Message: "No payment addresses specified " + "via --miningaddr", } } // Respond with an error if there's virtually 0 chance of mining a block // with the CPU. if !s.cfg.ChainParams.GenerateSupported { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCDifficulty, Message: fmt.Sprintf("No support for `generate` on "+ "the current network, %s, as it's unlikely to "+ "be possible to mine a block with the CPU.", s.cfg.ChainParams.Net), } } c := cmd.(*btcjson.GenerateCmd) // Respond with an error if the client is requesting 0 blocks to be generated. if c.NumBlocks == 0 { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInternal.Code, Message: "Please request a nonzero number of blocks to generate.", } } // Create a reply reply := make([]string, c.NumBlocks) blockHashes, err := s.cfg.CPUMiner.GenerateNBlocks(c.NumBlocks) if err != nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInternal.Code, Message: err.Error(), } } // Mine the correct number of blocks, assigning the hex representation of the // hash of each one to its place in the reply. for i, hash := range blockHashes { reply[i] = hash.String() } return reply, nil }
go
func handleGenerate(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { // Respond with an error if there are no addresses to pay the // created blocks to. if len(cfg.miningAddrs) == 0 { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInternal.Code, Message: "No payment addresses specified " + "via --miningaddr", } } // Respond with an error if there's virtually 0 chance of mining a block // with the CPU. if !s.cfg.ChainParams.GenerateSupported { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCDifficulty, Message: fmt.Sprintf("No support for `generate` on "+ "the current network, %s, as it's unlikely to "+ "be possible to mine a block with the CPU.", s.cfg.ChainParams.Net), } } c := cmd.(*btcjson.GenerateCmd) // Respond with an error if the client is requesting 0 blocks to be generated. if c.NumBlocks == 0 { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInternal.Code, Message: "Please request a nonzero number of blocks to generate.", } } // Create a reply reply := make([]string, c.NumBlocks) blockHashes, err := s.cfg.CPUMiner.GenerateNBlocks(c.NumBlocks) if err != nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInternal.Code, Message: err.Error(), } } // Mine the correct number of blocks, assigning the hex representation of the // hash of each one to its place in the reply. for i, hash := range blockHashes { reply[i] = hash.String() } return reply, nil }
[ "func", "handleGenerate", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "// Respond with an error if there are no addresses to pay the",...
// handleGenerate handles generate commands.
[ "handleGenerate", "handles", "generate", "commands", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L880-L931
162,954
btcsuite/btcd
rpcserver.go
handleGetBestBlock
func handleGetBestBlock(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { // All other "get block" commands give either the height, the // hash, or both but require the block SHA. This gets both for // the best block. best := s.cfg.Chain.BestSnapshot() result := &btcjson.GetBestBlockResult{ Hash: best.Hash.String(), Height: best.Height, } return result, nil }
go
func handleGetBestBlock(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { // All other "get block" commands give either the height, the // hash, or both but require the block SHA. This gets both for // the best block. best := s.cfg.Chain.BestSnapshot() result := &btcjson.GetBestBlockResult{ Hash: best.Hash.String(), Height: best.Height, } return result, nil }
[ "func", "handleGetBestBlock", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "// All other \"get block\" commands give either the height,...
// handleGetBestBlock implements the getbestblock command.
[ "handleGetBestBlock", "implements", "the", "getbestblock", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L1024-L1034
162,955
btcsuite/btcd
rpcserver.go
handleGetBestBlockHash
func handleGetBestBlockHash(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { best := s.cfg.Chain.BestSnapshot() return best.Hash.String(), nil }
go
func handleGetBestBlockHash(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { best := s.cfg.Chain.BestSnapshot() return best.Hash.String(), nil }
[ "func", "handleGetBestBlockHash", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "best", ":=", "s", ".", "cfg", ".", "Chain",...
// handleGetBestBlockHash implements the getbestblockhash command.
[ "handleGetBestBlockHash", "implements", "the", "getbestblockhash", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L1037-L1040
162,956
btcsuite/btcd
rpcserver.go
softForkStatus
func softForkStatus(state blockchain.ThresholdState) (string, error) { switch state { case blockchain.ThresholdDefined: return "defined", nil case blockchain.ThresholdStarted: return "started", nil case blockchain.ThresholdLockedIn: return "lockedin", nil case blockchain.ThresholdActive: return "active", nil case blockchain.ThresholdFailed: return "failed", nil default: return "", fmt.Errorf("unknown deployment state: %v", state) } }
go
func softForkStatus(state blockchain.ThresholdState) (string, error) { switch state { case blockchain.ThresholdDefined: return "defined", nil case blockchain.ThresholdStarted: return "started", nil case blockchain.ThresholdLockedIn: return "lockedin", nil case blockchain.ThresholdActive: return "active", nil case blockchain.ThresholdFailed: return "failed", nil default: return "", fmt.Errorf("unknown deployment state: %v", state) } }
[ "func", "softForkStatus", "(", "state", "blockchain", ".", "ThresholdState", ")", "(", "string", ",", "error", ")", "{", "switch", "state", "{", "case", "blockchain", ".", "ThresholdDefined", ":", "return", "\"", "\"", ",", "nil", "\n", "case", "blockchain",...
// softForkStatus converts a ThresholdState state into a human readable string // corresponding to the particular state.
[ "softForkStatus", "converts", "a", "ThresholdState", "state", "into", "a", "human", "readable", "string", "corresponding", "to", "the", "particular", "state", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L1167-L1182
162,957
btcsuite/btcd
rpcserver.go
handleGetBlockChainInfo
func handleGetBlockChainInfo(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { // Obtain a snapshot of the current best known blockchain state. We'll // populate the response to this call primarily from this snapshot. params := s.cfg.ChainParams chain := s.cfg.Chain chainSnapshot := chain.BestSnapshot() chainInfo := &btcjson.GetBlockChainInfoResult{ Chain: params.Name, Blocks: chainSnapshot.Height, Headers: chainSnapshot.Height, BestBlockHash: chainSnapshot.Hash.String(), Difficulty: getDifficultyRatio(chainSnapshot.Bits, params), MedianTime: chainSnapshot.MedianTime.Unix(), Pruned: false, Bip9SoftForks: make(map[string]*btcjson.Bip9SoftForkDescription), } // Next, populate the response with information describing the current // status of soft-forks deployed via the super-majority block // signalling mechanism. height := chainSnapshot.Height chainInfo.SoftForks = []*btcjson.SoftForkDescription{ { ID: "bip34", Version: 2, Reject: struct { Status bool `json:"status"` }{ Status: height >= params.BIP0034Height, }, }, { ID: "bip66", Version: 3, Reject: struct { Status bool `json:"status"` }{ Status: height >= params.BIP0066Height, }, }, { ID: "bip65", Version: 4, Reject: struct { Status bool `json:"status"` }{ Status: height >= params.BIP0065Height, }, }, } // Finally, query the BIP0009 version bits state for all currently // defined BIP0009 soft-fork deployments. for deployment, deploymentDetails := range params.Deployments { // Map the integer deployment ID into a human readable // fork-name. var forkName string switch deployment { case chaincfg.DeploymentTestDummy: forkName = "dummy" case chaincfg.DeploymentCSV: forkName = "csv" case chaincfg.DeploymentSegwit: forkName = "segwit" default: return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInternal.Code, Message: fmt.Sprintf("Unknown deployment %v "+ "detected", deployment), } } // Query the chain for the current status of the deployment as // identified by its deployment ID. deploymentStatus, err := chain.ThresholdState(uint32(deployment)) if err != nil { context := "Failed to obtain deployment status" return nil, internalRPCError(err.Error(), context) } // Attempt to convert the current deployment status into a // human readable string. If the status is unrecognized, then a // non-nil error is returned. statusString, err := softForkStatus(deploymentStatus) if err != nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInternal.Code, Message: fmt.Sprintf("unknown deployment status: %v", deploymentStatus), } } // Finally, populate the soft-fork description with all the // information gathered above. chainInfo.Bip9SoftForks[forkName] = &btcjson.Bip9SoftForkDescription{ Status: strings.ToLower(statusString), Bit: deploymentDetails.BitNumber, StartTime: int64(deploymentDetails.StartTime), Timeout: int64(deploymentDetails.ExpireTime), } } return chainInfo, nil }
go
func handleGetBlockChainInfo(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { // Obtain a snapshot of the current best known blockchain state. We'll // populate the response to this call primarily from this snapshot. params := s.cfg.ChainParams chain := s.cfg.Chain chainSnapshot := chain.BestSnapshot() chainInfo := &btcjson.GetBlockChainInfoResult{ Chain: params.Name, Blocks: chainSnapshot.Height, Headers: chainSnapshot.Height, BestBlockHash: chainSnapshot.Hash.String(), Difficulty: getDifficultyRatio(chainSnapshot.Bits, params), MedianTime: chainSnapshot.MedianTime.Unix(), Pruned: false, Bip9SoftForks: make(map[string]*btcjson.Bip9SoftForkDescription), } // Next, populate the response with information describing the current // status of soft-forks deployed via the super-majority block // signalling mechanism. height := chainSnapshot.Height chainInfo.SoftForks = []*btcjson.SoftForkDescription{ { ID: "bip34", Version: 2, Reject: struct { Status bool `json:"status"` }{ Status: height >= params.BIP0034Height, }, }, { ID: "bip66", Version: 3, Reject: struct { Status bool `json:"status"` }{ Status: height >= params.BIP0066Height, }, }, { ID: "bip65", Version: 4, Reject: struct { Status bool `json:"status"` }{ Status: height >= params.BIP0065Height, }, }, } // Finally, query the BIP0009 version bits state for all currently // defined BIP0009 soft-fork deployments. for deployment, deploymentDetails := range params.Deployments { // Map the integer deployment ID into a human readable // fork-name. var forkName string switch deployment { case chaincfg.DeploymentTestDummy: forkName = "dummy" case chaincfg.DeploymentCSV: forkName = "csv" case chaincfg.DeploymentSegwit: forkName = "segwit" default: return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInternal.Code, Message: fmt.Sprintf("Unknown deployment %v "+ "detected", deployment), } } // Query the chain for the current status of the deployment as // identified by its deployment ID. deploymentStatus, err := chain.ThresholdState(uint32(deployment)) if err != nil { context := "Failed to obtain deployment status" return nil, internalRPCError(err.Error(), context) } // Attempt to convert the current deployment status into a // human readable string. If the status is unrecognized, then a // non-nil error is returned. statusString, err := softForkStatus(deploymentStatus) if err != nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInternal.Code, Message: fmt.Sprintf("unknown deployment status: %v", deploymentStatus), } } // Finally, populate the soft-fork description with all the // information gathered above. chainInfo.Bip9SoftForks[forkName] = &btcjson.Bip9SoftForkDescription{ Status: strings.ToLower(statusString), Bit: deploymentDetails.BitNumber, StartTime: int64(deploymentDetails.StartTime), Timeout: int64(deploymentDetails.ExpireTime), } } return chainInfo, nil }
[ "func", "handleGetBlockChainInfo", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "// Obtain a snapshot of the current best known blockch...
// handleGetBlockChainInfo implements the getblockchaininfo command.
[ "handleGetBlockChainInfo", "implements", "the", "getblockchaininfo", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L1185-L1292
162,958
btcsuite/btcd
rpcserver.go
handleGetBlockCount
func handleGetBlockCount(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { best := s.cfg.Chain.BestSnapshot() return int64(best.Height), nil }
go
func handleGetBlockCount(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { best := s.cfg.Chain.BestSnapshot() return int64(best.Height), nil }
[ "func", "handleGetBlockCount", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "best", ":=", "s", ".", "cfg", ".", "Chain", ...
// handleGetBlockCount implements the getblockcount command.
[ "handleGetBlockCount", "implements", "the", "getblockcount", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L1295-L1298
162,959
btcsuite/btcd
rpcserver.go
handleGetBlockHash
func handleGetBlockHash(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.GetBlockHashCmd) hash, err := s.cfg.Chain.BlockHashByHeight(int32(c.Index)) if err != nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCOutOfRange, Message: "Block number out of range", } } return hash.String(), nil }
go
func handleGetBlockHash(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.GetBlockHashCmd) hash, err := s.cfg.Chain.BlockHashByHeight(int32(c.Index)) if err != nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCOutOfRange, Message: "Block number out of range", } } return hash.String(), nil }
[ "func", "handleGetBlockHash", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "c", ":=", "cmd", ".", "(", "*", "btcjson", "....
// handleGetBlockHash implements the getblockhash command.
[ "handleGetBlockHash", "implements", "the", "getblockhash", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L1301-L1312
162,960
btcsuite/btcd
rpcserver.go
handleGetBlockHeader
func handleGetBlockHeader(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.GetBlockHeaderCmd) // Fetch the header from chain. hash, err := chainhash.NewHashFromStr(c.Hash) if err != nil { return nil, rpcDecodeHexError(c.Hash) } blockHeader, err := s.cfg.Chain.HeaderByHash(hash) if err != nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCBlockNotFound, Message: "Block not found", } } // When the verbose flag isn't set, simply return the serialized block // header as a hex-encoded string. if c.Verbose != nil && !*c.Verbose { var headerBuf bytes.Buffer err := blockHeader.Serialize(&headerBuf) if err != nil { context := "Failed to serialize block header" return nil, internalRPCError(err.Error(), context) } return hex.EncodeToString(headerBuf.Bytes()), nil } // The verbose flag is set, so generate the JSON object and return it. // Get the block height from chain. blockHeight, err := s.cfg.Chain.BlockHeightByHash(hash) if err != nil { context := "Failed to obtain block height" return nil, internalRPCError(err.Error(), context) } best := s.cfg.Chain.BestSnapshot() // Get next block hash unless there are none. var nextHashString string if blockHeight < best.Height { nextHash, err := s.cfg.Chain.BlockHashByHeight(blockHeight + 1) if err != nil { context := "No next block" return nil, internalRPCError(err.Error(), context) } nextHashString = nextHash.String() } params := s.cfg.ChainParams blockHeaderReply := btcjson.GetBlockHeaderVerboseResult{ Hash: c.Hash, Confirmations: int64(1 + best.Height - blockHeight), Height: blockHeight, Version: blockHeader.Version, VersionHex: fmt.Sprintf("%08x", blockHeader.Version), MerkleRoot: blockHeader.MerkleRoot.String(), NextHash: nextHashString, PreviousHash: blockHeader.PrevBlock.String(), Nonce: uint64(blockHeader.Nonce), Time: blockHeader.Timestamp.Unix(), Bits: strconv.FormatInt(int64(blockHeader.Bits), 16), Difficulty: getDifficultyRatio(blockHeader.Bits, params), } return blockHeaderReply, nil }
go
func handleGetBlockHeader(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.GetBlockHeaderCmd) // Fetch the header from chain. hash, err := chainhash.NewHashFromStr(c.Hash) if err != nil { return nil, rpcDecodeHexError(c.Hash) } blockHeader, err := s.cfg.Chain.HeaderByHash(hash) if err != nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCBlockNotFound, Message: "Block not found", } } // When the verbose flag isn't set, simply return the serialized block // header as a hex-encoded string. if c.Verbose != nil && !*c.Verbose { var headerBuf bytes.Buffer err := blockHeader.Serialize(&headerBuf) if err != nil { context := "Failed to serialize block header" return nil, internalRPCError(err.Error(), context) } return hex.EncodeToString(headerBuf.Bytes()), nil } // The verbose flag is set, so generate the JSON object and return it. // Get the block height from chain. blockHeight, err := s.cfg.Chain.BlockHeightByHash(hash) if err != nil { context := "Failed to obtain block height" return nil, internalRPCError(err.Error(), context) } best := s.cfg.Chain.BestSnapshot() // Get next block hash unless there are none. var nextHashString string if blockHeight < best.Height { nextHash, err := s.cfg.Chain.BlockHashByHeight(blockHeight + 1) if err != nil { context := "No next block" return nil, internalRPCError(err.Error(), context) } nextHashString = nextHash.String() } params := s.cfg.ChainParams blockHeaderReply := btcjson.GetBlockHeaderVerboseResult{ Hash: c.Hash, Confirmations: int64(1 + best.Height - blockHeight), Height: blockHeight, Version: blockHeader.Version, VersionHex: fmt.Sprintf("%08x", blockHeader.Version), MerkleRoot: blockHeader.MerkleRoot.String(), NextHash: nextHashString, PreviousHash: blockHeader.PrevBlock.String(), Nonce: uint64(blockHeader.Nonce), Time: blockHeader.Timestamp.Unix(), Bits: strconv.FormatInt(int64(blockHeader.Bits), 16), Difficulty: getDifficultyRatio(blockHeader.Bits, params), } return blockHeaderReply, nil }
[ "func", "handleGetBlockHeader", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "c", ":=", "cmd", ".", "(", "*", "btcjson", ...
// handleGetBlockHeader implements the getblockheader command.
[ "handleGetBlockHeader", "implements", "the", "getblockheader", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L1315-L1380
162,961
btcsuite/btcd
rpcserver.go
encodeTemplateID
func encodeTemplateID(prevHash *chainhash.Hash, lastGenerated time.Time) string { return fmt.Sprintf("%s-%d", prevHash.String(), lastGenerated.Unix()) }
go
func encodeTemplateID(prevHash *chainhash.Hash, lastGenerated time.Time) string { return fmt.Sprintf("%s-%d", prevHash.String(), lastGenerated.Unix()) }
[ "func", "encodeTemplateID", "(", "prevHash", "*", "chainhash", ".", "Hash", ",", "lastGenerated", "time", ".", "Time", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "prevHash", ".", "String", "(", ")", ",", "lastGenerated", "...
// encodeTemplateID encodes the passed details into an ID that can be used to // uniquely identify a block template.
[ "encodeTemplateID", "encodes", "the", "passed", "details", "into", "an", "ID", "that", "can", "be", "used", "to", "uniquely", "identify", "a", "block", "template", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L1384-L1386
162,962
btcsuite/btcd
rpcserver.go
decodeTemplateID
func decodeTemplateID(templateID string) (*chainhash.Hash, int64, error) { fields := strings.Split(templateID, "-") if len(fields) != 2 { return nil, 0, errors.New("invalid longpollid format") } prevHash, err := chainhash.NewHashFromStr(fields[0]) if err != nil { return nil, 0, errors.New("invalid longpollid format") } lastGenerated, err := strconv.ParseInt(fields[1], 10, 64) if err != nil { return nil, 0, errors.New("invalid longpollid format") } return prevHash, lastGenerated, nil }
go
func decodeTemplateID(templateID string) (*chainhash.Hash, int64, error) { fields := strings.Split(templateID, "-") if len(fields) != 2 { return nil, 0, errors.New("invalid longpollid format") } prevHash, err := chainhash.NewHashFromStr(fields[0]) if err != nil { return nil, 0, errors.New("invalid longpollid format") } lastGenerated, err := strconv.ParseInt(fields[1], 10, 64) if err != nil { return nil, 0, errors.New("invalid longpollid format") } return prevHash, lastGenerated, nil }
[ "func", "decodeTemplateID", "(", "templateID", "string", ")", "(", "*", "chainhash", ".", "Hash", ",", "int64", ",", "error", ")", "{", "fields", ":=", "strings", ".", "Split", "(", "templateID", ",", "\"", "\"", ")", "\n", "if", "len", "(", "fields", ...
// decodeTemplateID decodes an ID that is used to uniquely identify a block // template. This is mainly used as a mechanism to track when to update clients // that are using long polling for block templates. The ID consists of the // previous block hash for the associated template and the time the associated // template was generated.
[ "decodeTemplateID", "decodes", "an", "ID", "that", "is", "used", "to", "uniquely", "identify", "a", "block", "template", ".", "This", "is", "mainly", "used", "as", "a", "mechanism", "to", "track", "when", "to", "update", "clients", "that", "are", "using", ...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L1393-L1409
162,963
btcsuite/btcd
rpcserver.go
notifyLongPollers
func (state *gbtWorkState) notifyLongPollers(latestHash *chainhash.Hash, lastGenerated time.Time) { // Notify anything that is waiting for a block template update from a // hash which is not the hash of the tip of the best chain since their // work is now invalid. for hash, channels := range state.notifyMap { if !hash.IsEqual(latestHash) { for _, c := range channels { close(c) } delete(state.notifyMap, hash) } } // Return now if the provided last generated timestamp has not been // initialized. if lastGenerated.IsZero() { return } // Return now if there is nothing registered for updates to the current // best block hash. channels, ok := state.notifyMap[*latestHash] if !ok { return } // Notify anything that is waiting for a block template update from a // block template generated before the most recently generated block // template. lastGeneratedUnix := lastGenerated.Unix() for lastGen, c := range channels { if lastGen < lastGeneratedUnix { close(c) delete(channels, lastGen) } } // Remove the entry altogether if there are no more registered // channels. if len(channels) == 0 { delete(state.notifyMap, *latestHash) } }
go
func (state *gbtWorkState) notifyLongPollers(latestHash *chainhash.Hash, lastGenerated time.Time) { // Notify anything that is waiting for a block template update from a // hash which is not the hash of the tip of the best chain since their // work is now invalid. for hash, channels := range state.notifyMap { if !hash.IsEqual(latestHash) { for _, c := range channels { close(c) } delete(state.notifyMap, hash) } } // Return now if the provided last generated timestamp has not been // initialized. if lastGenerated.IsZero() { return } // Return now if there is nothing registered for updates to the current // best block hash. channels, ok := state.notifyMap[*latestHash] if !ok { return } // Notify anything that is waiting for a block template update from a // block template generated before the most recently generated block // template. lastGeneratedUnix := lastGenerated.Unix() for lastGen, c := range channels { if lastGen < lastGeneratedUnix { close(c) delete(channels, lastGen) } } // Remove the entry altogether if there are no more registered // channels. if len(channels) == 0 { delete(state.notifyMap, *latestHash) } }
[ "func", "(", "state", "*", "gbtWorkState", ")", "notifyLongPollers", "(", "latestHash", "*", "chainhash", ".", "Hash", ",", "lastGenerated", "time", ".", "Time", ")", "{", "// Notify anything that is waiting for a block template update from a", "// hash which is not the has...
// notifyLongPollers notifies any channels that have been registered to be // notified when block templates are stale. // // This function MUST be called with the state locked.
[ "notifyLongPollers", "notifies", "any", "channels", "that", "have", "been", "registered", "to", "be", "notified", "when", "block", "templates", "are", "stale", ".", "This", "function", "MUST", "be", "called", "with", "the", "state", "locked", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L1415-L1457
162,964
btcsuite/btcd
rpcserver.go
NotifyBlockConnected
func (state *gbtWorkState) NotifyBlockConnected(blockHash *chainhash.Hash) { go func() { state.Lock() defer state.Unlock() state.notifyLongPollers(blockHash, state.lastTxUpdate) }() }
go
func (state *gbtWorkState) NotifyBlockConnected(blockHash *chainhash.Hash) { go func() { state.Lock() defer state.Unlock() state.notifyLongPollers(blockHash, state.lastTxUpdate) }() }
[ "func", "(", "state", "*", "gbtWorkState", ")", "NotifyBlockConnected", "(", "blockHash", "*", "chainhash", ".", "Hash", ")", "{", "go", "func", "(", ")", "{", "state", ".", "Lock", "(", ")", "\n", "defer", "state", ".", "Unlock", "(", ")", "\n\n", "...
// NotifyBlockConnected uses the newly-connected block to notify any long poll // clients with a new block template when their existing block template is // stale due to the newly connected block.
[ "NotifyBlockConnected", "uses", "the", "newly", "-", "connected", "block", "to", "notify", "any", "long", "poll", "clients", "with", "a", "new", "block", "template", "when", "their", "existing", "block", "template", "is", "stale", "due", "to", "the", "newly", ...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L1462-L1469
162,965
btcsuite/btcd
rpcserver.go
NotifyMempoolTx
func (state *gbtWorkState) NotifyMempoolTx(lastUpdated time.Time) { go func() { state.Lock() defer state.Unlock() // No need to notify anything if no block templates have been generated // yet. if state.prevHash == nil || state.lastGenerated.IsZero() { return } if time.Now().After(state.lastGenerated.Add(time.Second * gbtRegenerateSeconds)) { state.notifyLongPollers(state.prevHash, lastUpdated) } }() }
go
func (state *gbtWorkState) NotifyMempoolTx(lastUpdated time.Time) { go func() { state.Lock() defer state.Unlock() // No need to notify anything if no block templates have been generated // yet. if state.prevHash == nil || state.lastGenerated.IsZero() { return } if time.Now().After(state.lastGenerated.Add(time.Second * gbtRegenerateSeconds)) { state.notifyLongPollers(state.prevHash, lastUpdated) } }() }
[ "func", "(", "state", "*", "gbtWorkState", ")", "NotifyMempoolTx", "(", "lastUpdated", "time", ".", "Time", ")", "{", "go", "func", "(", ")", "{", "state", ".", "Lock", "(", ")", "\n", "defer", "state", ".", "Unlock", "(", ")", "\n\n", "// No need to n...
// NotifyMempoolTx uses the new last updated time for the transaction memory // pool to notify any long poll clients with a new block template when their // existing block template is stale due to enough time passing and the contents // of the memory pool changing.
[ "NotifyMempoolTx", "uses", "the", "new", "last", "updated", "time", "for", "the", "transaction", "memory", "pool", "to", "notify", "any", "long", "poll", "clients", "with", "a", "new", "block", "template", "when", "their", "existing", "block", "template", "is"...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L1475-L1492
162,966
btcsuite/btcd
rpcserver.go
templateUpdateChan
func (state *gbtWorkState) templateUpdateChan(prevHash *chainhash.Hash, lastGenerated int64) chan struct{} { // Either get the current list of channels waiting for updates about // changes to block template for the previous hash or create a new one. channels, ok := state.notifyMap[*prevHash] if !ok { m := make(map[int64]chan struct{}) state.notifyMap[*prevHash] = m channels = m } // Get the current channel associated with the time the block template // was last generated or create a new one. c, ok := channels[lastGenerated] if !ok { c = make(chan struct{}) channels[lastGenerated] = c } return c }
go
func (state *gbtWorkState) templateUpdateChan(prevHash *chainhash.Hash, lastGenerated int64) chan struct{} { // Either get the current list of channels waiting for updates about // changes to block template for the previous hash or create a new one. channels, ok := state.notifyMap[*prevHash] if !ok { m := make(map[int64]chan struct{}) state.notifyMap[*prevHash] = m channels = m } // Get the current channel associated with the time the block template // was last generated or create a new one. c, ok := channels[lastGenerated] if !ok { c = make(chan struct{}) channels[lastGenerated] = c } return c }
[ "func", "(", "state", "*", "gbtWorkState", ")", "templateUpdateChan", "(", "prevHash", "*", "chainhash", ".", "Hash", ",", "lastGenerated", "int64", ")", "chan", "struct", "{", "}", "{", "// Either get the current list of channels waiting for updates about", "// changes...
// templateUpdateChan returns a channel that will be closed once the block // template associated with the passed previous hash and last generated time // is stale. The function will return existing channels for duplicate // parameters which allows multiple clients to wait for the same block template // without requiring a different channel for each client. // // This function MUST be called with the state locked.
[ "templateUpdateChan", "returns", "a", "channel", "that", "will", "be", "closed", "once", "the", "block", "template", "associated", "with", "the", "passed", "previous", "hash", "and", "last", "generated", "time", "is", "stale", ".", "The", "function", "will", "...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L1501-L1520
162,967
btcsuite/btcd
rpcserver.go
chainErrToGBTErrString
func chainErrToGBTErrString(err error) string { // When the passed error is not a RuleError, just return a generic // rejected string with the error text. ruleErr, ok := err.(blockchain.RuleError) if !ok { return "rejected: " + err.Error() } switch ruleErr.ErrorCode { case blockchain.ErrDuplicateBlock: return "duplicate" case blockchain.ErrBlockTooBig: return "bad-blk-length" case blockchain.ErrBlockWeightTooHigh: return "bad-blk-weight" case blockchain.ErrBlockVersionTooOld: return "bad-version" case blockchain.ErrInvalidTime: return "bad-time" case blockchain.ErrTimeTooOld: return "time-too-old" case blockchain.ErrTimeTooNew: return "time-too-new" case blockchain.ErrDifficultyTooLow: return "bad-diffbits" case blockchain.ErrUnexpectedDifficulty: return "bad-diffbits" case blockchain.ErrHighHash: return "high-hash" case blockchain.ErrBadMerkleRoot: return "bad-txnmrklroot" case blockchain.ErrBadCheckpoint: return "bad-checkpoint" case blockchain.ErrForkTooOld: return "fork-too-old" case blockchain.ErrCheckpointTimeTooOld: return "checkpoint-time-too-old" case blockchain.ErrNoTransactions: return "bad-txns-none" case blockchain.ErrNoTxInputs: return "bad-txns-noinputs" case blockchain.ErrNoTxOutputs: return "bad-txns-nooutputs" case blockchain.ErrTxTooBig: return "bad-txns-size" case blockchain.ErrBadTxOutValue: return "bad-txns-outputvalue" case blockchain.ErrDuplicateTxInputs: return "bad-txns-dupinputs" case blockchain.ErrBadTxInput: return "bad-txns-badinput" case blockchain.ErrMissingTxOut: return "bad-txns-missinginput" case blockchain.ErrUnfinalizedTx: return "bad-txns-unfinalizedtx" case blockchain.ErrDuplicateTx: return "bad-txns-duplicate" case blockchain.ErrOverwriteTx: return "bad-txns-overwrite" case blockchain.ErrImmatureSpend: return "bad-txns-maturity" case blockchain.ErrSpendTooHigh: return "bad-txns-highspend" case blockchain.ErrBadFees: return "bad-txns-fees" case blockchain.ErrTooManySigOps: return "high-sigops" case blockchain.ErrFirstTxNotCoinbase: return "bad-txns-nocoinbase" case blockchain.ErrMultipleCoinbases: return "bad-txns-multicoinbase" case blockchain.ErrBadCoinbaseScriptLen: return "bad-cb-length" case blockchain.ErrBadCoinbaseValue: return "bad-cb-value" case blockchain.ErrMissingCoinbaseHeight: return "bad-cb-height" case blockchain.ErrBadCoinbaseHeight: return "bad-cb-height" case blockchain.ErrScriptMalformed: return "bad-script-malformed" case blockchain.ErrScriptValidation: return "bad-script-validate" case blockchain.ErrUnexpectedWitness: return "unexpected-witness" case blockchain.ErrInvalidWitnessCommitment: return "bad-witness-nonce-size" case blockchain.ErrWitnessCommitmentMismatch: return "bad-witness-merkle-match" case blockchain.ErrPreviousBlockUnknown: return "prev-blk-not-found" case blockchain.ErrInvalidAncestorBlock: return "bad-prevblk" case blockchain.ErrPrevBlockNotBest: return "inconclusive-not-best-prvblk" } return "rejected: " + err.Error() }
go
func chainErrToGBTErrString(err error) string { // When the passed error is not a RuleError, just return a generic // rejected string with the error text. ruleErr, ok := err.(blockchain.RuleError) if !ok { return "rejected: " + err.Error() } switch ruleErr.ErrorCode { case blockchain.ErrDuplicateBlock: return "duplicate" case blockchain.ErrBlockTooBig: return "bad-blk-length" case blockchain.ErrBlockWeightTooHigh: return "bad-blk-weight" case blockchain.ErrBlockVersionTooOld: return "bad-version" case blockchain.ErrInvalidTime: return "bad-time" case blockchain.ErrTimeTooOld: return "time-too-old" case blockchain.ErrTimeTooNew: return "time-too-new" case blockchain.ErrDifficultyTooLow: return "bad-diffbits" case blockchain.ErrUnexpectedDifficulty: return "bad-diffbits" case blockchain.ErrHighHash: return "high-hash" case blockchain.ErrBadMerkleRoot: return "bad-txnmrklroot" case blockchain.ErrBadCheckpoint: return "bad-checkpoint" case blockchain.ErrForkTooOld: return "fork-too-old" case blockchain.ErrCheckpointTimeTooOld: return "checkpoint-time-too-old" case blockchain.ErrNoTransactions: return "bad-txns-none" case blockchain.ErrNoTxInputs: return "bad-txns-noinputs" case blockchain.ErrNoTxOutputs: return "bad-txns-nooutputs" case blockchain.ErrTxTooBig: return "bad-txns-size" case blockchain.ErrBadTxOutValue: return "bad-txns-outputvalue" case blockchain.ErrDuplicateTxInputs: return "bad-txns-dupinputs" case blockchain.ErrBadTxInput: return "bad-txns-badinput" case blockchain.ErrMissingTxOut: return "bad-txns-missinginput" case blockchain.ErrUnfinalizedTx: return "bad-txns-unfinalizedtx" case blockchain.ErrDuplicateTx: return "bad-txns-duplicate" case blockchain.ErrOverwriteTx: return "bad-txns-overwrite" case blockchain.ErrImmatureSpend: return "bad-txns-maturity" case blockchain.ErrSpendTooHigh: return "bad-txns-highspend" case blockchain.ErrBadFees: return "bad-txns-fees" case blockchain.ErrTooManySigOps: return "high-sigops" case blockchain.ErrFirstTxNotCoinbase: return "bad-txns-nocoinbase" case blockchain.ErrMultipleCoinbases: return "bad-txns-multicoinbase" case blockchain.ErrBadCoinbaseScriptLen: return "bad-cb-length" case blockchain.ErrBadCoinbaseValue: return "bad-cb-value" case blockchain.ErrMissingCoinbaseHeight: return "bad-cb-height" case blockchain.ErrBadCoinbaseHeight: return "bad-cb-height" case blockchain.ErrScriptMalformed: return "bad-script-malformed" case blockchain.ErrScriptValidation: return "bad-script-validate" case blockchain.ErrUnexpectedWitness: return "unexpected-witness" case blockchain.ErrInvalidWitnessCommitment: return "bad-witness-nonce-size" case blockchain.ErrWitnessCommitmentMismatch: return "bad-witness-merkle-match" case blockchain.ErrPreviousBlockUnknown: return "prev-blk-not-found" case blockchain.ErrInvalidAncestorBlock: return "bad-prevblk" case blockchain.ErrPrevBlockNotBest: return "inconclusive-not-best-prvblk" } return "rejected: " + err.Error() }
[ "func", "chainErrToGBTErrString", "(", "err", "error", ")", "string", "{", "// When the passed error is not a RuleError, just return a generic", "// rejected string with the error text.", "ruleErr", ",", "ok", ":=", "err", ".", "(", "blockchain", ".", "RuleError", ")", "\n"...
// chainErrToGBTErrString converts an error returned from btcchain to a string // which matches the reasons and format described in BIP0022 for rejection // reasons.
[ "chainErrToGBTErrString", "converts", "an", "error", "returned", "from", "btcchain", "to", "a", "string", "which", "matches", "the", "reasons", "and", "format", "described", "in", "BIP0022", "for", "rejection", "reasons", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L1987-L2085
162,968
btcsuite/btcd
rpcserver.go
handleGetCFilter
func handleGetCFilter(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { if s.cfg.CfIndex == nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCNoCFIndex, Message: "The CF index must be enabled for this command", } } c := cmd.(*btcjson.GetCFilterCmd) hash, err := chainhash.NewHashFromStr(c.Hash) if err != nil { return nil, rpcDecodeHexError(c.Hash) } filterBytes, err := s.cfg.CfIndex.FilterByBlockHash(hash, c.FilterType) if err != nil { rpcsLog.Debugf("Could not find committed filter for %v: %v", hash, err) return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCBlockNotFound, Message: "Block not found", } } rpcsLog.Debugf("Found committed filter for %v", hash) return hex.EncodeToString(filterBytes), nil }
go
func handleGetCFilter(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { if s.cfg.CfIndex == nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCNoCFIndex, Message: "The CF index must be enabled for this command", } } c := cmd.(*btcjson.GetCFilterCmd) hash, err := chainhash.NewHashFromStr(c.Hash) if err != nil { return nil, rpcDecodeHexError(c.Hash) } filterBytes, err := s.cfg.CfIndex.FilterByBlockHash(hash, c.FilterType) if err != nil { rpcsLog.Debugf("Could not find committed filter for %v: %v", hash, err) return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCBlockNotFound, Message: "Block not found", } } rpcsLog.Debugf("Found committed filter for %v", hash) return hex.EncodeToString(filterBytes), nil }
[ "func", "handleGetCFilter", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "s", ".", "cfg", ".", "CfIndex", "==", "ni...
// handleGetCFilter implements the getcfilter command.
[ "handleGetCFilter", "implements", "the", "getcfilter", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L2175-L2201
162,969
btcsuite/btcd
rpcserver.go
handleGetCFilterHeader
func handleGetCFilterHeader(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { if s.cfg.CfIndex == nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCNoCFIndex, Message: "The CF index must be enabled for this command", } } c := cmd.(*btcjson.GetCFilterHeaderCmd) hash, err := chainhash.NewHashFromStr(c.Hash) if err != nil { return nil, rpcDecodeHexError(c.Hash) } headerBytes, err := s.cfg.CfIndex.FilterHeaderByBlockHash(hash, c.FilterType) if len(headerBytes) > 0 { rpcsLog.Debugf("Found header of committed filter for %v", hash) } else { rpcsLog.Debugf("Could not find header of committed filter for %v: %v", hash, err) return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCBlockNotFound, Message: "Block not found", } } hash.SetBytes(headerBytes) return hash.String(), nil }
go
func handleGetCFilterHeader(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { if s.cfg.CfIndex == nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCNoCFIndex, Message: "The CF index must be enabled for this command", } } c := cmd.(*btcjson.GetCFilterHeaderCmd) hash, err := chainhash.NewHashFromStr(c.Hash) if err != nil { return nil, rpcDecodeHexError(c.Hash) } headerBytes, err := s.cfg.CfIndex.FilterHeaderByBlockHash(hash, c.FilterType) if len(headerBytes) > 0 { rpcsLog.Debugf("Found header of committed filter for %v", hash) } else { rpcsLog.Debugf("Could not find header of committed filter for %v: %v", hash, err) return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCBlockNotFound, Message: "Block not found", } } hash.SetBytes(headerBytes) return hash.String(), nil }
[ "func", "handleGetCFilterHeader", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "s", ".", "cfg", ".", "CfIndex", "==",...
// handleGetCFilterHeader implements the getcfilterheader command.
[ "handleGetCFilterHeader", "implements", "the", "getcfilterheader", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L2204-L2232
162,970
btcsuite/btcd
rpcserver.go
handleGetConnectionCount
func handleGetConnectionCount(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { return s.cfg.ConnMgr.ConnectedCount(), nil }
go
func handleGetConnectionCount(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { return s.cfg.ConnMgr.ConnectedCount(), nil }
[ "func", "handleGetConnectionCount", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "s", ".", "cfg", ".", "ConnMgr", ...
// handleGetConnectionCount implements the getconnectioncount command.
[ "handleGetConnectionCount", "implements", "the", "getconnectioncount", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L2235-L2237
162,971
btcsuite/btcd
rpcserver.go
handleGetCurrentNet
func handleGetCurrentNet(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { return s.cfg.ChainParams.Net, nil }
go
func handleGetCurrentNet(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { return s.cfg.ChainParams.Net, nil }
[ "func", "handleGetCurrentNet", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "s", ".", "cfg", ".", "ChainParams", ...
// handleGetCurrentNet implements the getcurrentnet command.
[ "handleGetCurrentNet", "implements", "the", "getcurrentnet", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L2240-L2242
162,972
btcsuite/btcd
rpcserver.go
handleGetDifficulty
func handleGetDifficulty(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { best := s.cfg.Chain.BestSnapshot() return getDifficultyRatio(best.Bits, s.cfg.ChainParams), nil }
go
func handleGetDifficulty(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { best := s.cfg.Chain.BestSnapshot() return getDifficultyRatio(best.Bits, s.cfg.ChainParams), nil }
[ "func", "handleGetDifficulty", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "best", ":=", "s", ".", "cfg", ".", "Chain", ...
// handleGetDifficulty implements the getdifficulty command.
[ "handleGetDifficulty", "implements", "the", "getdifficulty", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L2245-L2248
162,973
btcsuite/btcd
rpcserver.go
handleGetGenerate
func handleGetGenerate(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { return s.cfg.CPUMiner.IsMining(), nil }
go
func handleGetGenerate(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { return s.cfg.CPUMiner.IsMining(), nil }
[ "func", "handleGetGenerate", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "s", ".", "cfg", ".", "CPUMiner", ".", ...
// handleGetGenerate implements the getgenerate command.
[ "handleGetGenerate", "implements", "the", "getgenerate", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L2251-L2253
162,974
btcsuite/btcd
rpcserver.go
handleGetHashesPerSec
func handleGetHashesPerSec(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { return int64(s.cfg.CPUMiner.HashesPerSecond()), nil }
go
func handleGetHashesPerSec(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { return int64(s.cfg.CPUMiner.HashesPerSecond()), nil }
[ "func", "handleGetHashesPerSec", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "int64", "(", "s", ".", "cfg", ".",...
// handleGetHashesPerSec implements the gethashespersec command.
[ "handleGetHashesPerSec", "implements", "the", "gethashespersec", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L2256-L2258
162,975
btcsuite/btcd
rpcserver.go
handleGetInfo
func handleGetInfo(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { best := s.cfg.Chain.BestSnapshot() ret := &btcjson.InfoChainResult{ Version: int32(1000000*appMajor + 10000*appMinor + 100*appPatch), ProtocolVersion: int32(maxProtocolVersion), Blocks: best.Height, TimeOffset: int64(s.cfg.TimeSource.Offset().Seconds()), Connections: s.cfg.ConnMgr.ConnectedCount(), Proxy: cfg.Proxy, Difficulty: getDifficultyRatio(best.Bits, s.cfg.ChainParams), TestNet: cfg.TestNet3, RelayFee: cfg.minRelayTxFee.ToBTC(), } return ret, nil }
go
func handleGetInfo(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { best := s.cfg.Chain.BestSnapshot() ret := &btcjson.InfoChainResult{ Version: int32(1000000*appMajor + 10000*appMinor + 100*appPatch), ProtocolVersion: int32(maxProtocolVersion), Blocks: best.Height, TimeOffset: int64(s.cfg.TimeSource.Offset().Seconds()), Connections: s.cfg.ConnMgr.ConnectedCount(), Proxy: cfg.Proxy, Difficulty: getDifficultyRatio(best.Bits, s.cfg.ChainParams), TestNet: cfg.TestNet3, RelayFee: cfg.minRelayTxFee.ToBTC(), } return ret, nil }
[ "func", "handleGetInfo", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "best", ":=", "s", ".", "cfg", ".", "Chain", ".", ...
// handleGetInfo implements the getinfo command. We only return the fields // that are not related to wallet functionality.
[ "handleGetInfo", "implements", "the", "getinfo", "command", ".", "We", "only", "return", "the", "fields", "that", "are", "not", "related", "to", "wallet", "functionality", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L2303-L2318
162,976
btcsuite/btcd
rpcserver.go
handleGetMempoolInfo
func handleGetMempoolInfo(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { mempoolTxns := s.cfg.TxMemPool.TxDescs() var numBytes int64 for _, txD := range mempoolTxns { numBytes += int64(txD.Tx.MsgTx().SerializeSize()) } ret := &btcjson.GetMempoolInfoResult{ Size: int64(len(mempoolTxns)), Bytes: numBytes, } return ret, nil }
go
func handleGetMempoolInfo(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { mempoolTxns := s.cfg.TxMemPool.TxDescs() var numBytes int64 for _, txD := range mempoolTxns { numBytes += int64(txD.Tx.MsgTx().SerializeSize()) } ret := &btcjson.GetMempoolInfoResult{ Size: int64(len(mempoolTxns)), Bytes: numBytes, } return ret, nil }
[ "func", "handleGetMempoolInfo", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "mempoolTxns", ":=", "s", ".", "cfg", ".", "Tx...
// handleGetMempoolInfo implements the getmempoolinfo command.
[ "handleGetMempoolInfo", "implements", "the", "getmempoolinfo", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L2321-L2335
162,977
btcsuite/btcd
rpcserver.go
handleGetMiningInfo
func handleGetMiningInfo(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { // Create a default getnetworkhashps command to use defaults and make // use of the existing getnetworkhashps handler. gnhpsCmd := btcjson.NewGetNetworkHashPSCmd(nil, nil) networkHashesPerSecIface, err := handleGetNetworkHashPS(s, gnhpsCmd, closeChan) if err != nil { return nil, err } networkHashesPerSec, ok := networkHashesPerSecIface.(int64) if !ok { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInternal.Code, Message: "networkHashesPerSec is not an int64", } } best := s.cfg.Chain.BestSnapshot() result := btcjson.GetMiningInfoResult{ Blocks: int64(best.Height), CurrentBlockSize: best.BlockSize, CurrentBlockWeight: best.BlockWeight, CurrentBlockTx: best.NumTxns, Difficulty: getDifficultyRatio(best.Bits, s.cfg.ChainParams), Generate: s.cfg.CPUMiner.IsMining(), GenProcLimit: s.cfg.CPUMiner.NumWorkers(), HashesPerSec: int64(s.cfg.CPUMiner.HashesPerSecond()), NetworkHashPS: networkHashesPerSec, PooledTx: uint64(s.cfg.TxMemPool.Count()), TestNet: cfg.TestNet3, } return &result, nil }
go
func handleGetMiningInfo(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { // Create a default getnetworkhashps command to use defaults and make // use of the existing getnetworkhashps handler. gnhpsCmd := btcjson.NewGetNetworkHashPSCmd(nil, nil) networkHashesPerSecIface, err := handleGetNetworkHashPS(s, gnhpsCmd, closeChan) if err != nil { return nil, err } networkHashesPerSec, ok := networkHashesPerSecIface.(int64) if !ok { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInternal.Code, Message: "networkHashesPerSec is not an int64", } } best := s.cfg.Chain.BestSnapshot() result := btcjson.GetMiningInfoResult{ Blocks: int64(best.Height), CurrentBlockSize: best.BlockSize, CurrentBlockWeight: best.BlockWeight, CurrentBlockTx: best.NumTxns, Difficulty: getDifficultyRatio(best.Bits, s.cfg.ChainParams), Generate: s.cfg.CPUMiner.IsMining(), GenProcLimit: s.cfg.CPUMiner.NumWorkers(), HashesPerSec: int64(s.cfg.CPUMiner.HashesPerSecond()), NetworkHashPS: networkHashesPerSec, PooledTx: uint64(s.cfg.TxMemPool.Count()), TestNet: cfg.TestNet3, } return &result, nil }
[ "func", "handleGetMiningInfo", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "// Create a default getnetworkhashps command to use defaul...
// handleGetMiningInfo implements the getmininginfo command. We only return the // fields that are not related to wallet functionality.
[ "handleGetMiningInfo", "implements", "the", "getmininginfo", "command", ".", "We", "only", "return", "the", "fields", "that", "are", "not", "related", "to", "wallet", "functionality", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L2339-L2371
162,978
btcsuite/btcd
rpcserver.go
handleGetNetTotals
func handleGetNetTotals(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { totalBytesRecv, totalBytesSent := s.cfg.ConnMgr.NetTotals() reply := &btcjson.GetNetTotalsResult{ TotalBytesRecv: totalBytesRecv, TotalBytesSent: totalBytesSent, TimeMillis: time.Now().UTC().UnixNano() / int64(time.Millisecond), } return reply, nil }
go
func handleGetNetTotals(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { totalBytesRecv, totalBytesSent := s.cfg.ConnMgr.NetTotals() reply := &btcjson.GetNetTotalsResult{ TotalBytesRecv: totalBytesRecv, TotalBytesSent: totalBytesSent, TimeMillis: time.Now().UTC().UnixNano() / int64(time.Millisecond), } return reply, nil }
[ "func", "handleGetNetTotals", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "totalBytesRecv", ",", "totalBytesSent", ":=", "s", ...
// handleGetNetTotals implements the getnettotals command.
[ "handleGetNetTotals", "implements", "the", "getnettotals", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L2374-L2382
162,979
btcsuite/btcd
rpcserver.go
handleGetNetworkHashPS
func handleGetNetworkHashPS(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { // Note: All valid error return paths should return an int64. // Literal zeros are inferred as int, and won't coerce to int64 // because the return value is an interface{}. c := cmd.(*btcjson.GetNetworkHashPSCmd) // When the passed height is too high or zero, just return 0 now // since we can't reasonably calculate the number of network hashes // per second from invalid values. When it's negative, use the current // best block height. best := s.cfg.Chain.BestSnapshot() endHeight := int32(-1) if c.Height != nil { endHeight = int32(*c.Height) } if endHeight > best.Height || endHeight == 0 { return int64(0), nil } if endHeight < 0 { endHeight = best.Height } // Calculate the number of blocks per retarget interval based on the // chain parameters. blocksPerRetarget := int32(s.cfg.ChainParams.TargetTimespan / s.cfg.ChainParams.TargetTimePerBlock) // Calculate the starting block height based on the passed number of // blocks. When the passed value is negative, use the last block the // difficulty changed as the starting height. Also make sure the // starting height is not before the beginning of the chain. numBlocks := int32(120) if c.Blocks != nil { numBlocks = int32(*c.Blocks) } var startHeight int32 if numBlocks <= 0 { startHeight = endHeight - ((endHeight % blocksPerRetarget) + 1) } else { startHeight = endHeight - numBlocks } if startHeight < 0 { startHeight = 0 } rpcsLog.Debugf("Calculating network hashes per second from %d to %d", startHeight, endHeight) // Find the min and max block timestamps as well as calculate the total // amount of work that happened between the start and end blocks. var minTimestamp, maxTimestamp time.Time totalWork := big.NewInt(0) for curHeight := startHeight; curHeight <= endHeight; curHeight++ { hash, err := s.cfg.Chain.BlockHashByHeight(curHeight) if err != nil { context := "Failed to fetch block hash" return nil, internalRPCError(err.Error(), context) } // Fetch the header from chain. header, err := s.cfg.Chain.HeaderByHash(hash) if err != nil { context := "Failed to fetch block header" return nil, internalRPCError(err.Error(), context) } if curHeight == startHeight { minTimestamp = header.Timestamp maxTimestamp = minTimestamp } else { totalWork.Add(totalWork, blockchain.CalcWork(header.Bits)) if minTimestamp.After(header.Timestamp) { minTimestamp = header.Timestamp } if maxTimestamp.Before(header.Timestamp) { maxTimestamp = header.Timestamp } } } // Calculate the difference in seconds between the min and max block // timestamps and avoid division by zero in the case where there is no // time difference. timeDiff := int64(maxTimestamp.Sub(minTimestamp) / time.Second) if timeDiff == 0 { return int64(0), nil } hashesPerSec := new(big.Int).Div(totalWork, big.NewInt(timeDiff)) return hashesPerSec.Int64(), nil }
go
func handleGetNetworkHashPS(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { // Note: All valid error return paths should return an int64. // Literal zeros are inferred as int, and won't coerce to int64 // because the return value is an interface{}. c := cmd.(*btcjson.GetNetworkHashPSCmd) // When the passed height is too high or zero, just return 0 now // since we can't reasonably calculate the number of network hashes // per second from invalid values. When it's negative, use the current // best block height. best := s.cfg.Chain.BestSnapshot() endHeight := int32(-1) if c.Height != nil { endHeight = int32(*c.Height) } if endHeight > best.Height || endHeight == 0 { return int64(0), nil } if endHeight < 0 { endHeight = best.Height } // Calculate the number of blocks per retarget interval based on the // chain parameters. blocksPerRetarget := int32(s.cfg.ChainParams.TargetTimespan / s.cfg.ChainParams.TargetTimePerBlock) // Calculate the starting block height based on the passed number of // blocks. When the passed value is negative, use the last block the // difficulty changed as the starting height. Also make sure the // starting height is not before the beginning of the chain. numBlocks := int32(120) if c.Blocks != nil { numBlocks = int32(*c.Blocks) } var startHeight int32 if numBlocks <= 0 { startHeight = endHeight - ((endHeight % blocksPerRetarget) + 1) } else { startHeight = endHeight - numBlocks } if startHeight < 0 { startHeight = 0 } rpcsLog.Debugf("Calculating network hashes per second from %d to %d", startHeight, endHeight) // Find the min and max block timestamps as well as calculate the total // amount of work that happened between the start and end blocks. var minTimestamp, maxTimestamp time.Time totalWork := big.NewInt(0) for curHeight := startHeight; curHeight <= endHeight; curHeight++ { hash, err := s.cfg.Chain.BlockHashByHeight(curHeight) if err != nil { context := "Failed to fetch block hash" return nil, internalRPCError(err.Error(), context) } // Fetch the header from chain. header, err := s.cfg.Chain.HeaderByHash(hash) if err != nil { context := "Failed to fetch block header" return nil, internalRPCError(err.Error(), context) } if curHeight == startHeight { minTimestamp = header.Timestamp maxTimestamp = minTimestamp } else { totalWork.Add(totalWork, blockchain.CalcWork(header.Bits)) if minTimestamp.After(header.Timestamp) { minTimestamp = header.Timestamp } if maxTimestamp.Before(header.Timestamp) { maxTimestamp = header.Timestamp } } } // Calculate the difference in seconds between the min and max block // timestamps and avoid division by zero in the case where there is no // time difference. timeDiff := int64(maxTimestamp.Sub(minTimestamp) / time.Second) if timeDiff == 0 { return int64(0), nil } hashesPerSec := new(big.Int).Div(totalWork, big.NewInt(timeDiff)) return hashesPerSec.Int64(), nil }
[ "func", "handleGetNetworkHashPS", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "// Note: All valid error return paths should return an ...
// handleGetNetworkHashPS implements the getnetworkhashps command.
[ "handleGetNetworkHashPS", "implements", "the", "getnetworkhashps", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L2385-L2476
162,980
btcsuite/btcd
rpcserver.go
handleGetPeerInfo
func handleGetPeerInfo(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { peers := s.cfg.ConnMgr.ConnectedPeers() syncPeerID := s.cfg.SyncMgr.SyncPeerID() infos := make([]*btcjson.GetPeerInfoResult, 0, len(peers)) for _, p := range peers { statsSnap := p.ToPeer().StatsSnapshot() info := &btcjson.GetPeerInfoResult{ ID: statsSnap.ID, Addr: statsSnap.Addr, AddrLocal: p.ToPeer().LocalAddr().String(), Services: fmt.Sprintf("%08d", uint64(statsSnap.Services)), RelayTxes: !p.IsTxRelayDisabled(), LastSend: statsSnap.LastSend.Unix(), LastRecv: statsSnap.LastRecv.Unix(), BytesSent: statsSnap.BytesSent, BytesRecv: statsSnap.BytesRecv, ConnTime: statsSnap.ConnTime.Unix(), PingTime: float64(statsSnap.LastPingMicros), TimeOffset: statsSnap.TimeOffset, Version: statsSnap.Version, SubVer: statsSnap.UserAgent, Inbound: statsSnap.Inbound, StartingHeight: statsSnap.StartingHeight, CurrentHeight: statsSnap.LastBlock, BanScore: int32(p.BanScore()), FeeFilter: p.FeeFilter(), SyncNode: statsSnap.ID == syncPeerID, } if p.ToPeer().LastPingNonce() != 0 { wait := float64(time.Since(statsSnap.LastPingTime).Nanoseconds()) // We actually want microseconds. info.PingWait = wait / 1000 } infos = append(infos, info) } return infos, nil }
go
func handleGetPeerInfo(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { peers := s.cfg.ConnMgr.ConnectedPeers() syncPeerID := s.cfg.SyncMgr.SyncPeerID() infos := make([]*btcjson.GetPeerInfoResult, 0, len(peers)) for _, p := range peers { statsSnap := p.ToPeer().StatsSnapshot() info := &btcjson.GetPeerInfoResult{ ID: statsSnap.ID, Addr: statsSnap.Addr, AddrLocal: p.ToPeer().LocalAddr().String(), Services: fmt.Sprintf("%08d", uint64(statsSnap.Services)), RelayTxes: !p.IsTxRelayDisabled(), LastSend: statsSnap.LastSend.Unix(), LastRecv: statsSnap.LastRecv.Unix(), BytesSent: statsSnap.BytesSent, BytesRecv: statsSnap.BytesRecv, ConnTime: statsSnap.ConnTime.Unix(), PingTime: float64(statsSnap.LastPingMicros), TimeOffset: statsSnap.TimeOffset, Version: statsSnap.Version, SubVer: statsSnap.UserAgent, Inbound: statsSnap.Inbound, StartingHeight: statsSnap.StartingHeight, CurrentHeight: statsSnap.LastBlock, BanScore: int32(p.BanScore()), FeeFilter: p.FeeFilter(), SyncNode: statsSnap.ID == syncPeerID, } if p.ToPeer().LastPingNonce() != 0 { wait := float64(time.Since(statsSnap.LastPingTime).Nanoseconds()) // We actually want microseconds. info.PingWait = wait / 1000 } infos = append(infos, info) } return infos, nil }
[ "func", "handleGetPeerInfo", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "peers", ":=", "s", ".", "cfg", ".", "ConnMgr", ...
// handleGetPeerInfo implements the getpeerinfo command.
[ "handleGetPeerInfo", "implements", "the", "getpeerinfo", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L2479-L2515
162,981
btcsuite/btcd
rpcserver.go
handleGetRawMempool
func handleGetRawMempool(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.GetRawMempoolCmd) mp := s.cfg.TxMemPool if c.Verbose != nil && *c.Verbose { return mp.RawMempoolVerbose(), nil } // The response is simply an array of the transaction hashes if the // verbose flag is not set. descs := mp.TxDescs() hashStrings := make([]string, len(descs)) for i := range hashStrings { hashStrings[i] = descs[i].Tx.Hash().String() } return hashStrings, nil }
go
func handleGetRawMempool(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.GetRawMempoolCmd) mp := s.cfg.TxMemPool if c.Verbose != nil && *c.Verbose { return mp.RawMempoolVerbose(), nil } // The response is simply an array of the transaction hashes if the // verbose flag is not set. descs := mp.TxDescs() hashStrings := make([]string, len(descs)) for i := range hashStrings { hashStrings[i] = descs[i].Tx.Hash().String() } return hashStrings, nil }
[ "func", "handleGetRawMempool", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "c", ":=", "cmd", ".", "(", "*", "btcjson", "...
// handleGetRawMempool implements the getrawmempool command.
[ "handleGetRawMempool", "implements", "the", "getrawmempool", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L2518-L2535
162,982
btcsuite/btcd
rpcserver.go
handleHelp
func handleHelp(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.HelpCmd) // Provide a usage overview of all commands when no specific command // was specified. var command string if c.Command != nil { command = *c.Command } if command == "" { usage, err := s.helpCacher.rpcUsage(false) if err != nil { context := "Failed to generate RPC usage" return nil, internalRPCError(err.Error(), context) } return usage, nil } // Check that the command asked for is supported and implemented. Only // search the main list of handlers since help should not be provided // for commands that are unimplemented or related to wallet // functionality. if _, ok := rpcHandlers[command]; !ok { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInvalidParameter, Message: "Unknown command: " + command, } } // Get the help for the command. help, err := s.helpCacher.rpcMethodHelp(command) if err != nil { context := "Failed to generate help" return nil, internalRPCError(err.Error(), context) } return help, nil }
go
func handleHelp(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.HelpCmd) // Provide a usage overview of all commands when no specific command // was specified. var command string if c.Command != nil { command = *c.Command } if command == "" { usage, err := s.helpCacher.rpcUsage(false) if err != nil { context := "Failed to generate RPC usage" return nil, internalRPCError(err.Error(), context) } return usage, nil } // Check that the command asked for is supported and implemented. Only // search the main list of handlers since help should not be provided // for commands that are unimplemented or related to wallet // functionality. if _, ok := rpcHandlers[command]; !ok { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInvalidParameter, Message: "Unknown command: " + command, } } // Get the help for the command. help, err := s.helpCacher.rpcMethodHelp(command) if err != nil { context := "Failed to generate help" return nil, internalRPCError(err.Error(), context) } return help, nil }
[ "func", "handleHelp", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "c", ":=", "cmd", ".", "(", "*", "btcjson", ".", "He...
// handleHelp implements the help command.
[ "handleHelp", "implements", "the", "help", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L2763-L2799
162,983
btcsuite/btcd
rpcserver.go
handlePing
func handlePing(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { // Ask server to ping \o_ nonce, err := wire.RandomUint64() if err != nil { return nil, internalRPCError("Not sending ping - failed to "+ "generate nonce: "+err.Error(), "") } s.cfg.ConnMgr.BroadcastMessage(wire.NewMsgPing(nonce)) return nil, nil }
go
func handlePing(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { // Ask server to ping \o_ nonce, err := wire.RandomUint64() if err != nil { return nil, internalRPCError("Not sending ping - failed to "+ "generate nonce: "+err.Error(), "") } s.cfg.ConnMgr.BroadcastMessage(wire.NewMsgPing(nonce)) return nil, nil }
[ "func", "handlePing", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "// Ask server to ping \\o_", "nonce", ",", "err", ":=", "...
// handlePing implements the ping command.
[ "handlePing", "implements", "the", "ping", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L2802-L2812
162,984
btcsuite/btcd
rpcserver.go
fetchInputTxos
func fetchInputTxos(s *rpcServer, tx *wire.MsgTx) (map[wire.OutPoint]wire.TxOut, error) { mp := s.cfg.TxMemPool originOutputs := make(map[wire.OutPoint]wire.TxOut) for txInIndex, txIn := range tx.TxIn { // Attempt to fetch and use the referenced transaction from the // memory pool. origin := &txIn.PreviousOutPoint originTx, err := mp.FetchTransaction(&origin.Hash) if err == nil { txOuts := originTx.MsgTx().TxOut if origin.Index >= uint32(len(txOuts)) { errStr := fmt.Sprintf("unable to find output "+ "%v referenced from transaction %s:%d", origin, tx.TxHash(), txInIndex) return nil, internalRPCError(errStr, "") } originOutputs[*origin] = *txOuts[origin.Index] continue } // Look up the location of the transaction. blockRegion, err := s.cfg.TxIndex.TxBlockRegion(&origin.Hash) if err != nil { context := "Failed to retrieve transaction location" return nil, internalRPCError(err.Error(), context) } if blockRegion == nil { return nil, rpcNoTxInfoError(&origin.Hash) } // Load the raw transaction bytes from the database. var txBytes []byte err = s.cfg.DB.View(func(dbTx database.Tx) error { var err error txBytes, err = dbTx.FetchBlockRegion(blockRegion) return err }) if err != nil { return nil, rpcNoTxInfoError(&origin.Hash) } // Deserialize the transaction var msgTx wire.MsgTx err = msgTx.Deserialize(bytes.NewReader(txBytes)) if err != nil { context := "Failed to deserialize transaction" return nil, internalRPCError(err.Error(), context) } // Add the referenced output to the map. if origin.Index >= uint32(len(msgTx.TxOut)) { errStr := fmt.Sprintf("unable to find output %v "+ "referenced from transaction %s:%d", origin, tx.TxHash(), txInIndex) return nil, internalRPCError(errStr, "") } originOutputs[*origin] = *msgTx.TxOut[origin.Index] } return originOutputs, nil }
go
func fetchInputTxos(s *rpcServer, tx *wire.MsgTx) (map[wire.OutPoint]wire.TxOut, error) { mp := s.cfg.TxMemPool originOutputs := make(map[wire.OutPoint]wire.TxOut) for txInIndex, txIn := range tx.TxIn { // Attempt to fetch and use the referenced transaction from the // memory pool. origin := &txIn.PreviousOutPoint originTx, err := mp.FetchTransaction(&origin.Hash) if err == nil { txOuts := originTx.MsgTx().TxOut if origin.Index >= uint32(len(txOuts)) { errStr := fmt.Sprintf("unable to find output "+ "%v referenced from transaction %s:%d", origin, tx.TxHash(), txInIndex) return nil, internalRPCError(errStr, "") } originOutputs[*origin] = *txOuts[origin.Index] continue } // Look up the location of the transaction. blockRegion, err := s.cfg.TxIndex.TxBlockRegion(&origin.Hash) if err != nil { context := "Failed to retrieve transaction location" return nil, internalRPCError(err.Error(), context) } if blockRegion == nil { return nil, rpcNoTxInfoError(&origin.Hash) } // Load the raw transaction bytes from the database. var txBytes []byte err = s.cfg.DB.View(func(dbTx database.Tx) error { var err error txBytes, err = dbTx.FetchBlockRegion(blockRegion) return err }) if err != nil { return nil, rpcNoTxInfoError(&origin.Hash) } // Deserialize the transaction var msgTx wire.MsgTx err = msgTx.Deserialize(bytes.NewReader(txBytes)) if err != nil { context := "Failed to deserialize transaction" return nil, internalRPCError(err.Error(), context) } // Add the referenced output to the map. if origin.Index >= uint32(len(msgTx.TxOut)) { errStr := fmt.Sprintf("unable to find output %v "+ "referenced from transaction %s:%d", origin, tx.TxHash(), txInIndex) return nil, internalRPCError(errStr, "") } originOutputs[*origin] = *msgTx.TxOut[origin.Index] } return originOutputs, nil }
[ "func", "fetchInputTxos", "(", "s", "*", "rpcServer", ",", "tx", "*", "wire", ".", "MsgTx", ")", "(", "map", "[", "wire", ".", "OutPoint", "]", "wire", ".", "TxOut", ",", "error", ")", "{", "mp", ":=", "s", ".", "cfg", ".", "TxMemPool", "\n", "or...
// fetchInputTxos fetches the outpoints from all transactions referenced by the // inputs to the passed transaction by checking the transaction mempool first // then the transaction index for those already mined into blocks.
[ "fetchInputTxos", "fetches", "the", "outpoints", "from", "all", "transactions", "referenced", "by", "the", "inputs", "to", "the", "passed", "transaction", "by", "checking", "the", "transaction", "mempool", "first", "then", "the", "transaction", "index", "for", "th...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L2830-L2891
162,985
btcsuite/btcd
rpcserver.go
fetchMempoolTxnsForAddress
func fetchMempoolTxnsForAddress(s *rpcServer, addr btcutil.Address, numToSkip, numRequested uint32) ([]*btcutil.Tx, uint32) { // There are no entries to return when there are less available than the // number being skipped. mpTxns := s.cfg.AddrIndex.UnconfirmedTxnsForAddress(addr) numAvailable := uint32(len(mpTxns)) if numToSkip > numAvailable { return nil, numAvailable } // Filter the available entries based on the number to skip and number // requested. rangeEnd := numToSkip + numRequested if rangeEnd > numAvailable { rangeEnd = numAvailable } return mpTxns[numToSkip:rangeEnd], numToSkip }
go
func fetchMempoolTxnsForAddress(s *rpcServer, addr btcutil.Address, numToSkip, numRequested uint32) ([]*btcutil.Tx, uint32) { // There are no entries to return when there are less available than the // number being skipped. mpTxns := s.cfg.AddrIndex.UnconfirmedTxnsForAddress(addr) numAvailable := uint32(len(mpTxns)) if numToSkip > numAvailable { return nil, numAvailable } // Filter the available entries based on the number to skip and number // requested. rangeEnd := numToSkip + numRequested if rangeEnd > numAvailable { rangeEnd = numAvailable } return mpTxns[numToSkip:rangeEnd], numToSkip }
[ "func", "fetchMempoolTxnsForAddress", "(", "s", "*", "rpcServer", ",", "addr", "btcutil", ".", "Address", ",", "numToSkip", ",", "numRequested", "uint32", ")", "(", "[", "]", "*", "btcutil", ".", "Tx", ",", "uint32", ")", "{", "// There are no entries to retur...
// fetchMempoolTxnsForAddress queries the address index for all unconfirmed // transactions that involve the provided address. The results will be limited // by the number to skip and the number requested.
[ "fetchMempoolTxnsForAddress", "queries", "the", "address", "index", "for", "all", "unconfirmed", "transactions", "that", "involve", "the", "provided", "address", ".", "The", "results", "will", "be", "limited", "by", "the", "number", "to", "skip", "and", "the", "...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L3017-L3033
162,986
btcsuite/btcd
rpcserver.go
handleSendRawTransaction
func handleSendRawTransaction(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.SendRawTransactionCmd) // Deserialize and send off to tx relay hexStr := c.HexTx if len(hexStr)%2 != 0 { hexStr = "0" + hexStr } serializedTx, err := hex.DecodeString(hexStr) if err != nil { return nil, rpcDecodeHexError(hexStr) } var msgTx wire.MsgTx err = msgTx.Deserialize(bytes.NewReader(serializedTx)) if err != nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCDeserialization, Message: "TX decode failed: " + err.Error(), } } // Use 0 for the tag to represent local node. tx := btcutil.NewTx(&msgTx) acceptedTxs, err := s.cfg.TxMemPool.ProcessTransaction(tx, false, false, 0) if err != nil { // When the error is a rule error, it means the transaction was // simply rejected as opposed to something actually going wrong, // so log it as such. Otherwise, something really did go wrong, // so log it as an actual error. In both cases, a JSON-RPC // error is returned to the client with the deserialization // error code (to match bitcoind behavior). if _, ok := err.(mempool.RuleError); ok { rpcsLog.Debugf("Rejected transaction %v: %v", tx.Hash(), err) } else { rpcsLog.Errorf("Failed to process transaction %v: %v", tx.Hash(), err) } return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCDeserialization, Message: "TX rejected: " + err.Error(), } } // When the transaction was accepted it should be the first item in the // returned array of accepted transactions. The only way this will not // be true is if the API for ProcessTransaction changes and this code is // not properly updated, but ensure the condition holds as a safeguard. // // Also, since an error is being returned to the caller, ensure the // transaction is removed from the memory pool. if len(acceptedTxs) == 0 || !acceptedTxs[0].Tx.Hash().IsEqual(tx.Hash()) { s.cfg.TxMemPool.RemoveTransaction(tx, true) errStr := fmt.Sprintf("transaction %v is not in accepted list", tx.Hash()) return nil, internalRPCError(errStr, "") } // Generate and relay inventory vectors for all newly accepted // transactions into the memory pool due to the original being // accepted. s.cfg.ConnMgr.RelayTransactions(acceptedTxs) // Notify both websocket and getblocktemplate long poll clients of all // newly accepted transactions. s.NotifyNewTransactions(acceptedTxs) // Keep track of all the sendrawtransaction request txns so that they // can be rebroadcast if they don't make their way into a block. txD := acceptedTxs[0] iv := wire.NewInvVect(wire.InvTypeTx, txD.Tx.Hash()) s.cfg.ConnMgr.AddRebroadcastInventory(iv, txD) return tx.Hash().String(), nil }
go
func handleSendRawTransaction(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.SendRawTransactionCmd) // Deserialize and send off to tx relay hexStr := c.HexTx if len(hexStr)%2 != 0 { hexStr = "0" + hexStr } serializedTx, err := hex.DecodeString(hexStr) if err != nil { return nil, rpcDecodeHexError(hexStr) } var msgTx wire.MsgTx err = msgTx.Deserialize(bytes.NewReader(serializedTx)) if err != nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCDeserialization, Message: "TX decode failed: " + err.Error(), } } // Use 0 for the tag to represent local node. tx := btcutil.NewTx(&msgTx) acceptedTxs, err := s.cfg.TxMemPool.ProcessTransaction(tx, false, false, 0) if err != nil { // When the error is a rule error, it means the transaction was // simply rejected as opposed to something actually going wrong, // so log it as such. Otherwise, something really did go wrong, // so log it as an actual error. In both cases, a JSON-RPC // error is returned to the client with the deserialization // error code (to match bitcoind behavior). if _, ok := err.(mempool.RuleError); ok { rpcsLog.Debugf("Rejected transaction %v: %v", tx.Hash(), err) } else { rpcsLog.Errorf("Failed to process transaction %v: %v", tx.Hash(), err) } return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCDeserialization, Message: "TX rejected: " + err.Error(), } } // When the transaction was accepted it should be the first item in the // returned array of accepted transactions. The only way this will not // be true is if the API for ProcessTransaction changes and this code is // not properly updated, but ensure the condition holds as a safeguard. // // Also, since an error is being returned to the caller, ensure the // transaction is removed from the memory pool. if len(acceptedTxs) == 0 || !acceptedTxs[0].Tx.Hash().IsEqual(tx.Hash()) { s.cfg.TxMemPool.RemoveTransaction(tx, true) errStr := fmt.Sprintf("transaction %v is not in accepted list", tx.Hash()) return nil, internalRPCError(errStr, "") } // Generate and relay inventory vectors for all newly accepted // transactions into the memory pool due to the original being // accepted. s.cfg.ConnMgr.RelayTransactions(acceptedTxs) // Notify both websocket and getblocktemplate long poll clients of all // newly accepted transactions. s.NotifyNewTransactions(acceptedTxs) // Keep track of all the sendrawtransaction request txns so that they // can be rebroadcast if they don't make their way into a block. txD := acceptedTxs[0] iv := wire.NewInvVect(wire.InvTypeTx, txD.Tx.Hash()) s.cfg.ConnMgr.AddRebroadcastInventory(iv, txD) return tx.Hash().String(), nil }
[ "func", "handleSendRawTransaction", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "c", ":=", "cmd", ".", "(", "*", "btcjson"...
// handleSendRawTransaction implements the sendrawtransaction command.
[ "handleSendRawTransaction", "implements", "the", "sendrawtransaction", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L3300-L3374
162,987
btcsuite/btcd
rpcserver.go
handleSetGenerate
func handleSetGenerate(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.SetGenerateCmd) // Disable generation regardless of the provided generate flag if the // maximum number of threads (goroutines for our purposes) is 0. // Otherwise enable or disable it depending on the provided flag. generate := c.Generate genProcLimit := -1 if c.GenProcLimit != nil { genProcLimit = *c.GenProcLimit } if genProcLimit == 0 { generate = false } if !generate { s.cfg.CPUMiner.Stop() } else { // Respond with an error if there are no addresses to pay the // created blocks to. if len(cfg.miningAddrs) == 0 { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInternal.Code, Message: "No payment addresses specified " + "via --miningaddr", } } // It's safe to call start even if it's already started. s.cfg.CPUMiner.SetNumWorkers(int32(genProcLimit)) s.cfg.CPUMiner.Start() } return nil, nil }
go
func handleSetGenerate(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.SetGenerateCmd) // Disable generation regardless of the provided generate flag if the // maximum number of threads (goroutines for our purposes) is 0. // Otherwise enable or disable it depending on the provided flag. generate := c.Generate genProcLimit := -1 if c.GenProcLimit != nil { genProcLimit = *c.GenProcLimit } if genProcLimit == 0 { generate = false } if !generate { s.cfg.CPUMiner.Stop() } else { // Respond with an error if there are no addresses to pay the // created blocks to. if len(cfg.miningAddrs) == 0 { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInternal.Code, Message: "No payment addresses specified " + "via --miningaddr", } } // It's safe to call start even if it's already started. s.cfg.CPUMiner.SetNumWorkers(int32(genProcLimit)) s.cfg.CPUMiner.Start() } return nil, nil }
[ "func", "handleSetGenerate", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "c", ":=", "cmd", ".", "(", "*", "btcjson", "."...
// handleSetGenerate implements the setgenerate command.
[ "handleSetGenerate", "implements", "the", "setgenerate", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L3377-L3410
162,988
btcsuite/btcd
rpcserver.go
handleSubmitBlock
func handleSubmitBlock(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.SubmitBlockCmd) // Deserialize the submitted block. hexStr := c.HexBlock if len(hexStr)%2 != 0 { hexStr = "0" + c.HexBlock } serializedBlock, err := hex.DecodeString(hexStr) if err != nil { return nil, rpcDecodeHexError(hexStr) } block, err := btcutil.NewBlockFromBytes(serializedBlock) if err != nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCDeserialization, Message: "Block decode failed: " + err.Error(), } } // Process this block using the same rules as blocks coming from other // nodes. This will in turn relay it to the network like normal. _, err = s.cfg.SyncMgr.SubmitBlock(block, blockchain.BFNone) if err != nil { return fmt.Sprintf("rejected: %s", err.Error()), nil } rpcsLog.Infof("Accepted block %s via submitblock", block.Hash()) return nil, nil }
go
func handleSubmitBlock(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.SubmitBlockCmd) // Deserialize the submitted block. hexStr := c.HexBlock if len(hexStr)%2 != 0 { hexStr = "0" + c.HexBlock } serializedBlock, err := hex.DecodeString(hexStr) if err != nil { return nil, rpcDecodeHexError(hexStr) } block, err := btcutil.NewBlockFromBytes(serializedBlock) if err != nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCDeserialization, Message: "Block decode failed: " + err.Error(), } } // Process this block using the same rules as blocks coming from other // nodes. This will in turn relay it to the network like normal. _, err = s.cfg.SyncMgr.SubmitBlock(block, blockchain.BFNone) if err != nil { return fmt.Sprintf("rejected: %s", err.Error()), nil } rpcsLog.Infof("Accepted block %s via submitblock", block.Hash()) return nil, nil }
[ "func", "handleSubmitBlock", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "c", ":=", "cmd", ".", "(", "*", "btcjson", "."...
// handleSubmitBlock implements the submitblock command.
[ "handleSubmitBlock", "implements", "the", "submitblock", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L3422-L3452
162,989
btcsuite/btcd
rpcserver.go
handleUptime
func handleUptime(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { return time.Now().Unix() - s.cfg.StartupTime, nil }
go
func handleUptime(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { return time.Now().Unix() - s.cfg.StartupTime, nil }
[ "func", "handleUptime", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "time", ".", "Now", "(", ")", ".", "Unix",...
// handleUptime implements the uptime command.
[ "handleUptime", "implements", "the", "uptime", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L3455-L3457
162,990
btcsuite/btcd
rpcserver.go
handleValidateAddress
func handleValidateAddress(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.ValidateAddressCmd) result := btcjson.ValidateAddressChainResult{} addr, err := btcutil.DecodeAddress(c.Address, s.cfg.ChainParams) if err != nil { // Return the default value (false) for IsValid. return result, nil } result.Address = addr.EncodeAddress() result.IsValid = true return result, nil }
go
func handleValidateAddress(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.ValidateAddressCmd) result := btcjson.ValidateAddressChainResult{} addr, err := btcutil.DecodeAddress(c.Address, s.cfg.ChainParams) if err != nil { // Return the default value (false) for IsValid. return result, nil } result.Address = addr.EncodeAddress() result.IsValid = true return result, nil }
[ "func", "handleValidateAddress", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "c", ":=", "cmd", ".", "(", "*", "btcjson", ...
// handleValidateAddress implements the validateaddress command.
[ "handleValidateAddress", "implements", "the", "validateaddress", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L3460-L3474
162,991
btcsuite/btcd
rpcserver.go
handleVerifyChain
func handleVerifyChain(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.VerifyChainCmd) var checkLevel, checkDepth int32 if c.CheckLevel != nil { checkLevel = *c.CheckLevel } if c.CheckDepth != nil { checkDepth = *c.CheckDepth } err := verifyChain(s, checkLevel, checkDepth) return err == nil, nil }
go
func handleVerifyChain(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.VerifyChainCmd) var checkLevel, checkDepth int32 if c.CheckLevel != nil { checkLevel = *c.CheckLevel } if c.CheckDepth != nil { checkDepth = *c.CheckDepth } err := verifyChain(s, checkLevel, checkDepth) return err == nil, nil }
[ "func", "handleVerifyChain", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "c", ":=", "cmd", ".", "(", "*", "btcjson", "."...
// handleVerifyChain implements the verifychain command.
[ "handleVerifyChain", "implements", "the", "verifychain", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L3512-L3525
162,992
btcsuite/btcd
rpcserver.go
handleVerifyMessage
func handleVerifyMessage(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.VerifyMessageCmd) // Decode the provided address. params := s.cfg.ChainParams addr, err := btcutil.DecodeAddress(c.Address, params) if err != nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInvalidAddressOrKey, Message: "Invalid address or key: " + err.Error(), } } // Only P2PKH addresses are valid for signing. if _, ok := addr.(*btcutil.AddressPubKeyHash); !ok { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCType, Message: "Address is not a pay-to-pubkey-hash address", } } // Decode base64 signature. sig, err := base64.StdEncoding.DecodeString(c.Signature) if err != nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCParse.Code, Message: "Malformed base64 encoding: " + err.Error(), } } // Validate the signature - this just shows that it was valid at all. // we will compare it with the key next. var buf bytes.Buffer wire.WriteVarString(&buf, 0, "Bitcoin Signed Message:\n") wire.WriteVarString(&buf, 0, c.Message) expectedMessageHash := chainhash.DoubleHashB(buf.Bytes()) pk, wasCompressed, err := btcec.RecoverCompact(btcec.S256(), sig, expectedMessageHash) if err != nil { // Mirror Bitcoin Core behavior, which treats error in // RecoverCompact as invalid signature. return false, nil } // Reconstruct the pubkey hash. var serializedPK []byte if wasCompressed { serializedPK = pk.SerializeCompressed() } else { serializedPK = pk.SerializeUncompressed() } address, err := btcutil.NewAddressPubKey(serializedPK, params) if err != nil { // Again mirror Bitcoin Core behavior, which treats error in public key // reconstruction as invalid signature. return false, nil } // Return boolean if addresses match. return address.EncodeAddress() == c.Address, nil }
go
func handleVerifyMessage(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.VerifyMessageCmd) // Decode the provided address. params := s.cfg.ChainParams addr, err := btcutil.DecodeAddress(c.Address, params) if err != nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCInvalidAddressOrKey, Message: "Invalid address or key: " + err.Error(), } } // Only P2PKH addresses are valid for signing. if _, ok := addr.(*btcutil.AddressPubKeyHash); !ok { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCType, Message: "Address is not a pay-to-pubkey-hash address", } } // Decode base64 signature. sig, err := base64.StdEncoding.DecodeString(c.Signature) if err != nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCParse.Code, Message: "Malformed base64 encoding: " + err.Error(), } } // Validate the signature - this just shows that it was valid at all. // we will compare it with the key next. var buf bytes.Buffer wire.WriteVarString(&buf, 0, "Bitcoin Signed Message:\n") wire.WriteVarString(&buf, 0, c.Message) expectedMessageHash := chainhash.DoubleHashB(buf.Bytes()) pk, wasCompressed, err := btcec.RecoverCompact(btcec.S256(), sig, expectedMessageHash) if err != nil { // Mirror Bitcoin Core behavior, which treats error in // RecoverCompact as invalid signature. return false, nil } // Reconstruct the pubkey hash. var serializedPK []byte if wasCompressed { serializedPK = pk.SerializeCompressed() } else { serializedPK = pk.SerializeUncompressed() } address, err := btcutil.NewAddressPubKey(serializedPK, params) if err != nil { // Again mirror Bitcoin Core behavior, which treats error in public key // reconstruction as invalid signature. return false, nil } // Return boolean if addresses match. return address.EncodeAddress() == c.Address, nil }
[ "func", "handleVerifyMessage", "(", "s", "*", "rpcServer", ",", "cmd", "interface", "{", "}", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "c", ":=", "cmd", ".", "(", "*", "btcjson", "...
// handleVerifyMessage implements the verifymessage command.
[ "handleVerifyMessage", "implements", "the", "verifymessage", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L3528-L3588
162,993
btcsuite/btcd
rpcserver.go
writeHTTPResponseHeaders
func (s *rpcServer) writeHTTPResponseHeaders(req *http.Request, headers http.Header, code int, w io.Writer) error { _, err := io.WriteString(w, s.httpStatusLine(req, code)) if err != nil { return err } err = headers.Write(w) if err != nil { return err } _, err = io.WriteString(w, "\r\n") return err }
go
func (s *rpcServer) writeHTTPResponseHeaders(req *http.Request, headers http.Header, code int, w io.Writer) error { _, err := io.WriteString(w, s.httpStatusLine(req, code)) if err != nil { return err } err = headers.Write(w) if err != nil { return err } _, err = io.WriteString(w, "\r\n") return err }
[ "func", "(", "s", "*", "rpcServer", ")", "writeHTTPResponseHeaders", "(", "req", "*", "http", ".", "Request", ",", "headers", "http", ".", "Header", ",", "code", "int", ",", "w", "io", ".", "Writer", ")", "error", "{", "_", ",", "err", ":=", "io", ...
// writeHTTPResponseHeaders writes the necessary response headers prior to // writing an HTTP body given a request to use for protocol negotiation, headers // to write, a status code, and a writer.
[ "writeHTTPResponseHeaders", "writes", "the", "necessary", "response", "headers", "prior", "to", "writing", "an", "HTTP", "body", "given", "a", "request", "to", "use", "for", "protocol", "negotiation", "headers", "to", "write", "a", "status", "code", "and", "a", ...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L3663-L3676
162,994
btcsuite/btcd
rpcserver.go
Stop
func (s *rpcServer) Stop() error { if atomic.AddInt32(&s.shutdown, 1) != 1 { rpcsLog.Infof("RPC server is already in the process of shutting down") return nil } rpcsLog.Warnf("RPC server shutting down") for _, listener := range s.cfg.Listeners { err := listener.Close() if err != nil { rpcsLog.Errorf("Problem shutting down rpc: %v", err) return err } } s.ntfnMgr.Shutdown() s.ntfnMgr.WaitForShutdown() close(s.quit) s.wg.Wait() rpcsLog.Infof("RPC server shutdown complete") return nil }
go
func (s *rpcServer) Stop() error { if atomic.AddInt32(&s.shutdown, 1) != 1 { rpcsLog.Infof("RPC server is already in the process of shutting down") return nil } rpcsLog.Warnf("RPC server shutting down") for _, listener := range s.cfg.Listeners { err := listener.Close() if err != nil { rpcsLog.Errorf("Problem shutting down rpc: %v", err) return err } } s.ntfnMgr.Shutdown() s.ntfnMgr.WaitForShutdown() close(s.quit) s.wg.Wait() rpcsLog.Infof("RPC server shutdown complete") return nil }
[ "func", "(", "s", "*", "rpcServer", ")", "Stop", "(", ")", "error", "{", "if", "atomic", ".", "AddInt32", "(", "&", "s", ".", "shutdown", ",", "1", ")", "!=", "1", "{", "rpcsLog", ".", "Infof", "(", "\"", "\"", ")", "\n", "return", "nil", "\n",...
// Stop is used by server.go to stop the rpc listener.
[ "Stop", "is", "used", "by", "server", ".", "go", "to", "stop", "the", "rpc", "listener", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L3679-L3698
162,995
btcsuite/btcd
rpcserver.go
NotifyNewTransactions
func (s *rpcServer) NotifyNewTransactions(txns []*mempool.TxDesc) { for _, txD := range txns { // Notify websocket clients about mempool transactions. s.ntfnMgr.NotifyMempoolTx(txD.Tx, true) // Potentially notify any getblocktemplate long poll clients // about stale block templates due to the new transaction. s.gbtWorkState.NotifyMempoolTx(s.cfg.TxMemPool.LastUpdated()) } }
go
func (s *rpcServer) NotifyNewTransactions(txns []*mempool.TxDesc) { for _, txD := range txns { // Notify websocket clients about mempool transactions. s.ntfnMgr.NotifyMempoolTx(txD.Tx, true) // Potentially notify any getblocktemplate long poll clients // about stale block templates due to the new transaction. s.gbtWorkState.NotifyMempoolTx(s.cfg.TxMemPool.LastUpdated()) } }
[ "func", "(", "s", "*", "rpcServer", ")", "NotifyNewTransactions", "(", "txns", "[", "]", "*", "mempool", ".", "TxDesc", ")", "{", "for", "_", ",", "txD", ":=", "range", "txns", "{", "// Notify websocket clients about mempool transactions.", "s", ".", "ntfnMgr"...
// NotifyNewTransactions notifies both websocket and getblocktemplate long // poll clients of the passed transactions. This function should be called // whenever new transactions are added to the mempool.
[ "NotifyNewTransactions", "notifies", "both", "websocket", "and", "getblocktemplate", "long", "poll", "clients", "of", "the", "passed", "transactions", ".", "This", "function", "should", "be", "called", "whenever", "new", "transactions", "are", "added", "to", "the", ...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L3710-L3719
162,996
btcsuite/btcd
rpcserver.go
limitConnections
func (s *rpcServer) limitConnections(w http.ResponseWriter, remoteAddr string) bool { if int(atomic.LoadInt32(&s.numClients)+1) > cfg.RPCMaxClients { rpcsLog.Infof("Max RPC clients exceeded [%d] - "+ "disconnecting client %s", cfg.RPCMaxClients, remoteAddr) http.Error(w, "503 Too busy. Try again later.", http.StatusServiceUnavailable) return true } return false }
go
func (s *rpcServer) limitConnections(w http.ResponseWriter, remoteAddr string) bool { if int(atomic.LoadInt32(&s.numClients)+1) > cfg.RPCMaxClients { rpcsLog.Infof("Max RPC clients exceeded [%d] - "+ "disconnecting client %s", cfg.RPCMaxClients, remoteAddr) http.Error(w, "503 Too busy. Try again later.", http.StatusServiceUnavailable) return true } return false }
[ "func", "(", "s", "*", "rpcServer", ")", "limitConnections", "(", "w", "http", ".", "ResponseWriter", ",", "remoteAddr", "string", ")", "bool", "{", "if", "int", "(", "atomic", ".", "LoadInt32", "(", "&", "s", ".", "numClients", ")", "+", "1", ")", "...
// limitConnections responds with a 503 service unavailable and returns true if // adding another client would exceed the maximum allow RPC clients. // // This function is safe for concurrent access.
[ "limitConnections", "responds", "with", "a", "503", "service", "unavailable", "and", "returns", "true", "if", "adding", "another", "client", "would", "exceed", "the", "maximum", "allow", "RPC", "clients", ".", "This", "function", "is", "safe", "for", "concurrent...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L3725-L3735
162,997
btcsuite/btcd
rpcserver.go
standardCmdResult
func (s *rpcServer) standardCmdResult(cmd *parsedRPCCmd, closeChan <-chan struct{}) (interface{}, error) { handler, ok := rpcHandlers[cmd.method] if ok { goto handled } _, ok = rpcAskWallet[cmd.method] if ok { handler = handleAskWallet goto handled } _, ok = rpcUnimplemented[cmd.method] if ok { handler = handleUnimplemented goto handled } return nil, btcjson.ErrRPCMethodNotFound handled: return handler(s, cmd.cmd, closeChan) }
go
func (s *rpcServer) standardCmdResult(cmd *parsedRPCCmd, closeChan <-chan struct{}) (interface{}, error) { handler, ok := rpcHandlers[cmd.method] if ok { goto handled } _, ok = rpcAskWallet[cmd.method] if ok { handler = handleAskWallet goto handled } _, ok = rpcUnimplemented[cmd.method] if ok { handler = handleUnimplemented goto handled } return nil, btcjson.ErrRPCMethodNotFound handled: return handler(s, cmd.cmd, closeChan) }
[ "func", "(", "s", "*", "rpcServer", ")", "standardCmdResult", "(", "cmd", "*", "parsedRPCCmd", ",", "closeChan", "<-", "chan", "struct", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "handler", ",", "ok", ":=", "rpcHandlers", "[", ...
// standardCmdResult checks that a parsed command is a standard Bitcoin JSON-RPC // command and runs the appropriate handler to reply to the command. Any // commands which are not recognized or not implemented will return an error // suitable for use in replies.
[ "standardCmdResult", "checks", "that", "a", "parsed", "command", "is", "a", "standard", "Bitcoin", "JSON", "-", "RPC", "command", "and", "runs", "the", "appropriate", "handler", "to", "reply", "to", "the", "command", ".", "Any", "commands", "which", "are", "...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L3812-L3831
162,998
btcsuite/btcd
rpcserver.go
parseCmd
func parseCmd(request *btcjson.Request) *parsedRPCCmd { var parsedCmd parsedRPCCmd parsedCmd.id = request.ID parsedCmd.method = request.Method cmd, err := btcjson.UnmarshalCmd(request) if err != nil { // When the error is because the method is not registered, // produce a method not found RPC error. if jerr, ok := err.(btcjson.Error); ok && jerr.ErrorCode == btcjson.ErrUnregisteredMethod { parsedCmd.err = btcjson.ErrRPCMethodNotFound return &parsedCmd } // Otherwise, some type of invalid parameters is the // cause, so produce the equivalent RPC error. parsedCmd.err = btcjson.NewRPCError( btcjson.ErrRPCInvalidParams.Code, err.Error()) return &parsedCmd } parsedCmd.cmd = cmd return &parsedCmd }
go
func parseCmd(request *btcjson.Request) *parsedRPCCmd { var parsedCmd parsedRPCCmd parsedCmd.id = request.ID parsedCmd.method = request.Method cmd, err := btcjson.UnmarshalCmd(request) if err != nil { // When the error is because the method is not registered, // produce a method not found RPC error. if jerr, ok := err.(btcjson.Error); ok && jerr.ErrorCode == btcjson.ErrUnregisteredMethod { parsedCmd.err = btcjson.ErrRPCMethodNotFound return &parsedCmd } // Otherwise, some type of invalid parameters is the // cause, so produce the equivalent RPC error. parsedCmd.err = btcjson.NewRPCError( btcjson.ErrRPCInvalidParams.Code, err.Error()) return &parsedCmd } parsedCmd.cmd = cmd return &parsedCmd }
[ "func", "parseCmd", "(", "request", "*", "btcjson", ".", "Request", ")", "*", "parsedRPCCmd", "{", "var", "parsedCmd", "parsedRPCCmd", "\n", "parsedCmd", ".", "id", "=", "request", ".", "ID", "\n", "parsedCmd", ".", "method", "=", "request", ".", "Method",...
// parseCmd parses a JSON-RPC request object into known concrete command. The // err field of the returned parsedRPCCmd struct will contain an RPC error that // is suitable for use in replies if the command is invalid in some way such as // an unregistered command or invalid parameters.
[ "parseCmd", "parses", "a", "JSON", "-", "RPC", "request", "object", "into", "known", "concrete", "command", ".", "The", "err", "field", "of", "the", "returned", "parsedRPCCmd", "struct", "will", "contain", "an", "RPC", "error", "that", "is", "suitable", "for...
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L3837-L3862
162,999
btcsuite/btcd
rpcserver.go
Start
func (s *rpcServer) Start() { if atomic.AddInt32(&s.started, 1) != 1 { return } rpcsLog.Trace("Starting RPC server") rpcServeMux := http.NewServeMux() httpServer := &http.Server{ Handler: rpcServeMux, // Timeout connections which don't complete the initial // handshake within the allowed timeframe. ReadTimeout: time.Second * rpcAuthTimeoutSeconds, } rpcServeMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Connection", "close") w.Header().Set("Content-Type", "application/json") r.Close = true // Limit the number of connections to max allowed. if s.limitConnections(w, r.RemoteAddr) { return } // Keep track of the number of connected clients. s.incrementClients() defer s.decrementClients() _, isAdmin, err := s.checkAuth(r, true) if err != nil { jsonAuthFail(w) return } // Read and respond to the request. s.jsonRPCRead(w, r, isAdmin) }) // Websocket endpoint. rpcServeMux.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { authenticated, isAdmin, err := s.checkAuth(r, false) if err != nil { jsonAuthFail(w) return } // Attempt to upgrade the connection to a websocket connection // using the default size for read/write buffers. ws, err := websocket.Upgrade(w, r, nil, 0, 0) if err != nil { if _, ok := err.(websocket.HandshakeError); !ok { rpcsLog.Errorf("Unexpected websocket error: %v", err) } http.Error(w, "400 Bad Request.", http.StatusBadRequest) return } s.WebsocketHandler(ws, r.RemoteAddr, authenticated, isAdmin) }) for _, listener := range s.cfg.Listeners { s.wg.Add(1) go func(listener net.Listener) { rpcsLog.Infof("RPC server listening on %s", listener.Addr()) httpServer.Serve(listener) rpcsLog.Tracef("RPC listener done for %s", listener.Addr()) s.wg.Done() }(listener) } s.ntfnMgr.Start() }
go
func (s *rpcServer) Start() { if atomic.AddInt32(&s.started, 1) != 1 { return } rpcsLog.Trace("Starting RPC server") rpcServeMux := http.NewServeMux() httpServer := &http.Server{ Handler: rpcServeMux, // Timeout connections which don't complete the initial // handshake within the allowed timeframe. ReadTimeout: time.Second * rpcAuthTimeoutSeconds, } rpcServeMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Connection", "close") w.Header().Set("Content-Type", "application/json") r.Close = true // Limit the number of connections to max allowed. if s.limitConnections(w, r.RemoteAddr) { return } // Keep track of the number of connected clients. s.incrementClients() defer s.decrementClients() _, isAdmin, err := s.checkAuth(r, true) if err != nil { jsonAuthFail(w) return } // Read and respond to the request. s.jsonRPCRead(w, r, isAdmin) }) // Websocket endpoint. rpcServeMux.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { authenticated, isAdmin, err := s.checkAuth(r, false) if err != nil { jsonAuthFail(w) return } // Attempt to upgrade the connection to a websocket connection // using the default size for read/write buffers. ws, err := websocket.Upgrade(w, r, nil, 0, 0) if err != nil { if _, ok := err.(websocket.HandshakeError); !ok { rpcsLog.Errorf("Unexpected websocket error: %v", err) } http.Error(w, "400 Bad Request.", http.StatusBadRequest) return } s.WebsocketHandler(ws, r.RemoteAddr, authenticated, isAdmin) }) for _, listener := range s.cfg.Listeners { s.wg.Add(1) go func(listener net.Listener) { rpcsLog.Infof("RPC server listening on %s", listener.Addr()) httpServer.Serve(listener) rpcsLog.Tracef("RPC listener done for %s", listener.Addr()) s.wg.Done() }(listener) } s.ntfnMgr.Start() }
[ "func", "(", "s", "*", "rpcServer", ")", "Start", "(", ")", "{", "if", "atomic", ".", "AddInt32", "(", "&", "s", ".", "started", ",", "1", ")", "!=", "1", "{", "return", "\n", "}", "\n\n", "rpcsLog", ".", "Trace", "(", "\"", "\"", ")", "\n", ...
// Start is used by server.go to start the rpc listener.
[ "Start", "is", "used", "by", "server", ".", "go", "to", "start", "the", "rpc", "listener", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserver.go#L4021-L4091