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 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
btcsuite/btcwallet | waddrmgr/db.go | fetchBirthdayBlockVerification | func fetchBirthdayBlockVerification(ns walletdb.ReadBucket) bool {
bucket := ns.NestedReadBucket(syncBucketName)
verifiedValue := bucket.Get(birthdayBlockVerifiedName)
// If there is no verification status, we can assume it has not been
// verified yet.
if verifiedValue == nil {
return false
}
// Otherwise, we'll determine if it's verified by the value stored.
verified := binary.BigEndian.Uint16(verifiedValue[:])
return verified != 0
} | go | func fetchBirthdayBlockVerification(ns walletdb.ReadBucket) bool {
bucket := ns.NestedReadBucket(syncBucketName)
verifiedValue := bucket.Get(birthdayBlockVerifiedName)
// If there is no verification status, we can assume it has not been
// verified yet.
if verifiedValue == nil {
return false
}
// Otherwise, we'll determine if it's verified by the value stored.
verified := binary.BigEndian.Uint16(verifiedValue[:])
return verified != 0
} | [
"func",
"fetchBirthdayBlockVerification",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
")",
"bool",
"{",
"bucket",
":=",
"ns",
".",
"NestedReadBucket",
"(",
"syncBucketName",
")",
"\n",
"verifiedValue",
":=",
"bucket",
".",
"Get",
"(",
"birthdayBlockVerifiedName",
")",
"\n\n",
"// If there is no verification status, we can assume it has not been",
"// verified yet.",
"if",
"verifiedValue",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"// Otherwise, we'll determine if it's verified by the value stored.",
"verified",
":=",
"binary",
".",
"BigEndian",
".",
"Uint16",
"(",
"verifiedValue",
"[",
":",
"]",
")",
"\n",
"return",
"verified",
"!=",
"0",
"\n",
"}"
] | // fetchBirthdayBlockVerification retrieves the bit that determines whether the
// wallet has verified that its birthday block is correct. | [
"fetchBirthdayBlockVerification",
"retrieves",
"the",
"bit",
"that",
"determines",
"whether",
"the",
"wallet",
"has",
"verified",
"that",
"its",
"birthday",
"block",
"is",
"correct",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L2018-L2031 | train |
btcsuite/btcwallet | waddrmgr/db.go | putBirthdayBlockVerification | func putBirthdayBlockVerification(ns walletdb.ReadWriteBucket, verified bool) error {
// Convert the boolean to an integer in its binary representation as
// there is no way to insert a boolean directly as a value of a
// key/value pair.
verifiedValue := uint16(0)
if verified {
verifiedValue = 1
}
var verifiedBytes [2]byte
binary.BigEndian.PutUint16(verifiedBytes[:], verifiedValue)
bucket := ns.NestedReadWriteBucket(syncBucketName)
err := bucket.Put(birthdayBlockVerifiedName, verifiedBytes[:])
if err != nil {
str := "failed to store birthday block verification"
return managerError(ErrDatabase, str, err)
}
return nil
} | go | func putBirthdayBlockVerification(ns walletdb.ReadWriteBucket, verified bool) error {
// Convert the boolean to an integer in its binary representation as
// there is no way to insert a boolean directly as a value of a
// key/value pair.
verifiedValue := uint16(0)
if verified {
verifiedValue = 1
}
var verifiedBytes [2]byte
binary.BigEndian.PutUint16(verifiedBytes[:], verifiedValue)
bucket := ns.NestedReadWriteBucket(syncBucketName)
err := bucket.Put(birthdayBlockVerifiedName, verifiedBytes[:])
if err != nil {
str := "failed to store birthday block verification"
return managerError(ErrDatabase, str, err)
}
return nil
} | [
"func",
"putBirthdayBlockVerification",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"verified",
"bool",
")",
"error",
"{",
"// Convert the boolean to an integer in its binary representation as",
"// there is no way to insert a boolean directly as a value of a",
"// key/value pair.",
"verifiedValue",
":=",
"uint16",
"(",
"0",
")",
"\n",
"if",
"verified",
"{",
"verifiedValue",
"=",
"1",
"\n",
"}",
"\n\n",
"var",
"verifiedBytes",
"[",
"2",
"]",
"byte",
"\n",
"binary",
".",
"BigEndian",
".",
"PutUint16",
"(",
"verifiedBytes",
"[",
":",
"]",
",",
"verifiedValue",
")",
"\n\n",
"bucket",
":=",
"ns",
".",
"NestedReadWriteBucket",
"(",
"syncBucketName",
")",
"\n",
"err",
":=",
"bucket",
".",
"Put",
"(",
"birthdayBlockVerifiedName",
",",
"verifiedBytes",
"[",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"str",
":=",
"\"",
"\"",
"\n",
"return",
"managerError",
"(",
"ErrDatabase",
",",
"str",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // putBirthdayBlockVerification stores a bit that determines whether the
// birthday block has been verified by the wallet to be correct. | [
"putBirthdayBlockVerification",
"stores",
"a",
"bit",
"that",
"determines",
"whether",
"the",
"birthday",
"block",
"has",
"been",
"verified",
"by",
"the",
"wallet",
"to",
"be",
"correct",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L2035-L2055 | train |
btcsuite/btcwallet | waddrmgr/db.go | managerExists | func managerExists(ns walletdb.ReadBucket) bool {
if ns == nil {
return false
}
mainBucket := ns.NestedReadBucket(mainBucketName)
return mainBucket != nil
} | go | func managerExists(ns walletdb.ReadBucket) bool {
if ns == nil {
return false
}
mainBucket := ns.NestedReadBucket(mainBucketName)
return mainBucket != nil
} | [
"func",
"managerExists",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
")",
"bool",
"{",
"if",
"ns",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"mainBucket",
":=",
"ns",
".",
"NestedReadBucket",
"(",
"mainBucketName",
")",
"\n",
"return",
"mainBucket",
"!=",
"nil",
"\n",
"}"
] | // managerExists returns whether or not the manager has already been created
// in the given database namespace. | [
"managerExists",
"returns",
"whether",
"or",
"not",
"the",
"manager",
"has",
"already",
"been",
"created",
"in",
"the",
"given",
"database",
"namespace",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L2059-L2065 | train |
btcsuite/btcwallet | waddrmgr/db.go | createScopedManagerNS | func createScopedManagerNS(ns walletdb.ReadWriteBucket, scope *KeyScope) error {
// First, we'll create the scope bucket itself for this particular
// scope.
scopeKey := scopeToBytes(scope)
scopeBucket, err := ns.CreateBucket(scopeKey[:])
if err != nil {
str := "failed to create sync bucket"
return managerError(ErrDatabase, str, err)
}
_, err = scopeBucket.CreateBucket(acctBucketName)
if err != nil {
str := "failed to create account bucket"
return managerError(ErrDatabase, str, err)
}
_, err = scopeBucket.CreateBucket(addrBucketName)
if err != nil {
str := "failed to create address bucket"
return managerError(ErrDatabase, str, err)
}
// usedAddrBucketName bucket was added after manager version 1 release
_, err = scopeBucket.CreateBucket(usedAddrBucketName)
if err != nil {
str := "failed to create used addresses bucket"
return managerError(ErrDatabase, str, err)
}
_, err = scopeBucket.CreateBucket(addrAcctIdxBucketName)
if err != nil {
str := "failed to create address index bucket"
return managerError(ErrDatabase, str, err)
}
_, err = scopeBucket.CreateBucket(acctNameIdxBucketName)
if err != nil {
str := "failed to create an account name index bucket"
return managerError(ErrDatabase, str, err)
}
_, err = scopeBucket.CreateBucket(acctIDIdxBucketName)
if err != nil {
str := "failed to create an account id index bucket"
return managerError(ErrDatabase, str, err)
}
_, err = scopeBucket.CreateBucket(metaBucketName)
if err != nil {
str := "failed to create a meta bucket"
return managerError(ErrDatabase, str, err)
}
return nil
} | go | func createScopedManagerNS(ns walletdb.ReadWriteBucket, scope *KeyScope) error {
// First, we'll create the scope bucket itself for this particular
// scope.
scopeKey := scopeToBytes(scope)
scopeBucket, err := ns.CreateBucket(scopeKey[:])
if err != nil {
str := "failed to create sync bucket"
return managerError(ErrDatabase, str, err)
}
_, err = scopeBucket.CreateBucket(acctBucketName)
if err != nil {
str := "failed to create account bucket"
return managerError(ErrDatabase, str, err)
}
_, err = scopeBucket.CreateBucket(addrBucketName)
if err != nil {
str := "failed to create address bucket"
return managerError(ErrDatabase, str, err)
}
// usedAddrBucketName bucket was added after manager version 1 release
_, err = scopeBucket.CreateBucket(usedAddrBucketName)
if err != nil {
str := "failed to create used addresses bucket"
return managerError(ErrDatabase, str, err)
}
_, err = scopeBucket.CreateBucket(addrAcctIdxBucketName)
if err != nil {
str := "failed to create address index bucket"
return managerError(ErrDatabase, str, err)
}
_, err = scopeBucket.CreateBucket(acctNameIdxBucketName)
if err != nil {
str := "failed to create an account name index bucket"
return managerError(ErrDatabase, str, err)
}
_, err = scopeBucket.CreateBucket(acctIDIdxBucketName)
if err != nil {
str := "failed to create an account id index bucket"
return managerError(ErrDatabase, str, err)
}
_, err = scopeBucket.CreateBucket(metaBucketName)
if err != nil {
str := "failed to create a meta bucket"
return managerError(ErrDatabase, str, err)
}
return nil
} | [
"func",
"createScopedManagerNS",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"scope",
"*",
"KeyScope",
")",
"error",
"{",
"// First, we'll create the scope bucket itself for this particular",
"// scope.",
"scopeKey",
":=",
"scopeToBytes",
"(",
"scope",
")",
"\n",
"scopeBucket",
",",
"err",
":=",
"ns",
".",
"CreateBucket",
"(",
"scopeKey",
"[",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"str",
":=",
"\"",
"\"",
"\n",
"return",
"managerError",
"(",
"ErrDatabase",
",",
"str",
",",
"err",
")",
"\n",
"}",
"\n\n",
"_",
",",
"err",
"=",
"scopeBucket",
".",
"CreateBucket",
"(",
"acctBucketName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"str",
":=",
"\"",
"\"",
"\n",
"return",
"managerError",
"(",
"ErrDatabase",
",",
"str",
",",
"err",
")",
"\n",
"}",
"\n\n",
"_",
",",
"err",
"=",
"scopeBucket",
".",
"CreateBucket",
"(",
"addrBucketName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"str",
":=",
"\"",
"\"",
"\n",
"return",
"managerError",
"(",
"ErrDatabase",
",",
"str",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// usedAddrBucketName bucket was added after manager version 1 release",
"_",
",",
"err",
"=",
"scopeBucket",
".",
"CreateBucket",
"(",
"usedAddrBucketName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"str",
":=",
"\"",
"\"",
"\n",
"return",
"managerError",
"(",
"ErrDatabase",
",",
"str",
",",
"err",
")",
"\n",
"}",
"\n\n",
"_",
",",
"err",
"=",
"scopeBucket",
".",
"CreateBucket",
"(",
"addrAcctIdxBucketName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"str",
":=",
"\"",
"\"",
"\n",
"return",
"managerError",
"(",
"ErrDatabase",
",",
"str",
",",
"err",
")",
"\n",
"}",
"\n\n",
"_",
",",
"err",
"=",
"scopeBucket",
".",
"CreateBucket",
"(",
"acctNameIdxBucketName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"str",
":=",
"\"",
"\"",
"\n",
"return",
"managerError",
"(",
"ErrDatabase",
",",
"str",
",",
"err",
")",
"\n",
"}",
"\n\n",
"_",
",",
"err",
"=",
"scopeBucket",
".",
"CreateBucket",
"(",
"acctIDIdxBucketName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"str",
":=",
"\"",
"\"",
"\n",
"return",
"managerError",
"(",
"ErrDatabase",
",",
"str",
",",
"err",
")",
"\n",
"}",
"\n\n",
"_",
",",
"err",
"=",
"scopeBucket",
".",
"CreateBucket",
"(",
"metaBucketName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"str",
":=",
"\"",
"\"",
"\n",
"return",
"managerError",
"(",
"ErrDatabase",
",",
"str",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // createScopedManagerNS creates the namespace buckets for a new registered
// manager scope within the top level bucket. All relevant sub-buckets that a
// ScopedManager needs to perform its duties are also created. | [
"createScopedManagerNS",
"creates",
"the",
"namespace",
"buckets",
"for",
"a",
"new",
"registered",
"manager",
"scope",
"within",
"the",
"top",
"level",
"bucket",
".",
"All",
"relevant",
"sub",
"-",
"buckets",
"that",
"a",
"ScopedManager",
"needs",
"to",
"perform",
"its",
"duties",
"are",
"also",
"created",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L2070-L2124 | train |
btcsuite/btcwallet | waddrmgr/db.go | createManagerNS | func createManagerNS(ns walletdb.ReadWriteBucket,
defaultScopes map[KeyScope]ScopeAddrSchema) error {
// First, we'll create all the relevant buckets that stem off of the
// main bucket.
mainBucket, err := ns.CreateBucket(mainBucketName)
if err != nil {
str := "failed to create main bucket"
return managerError(ErrDatabase, str, err)
}
_, err = ns.CreateBucket(syncBucketName)
if err != nil {
str := "failed to create sync bucket"
return managerError(ErrDatabase, str, err)
}
// We'll also create the two top-level scope related buckets as
// preparation for the operations below.
scopeBucket, err := ns.CreateBucket(scopeBucketName)
if err != nil {
str := "failed to create scope bucket"
return managerError(ErrDatabase, str, err)
}
scopeSchemas, err := ns.CreateBucket(scopeSchemaBucketName)
if err != nil {
str := "failed to create scope schema bucket"
return managerError(ErrDatabase, str, err)
}
// Next, we'll create the namespace for each of the relevant default
// manager scopes.
for scope, scopeSchema := range defaultScopes {
// Before we create the entire namespace of this scope, we'll
// update the schema mapping to note what types of addresses it
// prefers.
scopeKey := scopeToBytes(&scope)
schemaBytes := scopeSchemaToBytes(&scopeSchema)
err := scopeSchemas.Put(scopeKey[:], schemaBytes)
if err != nil {
return err
}
err = createScopedManagerNS(scopeBucket, &scope)
if err != nil {
return err
}
err = putLastAccount(ns, &scope, DefaultAccountNum)
if err != nil {
return err
}
}
if err := putManagerVersion(ns, latestMgrVersion); err != nil {
return err
}
createDate := uint64(time.Now().Unix())
var dateBytes [8]byte
binary.LittleEndian.PutUint64(dateBytes[:], createDate)
err = mainBucket.Put(mgrCreateDateName, dateBytes[:])
if err != nil {
str := "failed to store database creation time"
return managerError(ErrDatabase, str, err)
}
return nil
} | go | func createManagerNS(ns walletdb.ReadWriteBucket,
defaultScopes map[KeyScope]ScopeAddrSchema) error {
// First, we'll create all the relevant buckets that stem off of the
// main bucket.
mainBucket, err := ns.CreateBucket(mainBucketName)
if err != nil {
str := "failed to create main bucket"
return managerError(ErrDatabase, str, err)
}
_, err = ns.CreateBucket(syncBucketName)
if err != nil {
str := "failed to create sync bucket"
return managerError(ErrDatabase, str, err)
}
// We'll also create the two top-level scope related buckets as
// preparation for the operations below.
scopeBucket, err := ns.CreateBucket(scopeBucketName)
if err != nil {
str := "failed to create scope bucket"
return managerError(ErrDatabase, str, err)
}
scopeSchemas, err := ns.CreateBucket(scopeSchemaBucketName)
if err != nil {
str := "failed to create scope schema bucket"
return managerError(ErrDatabase, str, err)
}
// Next, we'll create the namespace for each of the relevant default
// manager scopes.
for scope, scopeSchema := range defaultScopes {
// Before we create the entire namespace of this scope, we'll
// update the schema mapping to note what types of addresses it
// prefers.
scopeKey := scopeToBytes(&scope)
schemaBytes := scopeSchemaToBytes(&scopeSchema)
err := scopeSchemas.Put(scopeKey[:], schemaBytes)
if err != nil {
return err
}
err = createScopedManagerNS(scopeBucket, &scope)
if err != nil {
return err
}
err = putLastAccount(ns, &scope, DefaultAccountNum)
if err != nil {
return err
}
}
if err := putManagerVersion(ns, latestMgrVersion); err != nil {
return err
}
createDate := uint64(time.Now().Unix())
var dateBytes [8]byte
binary.LittleEndian.PutUint64(dateBytes[:], createDate)
err = mainBucket.Put(mgrCreateDateName, dateBytes[:])
if err != nil {
str := "failed to store database creation time"
return managerError(ErrDatabase, str, err)
}
return nil
} | [
"func",
"createManagerNS",
"(",
"ns",
"walletdb",
".",
"ReadWriteBucket",
",",
"defaultScopes",
"map",
"[",
"KeyScope",
"]",
"ScopeAddrSchema",
")",
"error",
"{",
"// First, we'll create all the relevant buckets that stem off of the",
"// main bucket.",
"mainBucket",
",",
"err",
":=",
"ns",
".",
"CreateBucket",
"(",
"mainBucketName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"str",
":=",
"\"",
"\"",
"\n",
"return",
"managerError",
"(",
"ErrDatabase",
",",
"str",
",",
"err",
")",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"ns",
".",
"CreateBucket",
"(",
"syncBucketName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"str",
":=",
"\"",
"\"",
"\n",
"return",
"managerError",
"(",
"ErrDatabase",
",",
"str",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// We'll also create the two top-level scope related buckets as",
"// preparation for the operations below.",
"scopeBucket",
",",
"err",
":=",
"ns",
".",
"CreateBucket",
"(",
"scopeBucketName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"str",
":=",
"\"",
"\"",
"\n",
"return",
"managerError",
"(",
"ErrDatabase",
",",
"str",
",",
"err",
")",
"\n",
"}",
"\n",
"scopeSchemas",
",",
"err",
":=",
"ns",
".",
"CreateBucket",
"(",
"scopeSchemaBucketName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"str",
":=",
"\"",
"\"",
"\n",
"return",
"managerError",
"(",
"ErrDatabase",
",",
"str",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Next, we'll create the namespace for each of the relevant default",
"// manager scopes.",
"for",
"scope",
",",
"scopeSchema",
":=",
"range",
"defaultScopes",
"{",
"// Before we create the entire namespace of this scope, we'll",
"// update the schema mapping to note what types of addresses it",
"// prefers.",
"scopeKey",
":=",
"scopeToBytes",
"(",
"&",
"scope",
")",
"\n",
"schemaBytes",
":=",
"scopeSchemaToBytes",
"(",
"&",
"scopeSchema",
")",
"\n",
"err",
":=",
"scopeSchemas",
".",
"Put",
"(",
"scopeKey",
"[",
":",
"]",
",",
"schemaBytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"err",
"=",
"createScopedManagerNS",
"(",
"scopeBucket",
",",
"&",
"scope",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"err",
"=",
"putLastAccount",
"(",
"ns",
",",
"&",
"scope",
",",
"DefaultAccountNum",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"putManagerVersion",
"(",
"ns",
",",
"latestMgrVersion",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"createDate",
":=",
"uint64",
"(",
"time",
".",
"Now",
"(",
")",
".",
"Unix",
"(",
")",
")",
"\n",
"var",
"dateBytes",
"[",
"8",
"]",
"byte",
"\n",
"binary",
".",
"LittleEndian",
".",
"PutUint64",
"(",
"dateBytes",
"[",
":",
"]",
",",
"createDate",
")",
"\n",
"err",
"=",
"mainBucket",
".",
"Put",
"(",
"mgrCreateDateName",
",",
"dateBytes",
"[",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"str",
":=",
"\"",
"\"",
"\n",
"return",
"managerError",
"(",
"ErrDatabase",
",",
"str",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // createManagerNS creates the initial namespace structure needed for all of
// the manager data. This includes things such as all of the buckets as well
// as the version and creation date. In addition to creating the key space for
// the root address manager, we'll also create internal scopes for all the
// default manager scope types. | [
"createManagerNS",
"creates",
"the",
"initial",
"namespace",
"structure",
"needed",
"for",
"all",
"of",
"the",
"manager",
"data",
".",
"This",
"includes",
"things",
"such",
"as",
"all",
"of",
"the",
"buckets",
"as",
"well",
"as",
"the",
"version",
"and",
"creation",
"date",
".",
"In",
"addition",
"to",
"creating",
"the",
"key",
"space",
"for",
"the",
"root",
"address",
"manager",
"we",
"ll",
"also",
"create",
"internal",
"scopes",
"for",
"all",
"the",
"default",
"manager",
"scope",
"types",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L2131-L2198 | train |
btcsuite/btcwallet | rpcserver.go | openRPCKeyPair | func openRPCKeyPair() (tls.Certificate, error) {
// Check for existence of the TLS key file. If one time TLS keys are
// enabled but a key already exists, this function should error since
// it's possible that a persistent certificate was copied to a remote
// machine. Otherwise, generate a new keypair when the key is missing.
// When generating new persistent keys, overwriting an existing cert is
// acceptable if the previous execution used a one time TLS key.
// Otherwise, both the cert and key should be read from disk. If the
// cert is missing, the read error will occur in LoadX509KeyPair.
_, e := os.Stat(cfg.RPCKey.Value)
keyExists := !os.IsNotExist(e)
switch {
case cfg.OneTimeTLSKey && keyExists:
err := fmt.Errorf("one time TLS keys are enabled, but TLS key "+
"`%s` already exists", cfg.RPCKey.Value)
return tls.Certificate{}, err
case cfg.OneTimeTLSKey:
return generateRPCKeyPair(false)
case !keyExists:
return generateRPCKeyPair(true)
default:
return tls.LoadX509KeyPair(cfg.RPCCert.Value, cfg.RPCKey.Value)
}
} | go | func openRPCKeyPair() (tls.Certificate, error) {
// Check for existence of the TLS key file. If one time TLS keys are
// enabled but a key already exists, this function should error since
// it's possible that a persistent certificate was copied to a remote
// machine. Otherwise, generate a new keypair when the key is missing.
// When generating new persistent keys, overwriting an existing cert is
// acceptable if the previous execution used a one time TLS key.
// Otherwise, both the cert and key should be read from disk. If the
// cert is missing, the read error will occur in LoadX509KeyPair.
_, e := os.Stat(cfg.RPCKey.Value)
keyExists := !os.IsNotExist(e)
switch {
case cfg.OneTimeTLSKey && keyExists:
err := fmt.Errorf("one time TLS keys are enabled, but TLS key "+
"`%s` already exists", cfg.RPCKey.Value)
return tls.Certificate{}, err
case cfg.OneTimeTLSKey:
return generateRPCKeyPair(false)
case !keyExists:
return generateRPCKeyPair(true)
default:
return tls.LoadX509KeyPair(cfg.RPCCert.Value, cfg.RPCKey.Value)
}
} | [
"func",
"openRPCKeyPair",
"(",
")",
"(",
"tls",
".",
"Certificate",
",",
"error",
")",
"{",
"// Check for existence of the TLS key file. If one time TLS keys are",
"// enabled but a key already exists, this function should error since",
"// it's possible that a persistent certificate was copied to a remote",
"// machine. Otherwise, generate a new keypair when the key is missing.",
"// When generating new persistent keys, overwriting an existing cert is",
"// acceptable if the previous execution used a one time TLS key.",
"// Otherwise, both the cert and key should be read from disk. If the",
"// cert is missing, the read error will occur in LoadX509KeyPair.",
"_",
",",
"e",
":=",
"os",
".",
"Stat",
"(",
"cfg",
".",
"RPCKey",
".",
"Value",
")",
"\n",
"keyExists",
":=",
"!",
"os",
".",
"IsNotExist",
"(",
"e",
")",
"\n",
"switch",
"{",
"case",
"cfg",
".",
"OneTimeTLSKey",
"&&",
"keyExists",
":",
"err",
":=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"cfg",
".",
"RPCKey",
".",
"Value",
")",
"\n",
"return",
"tls",
".",
"Certificate",
"{",
"}",
",",
"err",
"\n",
"case",
"cfg",
".",
"OneTimeTLSKey",
":",
"return",
"generateRPCKeyPair",
"(",
"false",
")",
"\n",
"case",
"!",
"keyExists",
":",
"return",
"generateRPCKeyPair",
"(",
"true",
")",
"\n",
"default",
":",
"return",
"tls",
".",
"LoadX509KeyPair",
"(",
"cfg",
".",
"RPCCert",
".",
"Value",
",",
"cfg",
".",
"RPCKey",
".",
"Value",
")",
"\n",
"}",
"\n",
"}"
] | // openRPCKeyPair creates or loads the RPC TLS keypair specified by the
// application config. This function respects the cfg.OneTimeTLSKey setting. | [
"openRPCKeyPair",
"creates",
"or",
"loads",
"the",
"RPC",
"TLS",
"keypair",
"specified",
"by",
"the",
"application",
"config",
".",
"This",
"function",
"respects",
"the",
"cfg",
".",
"OneTimeTLSKey",
"setting",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpcserver.go#L29-L52 | train |
btcsuite/btcwallet | rpcserver.go | generateRPCKeyPair | func generateRPCKeyPair(writeKey bool) (tls.Certificate, error) {
log.Infof("Generating TLS certificates...")
// Create directories for cert and key files if they do not yet exist.
certDir, _ := filepath.Split(cfg.RPCCert.Value)
keyDir, _ := filepath.Split(cfg.RPCKey.Value)
err := os.MkdirAll(certDir, 0700)
if err != nil {
return tls.Certificate{}, err
}
err = os.MkdirAll(keyDir, 0700)
if err != nil {
return tls.Certificate{}, err
}
// Generate cert pair.
org := "btcwallet autogenerated cert"
validUntil := time.Now().Add(time.Hour * 24 * 365 * 10)
cert, key, err := btcutil.NewTLSCertPair(org, validUntil, nil)
if err != nil {
return tls.Certificate{}, err
}
keyPair, err := tls.X509KeyPair(cert, key)
if err != nil {
return tls.Certificate{}, err
}
// Write cert and (potentially) the key files.
err = ioutil.WriteFile(cfg.RPCCert.Value, cert, 0600)
if err != nil {
return tls.Certificate{}, err
}
if writeKey {
err = ioutil.WriteFile(cfg.RPCKey.Value, key, 0600)
if err != nil {
rmErr := os.Remove(cfg.RPCCert.Value)
if rmErr != nil {
log.Warnf("Cannot remove written certificates: %v",
rmErr)
}
return tls.Certificate{}, err
}
}
log.Info("Done generating TLS certificates")
return keyPair, nil
} | go | func generateRPCKeyPair(writeKey bool) (tls.Certificate, error) {
log.Infof("Generating TLS certificates...")
// Create directories for cert and key files if they do not yet exist.
certDir, _ := filepath.Split(cfg.RPCCert.Value)
keyDir, _ := filepath.Split(cfg.RPCKey.Value)
err := os.MkdirAll(certDir, 0700)
if err != nil {
return tls.Certificate{}, err
}
err = os.MkdirAll(keyDir, 0700)
if err != nil {
return tls.Certificate{}, err
}
// Generate cert pair.
org := "btcwallet autogenerated cert"
validUntil := time.Now().Add(time.Hour * 24 * 365 * 10)
cert, key, err := btcutil.NewTLSCertPair(org, validUntil, nil)
if err != nil {
return tls.Certificate{}, err
}
keyPair, err := tls.X509KeyPair(cert, key)
if err != nil {
return tls.Certificate{}, err
}
// Write cert and (potentially) the key files.
err = ioutil.WriteFile(cfg.RPCCert.Value, cert, 0600)
if err != nil {
return tls.Certificate{}, err
}
if writeKey {
err = ioutil.WriteFile(cfg.RPCKey.Value, key, 0600)
if err != nil {
rmErr := os.Remove(cfg.RPCCert.Value)
if rmErr != nil {
log.Warnf("Cannot remove written certificates: %v",
rmErr)
}
return tls.Certificate{}, err
}
}
log.Info("Done generating TLS certificates")
return keyPair, nil
} | [
"func",
"generateRPCKeyPair",
"(",
"writeKey",
"bool",
")",
"(",
"tls",
".",
"Certificate",
",",
"error",
")",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n\n",
"// Create directories for cert and key files if they do not yet exist.",
"certDir",
",",
"_",
":=",
"filepath",
".",
"Split",
"(",
"cfg",
".",
"RPCCert",
".",
"Value",
")",
"\n",
"keyDir",
",",
"_",
":=",
"filepath",
".",
"Split",
"(",
"cfg",
".",
"RPCKey",
".",
"Value",
")",
"\n",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"certDir",
",",
"0700",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"tls",
".",
"Certificate",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"err",
"=",
"os",
".",
"MkdirAll",
"(",
"keyDir",
",",
"0700",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"tls",
".",
"Certificate",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"// Generate cert pair.",
"org",
":=",
"\"",
"\"",
"\n",
"validUntil",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"time",
".",
"Hour",
"*",
"24",
"*",
"365",
"*",
"10",
")",
"\n",
"cert",
",",
"key",
",",
"err",
":=",
"btcutil",
".",
"NewTLSCertPair",
"(",
"org",
",",
"validUntil",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"tls",
".",
"Certificate",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"keyPair",
",",
"err",
":=",
"tls",
".",
"X509KeyPair",
"(",
"cert",
",",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"tls",
".",
"Certificate",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"// Write cert and (potentially) the key files.",
"err",
"=",
"ioutil",
".",
"WriteFile",
"(",
"cfg",
".",
"RPCCert",
".",
"Value",
",",
"cert",
",",
"0600",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"tls",
".",
"Certificate",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"if",
"writeKey",
"{",
"err",
"=",
"ioutil",
".",
"WriteFile",
"(",
"cfg",
".",
"RPCKey",
".",
"Value",
",",
"key",
",",
"0600",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"rmErr",
":=",
"os",
".",
"Remove",
"(",
"cfg",
".",
"RPCCert",
".",
"Value",
")",
"\n",
"if",
"rmErr",
"!=",
"nil",
"{",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"rmErr",
")",
"\n",
"}",
"\n",
"return",
"tls",
".",
"Certificate",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"keyPair",
",",
"nil",
"\n",
"}"
] | // generateRPCKeyPair generates a new RPC TLS keypair and writes the cert and
// possibly also the key in PEM format to the paths specified by the config. If
// successful, the new keypair is returned. | [
"generateRPCKeyPair",
"generates",
"a",
"new",
"RPC",
"TLS",
"keypair",
"and",
"writes",
"the",
"cert",
"and",
"possibly",
"also",
"the",
"key",
"in",
"PEM",
"format",
"to",
"the",
"paths",
"specified",
"by",
"the",
"config",
".",
"If",
"successful",
"the",
"new",
"keypair",
"is",
"returned",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpcserver.go#L57-L103 | train |
btcsuite/btcwallet | rpcserver.go | makeListeners | func makeListeners(normalizedListenAddrs []string, listen listenFunc) []net.Listener {
ipv4Addrs := make([]string, 0, len(normalizedListenAddrs)*2)
ipv6Addrs := make([]string, 0, len(normalizedListenAddrs)*2)
for _, addr := range normalizedListenAddrs {
host, _, err := net.SplitHostPort(addr)
if err != nil {
// Shouldn't happen due to already being normalized.
log.Errorf("`%s` is not a normalized "+
"listener address", addr)
continue
}
// Empty host or host of * on plan9 is both IPv4 and IPv6.
if host == "" || (host == "*" && runtime.GOOS == "plan9") {
ipv4Addrs = append(ipv4Addrs, addr)
ipv6Addrs = append(ipv6Addrs, addr)
continue
}
// Remove the IPv6 zone from the host, if present. The zone
// prevents ParseIP from correctly parsing the IP address.
// ResolveIPAddr is intentionally not used here due to the
// possibility of leaking a DNS query over Tor if the host is a
// hostname and not an IP address.
zoneIndex := strings.Index(host, "%")
if zoneIndex != -1 {
host = host[:zoneIndex]
}
ip := net.ParseIP(host)
switch {
case ip == nil:
log.Warnf("`%s` is not a valid IP address", host)
case ip.To4() == nil:
ipv6Addrs = append(ipv6Addrs, addr)
default:
ipv4Addrs = append(ipv4Addrs, addr)
}
}
listeners := make([]net.Listener, 0, len(ipv6Addrs)+len(ipv4Addrs))
for _, addr := range ipv4Addrs {
listener, err := listen("tcp4", addr)
if err != nil {
log.Warnf("Can't listen on %s: %v", addr, err)
continue
}
listeners = append(listeners, listener)
}
for _, addr := range ipv6Addrs {
listener, err := listen("tcp6", addr)
if err != nil {
log.Warnf("Can't listen on %s: %v", addr, err)
continue
}
listeners = append(listeners, listener)
}
return listeners
} | go | func makeListeners(normalizedListenAddrs []string, listen listenFunc) []net.Listener {
ipv4Addrs := make([]string, 0, len(normalizedListenAddrs)*2)
ipv6Addrs := make([]string, 0, len(normalizedListenAddrs)*2)
for _, addr := range normalizedListenAddrs {
host, _, err := net.SplitHostPort(addr)
if err != nil {
// Shouldn't happen due to already being normalized.
log.Errorf("`%s` is not a normalized "+
"listener address", addr)
continue
}
// Empty host or host of * on plan9 is both IPv4 and IPv6.
if host == "" || (host == "*" && runtime.GOOS == "plan9") {
ipv4Addrs = append(ipv4Addrs, addr)
ipv6Addrs = append(ipv6Addrs, addr)
continue
}
// Remove the IPv6 zone from the host, if present. The zone
// prevents ParseIP from correctly parsing the IP address.
// ResolveIPAddr is intentionally not used here due to the
// possibility of leaking a DNS query over Tor if the host is a
// hostname and not an IP address.
zoneIndex := strings.Index(host, "%")
if zoneIndex != -1 {
host = host[:zoneIndex]
}
ip := net.ParseIP(host)
switch {
case ip == nil:
log.Warnf("`%s` is not a valid IP address", host)
case ip.To4() == nil:
ipv6Addrs = append(ipv6Addrs, addr)
default:
ipv4Addrs = append(ipv4Addrs, addr)
}
}
listeners := make([]net.Listener, 0, len(ipv6Addrs)+len(ipv4Addrs))
for _, addr := range ipv4Addrs {
listener, err := listen("tcp4", addr)
if err != nil {
log.Warnf("Can't listen on %s: %v", addr, err)
continue
}
listeners = append(listeners, listener)
}
for _, addr := range ipv6Addrs {
listener, err := listen("tcp6", addr)
if err != nil {
log.Warnf("Can't listen on %s: %v", addr, err)
continue
}
listeners = append(listeners, listener)
}
return listeners
} | [
"func",
"makeListeners",
"(",
"normalizedListenAddrs",
"[",
"]",
"string",
",",
"listen",
"listenFunc",
")",
"[",
"]",
"net",
".",
"Listener",
"{",
"ipv4Addrs",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"normalizedListenAddrs",
")",
"*",
"2",
")",
"\n",
"ipv6Addrs",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"normalizedListenAddrs",
")",
"*",
"2",
")",
"\n",
"for",
"_",
",",
"addr",
":=",
"range",
"normalizedListenAddrs",
"{",
"host",
",",
"_",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Shouldn't happen due to already being normalized.",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"addr",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// Empty host or host of * on plan9 is both IPv4 and IPv6.",
"if",
"host",
"==",
"\"",
"\"",
"||",
"(",
"host",
"==",
"\"",
"\"",
"&&",
"runtime",
".",
"GOOS",
"==",
"\"",
"\"",
")",
"{",
"ipv4Addrs",
"=",
"append",
"(",
"ipv4Addrs",
",",
"addr",
")",
"\n",
"ipv6Addrs",
"=",
"append",
"(",
"ipv6Addrs",
",",
"addr",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// Remove the IPv6 zone from the host, if present. The zone",
"// prevents ParseIP from correctly parsing the IP address.",
"// ResolveIPAddr is intentionally not used here due to the",
"// possibility of leaking a DNS query over Tor if the host is a",
"// hostname and not an IP address.",
"zoneIndex",
":=",
"strings",
".",
"Index",
"(",
"host",
",",
"\"",
"\"",
")",
"\n",
"if",
"zoneIndex",
"!=",
"-",
"1",
"{",
"host",
"=",
"host",
"[",
":",
"zoneIndex",
"]",
"\n",
"}",
"\n\n",
"ip",
":=",
"net",
".",
"ParseIP",
"(",
"host",
")",
"\n",
"switch",
"{",
"case",
"ip",
"==",
"nil",
":",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"host",
")",
"\n",
"case",
"ip",
".",
"To4",
"(",
")",
"==",
"nil",
":",
"ipv6Addrs",
"=",
"append",
"(",
"ipv6Addrs",
",",
"addr",
")",
"\n",
"default",
":",
"ipv4Addrs",
"=",
"append",
"(",
"ipv4Addrs",
",",
"addr",
")",
"\n",
"}",
"\n",
"}",
"\n",
"listeners",
":=",
"make",
"(",
"[",
"]",
"net",
".",
"Listener",
",",
"0",
",",
"len",
"(",
"ipv6Addrs",
")",
"+",
"len",
"(",
"ipv4Addrs",
")",
")",
"\n",
"for",
"_",
",",
"addr",
":=",
"range",
"ipv4Addrs",
"{",
"listener",
",",
"err",
":=",
"listen",
"(",
"\"",
"\"",
",",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"addr",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"listeners",
"=",
"append",
"(",
"listeners",
",",
"listener",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"addr",
":=",
"range",
"ipv6Addrs",
"{",
"listener",
",",
"err",
":=",
"listen",
"(",
"\"",
"\"",
",",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"addr",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"listeners",
"=",
"append",
"(",
"listeners",
",",
"listener",
")",
"\n",
"}",
"\n",
"return",
"listeners",
"\n",
"}"
] | // makeListeners splits the normalized listen addresses into IPv4 and IPv6
// addresses and creates new net.Listeners for each with the passed listen func.
// Invalid addresses are logged and skipped. | [
"makeListeners",
"splits",
"the",
"normalized",
"listen",
"addresses",
"into",
"IPv4",
"and",
"IPv6",
"addresses",
"and",
"creates",
"new",
"net",
".",
"Listeners",
"for",
"each",
"with",
"the",
"passed",
"listen",
"func",
".",
"Invalid",
"addresses",
"are",
"logged",
"and",
"skipped",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpcserver.go#L184-L241 | train |
btcsuite/btcwallet | waddrmgr/address.go | unlock | func (a *managedAddress) unlock(key EncryptorDecryptor) ([]byte, error) {
// Protect concurrent access to clear text private key.
a.privKeyMutex.Lock()
defer a.privKeyMutex.Unlock()
if len(a.privKeyCT) == 0 {
privKey, err := key.Decrypt(a.privKeyEncrypted)
if err != nil {
str := fmt.Sprintf("failed to decrypt private key for "+
"%s", a.address)
return nil, managerError(ErrCrypto, str, err)
}
a.privKeyCT = privKey
}
privKeyCopy := make([]byte, len(a.privKeyCT))
copy(privKeyCopy, a.privKeyCT)
return privKeyCopy, nil
} | go | func (a *managedAddress) unlock(key EncryptorDecryptor) ([]byte, error) {
// Protect concurrent access to clear text private key.
a.privKeyMutex.Lock()
defer a.privKeyMutex.Unlock()
if len(a.privKeyCT) == 0 {
privKey, err := key.Decrypt(a.privKeyEncrypted)
if err != nil {
str := fmt.Sprintf("failed to decrypt private key for "+
"%s", a.address)
return nil, managerError(ErrCrypto, str, err)
}
a.privKeyCT = privKey
}
privKeyCopy := make([]byte, len(a.privKeyCT))
copy(privKeyCopy, a.privKeyCT)
return privKeyCopy, nil
} | [
"func",
"(",
"a",
"*",
"managedAddress",
")",
"unlock",
"(",
"key",
"EncryptorDecryptor",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"// Protect concurrent access to clear text private key.",
"a",
".",
"privKeyMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"a",
".",
"privKeyMutex",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"len",
"(",
"a",
".",
"privKeyCT",
")",
"==",
"0",
"{",
"privKey",
",",
"err",
":=",
"key",
".",
"Decrypt",
"(",
"a",
".",
"privKeyEncrypted",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"a",
".",
"address",
")",
"\n",
"return",
"nil",
",",
"managerError",
"(",
"ErrCrypto",
",",
"str",
",",
"err",
")",
"\n",
"}",
"\n\n",
"a",
".",
"privKeyCT",
"=",
"privKey",
"\n",
"}",
"\n\n",
"privKeyCopy",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"a",
".",
"privKeyCT",
")",
")",
"\n",
"copy",
"(",
"privKeyCopy",
",",
"a",
".",
"privKeyCT",
")",
"\n",
"return",
"privKeyCopy",
",",
"nil",
"\n",
"}"
] | // unlock decrypts and stores a pointer to the associated private key. It will
// fail if the key is invalid or the encrypted private key is not available.
// The returned clear text private key will always be a copy that may be safely
// used by the caller without worrying about it being zeroed during an address
// lock. | [
"unlock",
"decrypts",
"and",
"stores",
"a",
"pointer",
"to",
"the",
"associated",
"private",
"key",
".",
"It",
"will",
"fail",
"if",
"the",
"key",
"is",
"invalid",
"or",
"the",
"encrypted",
"private",
"key",
"is",
"not",
"available",
".",
"The",
"returned",
"clear",
"text",
"private",
"key",
"will",
"always",
"be",
"a",
"copy",
"that",
"may",
"be",
"safely",
"used",
"by",
"the",
"caller",
"without",
"worrying",
"about",
"it",
"being",
"zeroed",
"during",
"an",
"address",
"lock",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/address.go#L149-L168 | train |
btcsuite/btcwallet | waddrmgr/address.go | AddrHash | func (a *managedAddress) AddrHash() []byte {
var hash []byte
switch n := a.address.(type) {
case *btcutil.AddressPubKeyHash:
hash = n.Hash160()[:]
case *btcutil.AddressScriptHash:
hash = n.Hash160()[:]
case *btcutil.AddressWitnessPubKeyHash:
hash = n.Hash160()[:]
}
return hash
} | go | func (a *managedAddress) AddrHash() []byte {
var hash []byte
switch n := a.address.(type) {
case *btcutil.AddressPubKeyHash:
hash = n.Hash160()[:]
case *btcutil.AddressScriptHash:
hash = n.Hash160()[:]
case *btcutil.AddressWitnessPubKeyHash:
hash = n.Hash160()[:]
}
return hash
} | [
"func",
"(",
"a",
"*",
"managedAddress",
")",
"AddrHash",
"(",
")",
"[",
"]",
"byte",
"{",
"var",
"hash",
"[",
"]",
"byte",
"\n\n",
"switch",
"n",
":=",
"a",
".",
"address",
".",
"(",
"type",
")",
"{",
"case",
"*",
"btcutil",
".",
"AddressPubKeyHash",
":",
"hash",
"=",
"n",
".",
"Hash160",
"(",
")",
"[",
":",
"]",
"\n",
"case",
"*",
"btcutil",
".",
"AddressScriptHash",
":",
"hash",
"=",
"n",
".",
"Hash160",
"(",
")",
"[",
":",
"]",
"\n",
"case",
"*",
"btcutil",
".",
"AddressWitnessPubKeyHash",
":",
"hash",
"=",
"n",
".",
"Hash160",
"(",
")",
"[",
":",
"]",
"\n",
"}",
"\n\n",
"return",
"hash",
"\n",
"}"
] | // AddrHash returns the public key hash for the address.
//
// This is part of the ManagedAddress interface implementation. | [
"AddrHash",
"returns",
"the",
"public",
"key",
"hash",
"for",
"the",
"address",
".",
"This",
"is",
"part",
"of",
"the",
"ManagedAddress",
"interface",
"implementation",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/address.go#L206-L219 | train |
btcsuite/btcwallet | waddrmgr/address.go | Used | func (a *managedAddress) Used(ns walletdb.ReadBucket) bool {
return a.manager.fetchUsed(ns, a.AddrHash())
} | go | func (a *managedAddress) Used(ns walletdb.ReadBucket) bool {
return a.manager.fetchUsed(ns, a.AddrHash())
} | [
"func",
"(",
"a",
"*",
"managedAddress",
")",
"Used",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
")",
"bool",
"{",
"return",
"a",
".",
"manager",
".",
"fetchUsed",
"(",
"ns",
",",
"a",
".",
"AddrHash",
"(",
")",
")",
"\n",
"}"
] | // Used returns true if the address has been used in a transaction.
//
// This is part of the ManagedAddress interface implementation. | [
"Used",
"returns",
"true",
"if",
"the",
"address",
"has",
"been",
"used",
"in",
"a",
"transaction",
".",
"This",
"is",
"part",
"of",
"the",
"ManagedAddress",
"interface",
"implementation",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/address.go#L247-L249 | train |
btcsuite/btcwallet | waddrmgr/address.go | pubKeyBytes | func (a *managedAddress) pubKeyBytes() []byte {
if a.compressed {
return a.pubKey.SerializeCompressed()
}
return a.pubKey.SerializeUncompressed()
} | go | func (a *managedAddress) pubKeyBytes() []byte {
if a.compressed {
return a.pubKey.SerializeCompressed()
}
return a.pubKey.SerializeUncompressed()
} | [
"func",
"(",
"a",
"*",
"managedAddress",
")",
"pubKeyBytes",
"(",
")",
"[",
"]",
"byte",
"{",
"if",
"a",
".",
"compressed",
"{",
"return",
"a",
".",
"pubKey",
".",
"SerializeCompressed",
"(",
")",
"\n",
"}",
"\n",
"return",
"a",
".",
"pubKey",
".",
"SerializeUncompressed",
"(",
")",
"\n",
"}"
] | // pubKeyBytes returns the serialized public key bytes for the managed address
// based on whether or not the managed address is marked as compressed. | [
"pubKeyBytes",
"returns",
"the",
"serialized",
"public",
"key",
"bytes",
"for",
"the",
"managed",
"address",
"based",
"on",
"whether",
"or",
"not",
"the",
"managed",
"address",
"is",
"marked",
"as",
"compressed",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/address.go#L260-L265 | train |
btcsuite/btcwallet | waddrmgr/address.go | PrivKey | func (a *managedAddress) PrivKey() (*btcec.PrivateKey, error) {
// No private keys are available for a watching-only address manager.
if a.manager.rootManager.WatchOnly() {
return nil, managerError(ErrWatchingOnly, errWatchingOnly, nil)
}
a.manager.mtx.Lock()
defer a.manager.mtx.Unlock()
// Account manager must be unlocked to decrypt the private key.
if a.manager.rootManager.IsLocked() {
return nil, managerError(ErrLocked, errLocked, nil)
}
// Decrypt the key as needed. Also, make sure it's a copy since the
// private key stored in memory can be cleared at any time. Otherwise
// the returned private key could be invalidated from under the caller.
privKeyCopy, err := a.unlock(a.manager.rootManager.cryptoKeyPriv)
if err != nil {
return nil, err
}
privKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), privKeyCopy)
zero.Bytes(privKeyCopy)
return privKey, nil
} | go | func (a *managedAddress) PrivKey() (*btcec.PrivateKey, error) {
// No private keys are available for a watching-only address manager.
if a.manager.rootManager.WatchOnly() {
return nil, managerError(ErrWatchingOnly, errWatchingOnly, nil)
}
a.manager.mtx.Lock()
defer a.manager.mtx.Unlock()
// Account manager must be unlocked to decrypt the private key.
if a.manager.rootManager.IsLocked() {
return nil, managerError(ErrLocked, errLocked, nil)
}
// Decrypt the key as needed. Also, make sure it's a copy since the
// private key stored in memory can be cleared at any time. Otherwise
// the returned private key could be invalidated from under the caller.
privKeyCopy, err := a.unlock(a.manager.rootManager.cryptoKeyPriv)
if err != nil {
return nil, err
}
privKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), privKeyCopy)
zero.Bytes(privKeyCopy)
return privKey, nil
} | [
"func",
"(",
"a",
"*",
"managedAddress",
")",
"PrivKey",
"(",
")",
"(",
"*",
"btcec",
".",
"PrivateKey",
",",
"error",
")",
"{",
"// No private keys are available for a watching-only address manager.",
"if",
"a",
".",
"manager",
".",
"rootManager",
".",
"WatchOnly",
"(",
")",
"{",
"return",
"nil",
",",
"managerError",
"(",
"ErrWatchingOnly",
",",
"errWatchingOnly",
",",
"nil",
")",
"\n",
"}",
"\n\n",
"a",
".",
"manager",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"a",
".",
"manager",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"// Account manager must be unlocked to decrypt the private key.",
"if",
"a",
".",
"manager",
".",
"rootManager",
".",
"IsLocked",
"(",
")",
"{",
"return",
"nil",
",",
"managerError",
"(",
"ErrLocked",
",",
"errLocked",
",",
"nil",
")",
"\n",
"}",
"\n\n",
"// Decrypt the key as needed. Also, make sure it's a copy since the",
"// private key stored in memory can be cleared at any time. Otherwise",
"// the returned private key could be invalidated from under the caller.",
"privKeyCopy",
",",
"err",
":=",
"a",
".",
"unlock",
"(",
"a",
".",
"manager",
".",
"rootManager",
".",
"cryptoKeyPriv",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"privKey",
",",
"_",
":=",
"btcec",
".",
"PrivKeyFromBytes",
"(",
"btcec",
".",
"S256",
"(",
")",
",",
"privKeyCopy",
")",
"\n",
"zero",
".",
"Bytes",
"(",
"privKeyCopy",
")",
"\n",
"return",
"privKey",
",",
"nil",
"\n",
"}"
] | // PrivKey returns the private key for the address. It can fail if the address
// manager is watching-only or locked, or the address does not have any keys.
//
// This is part of the ManagedPubKeyAddress interface implementation. | [
"PrivKey",
"returns",
"the",
"private",
"key",
"for",
"the",
"address",
".",
"It",
"can",
"fail",
"if",
"the",
"address",
"manager",
"is",
"watching",
"-",
"only",
"or",
"locked",
"or",
"the",
"address",
"does",
"not",
"have",
"any",
"keys",
".",
"This",
"is",
"part",
"of",
"the",
"ManagedPubKeyAddress",
"interface",
"implementation",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/address.go#L279-L304 | train |
btcsuite/btcwallet | waddrmgr/address.go | DerivationInfo | func (a *managedAddress) DerivationInfo() (KeyScope, DerivationPath, bool) {
var (
scope KeyScope
path DerivationPath
)
// If this key is imported, then we can't return any information as we
// don't know precisely how the key was derived.
if a.imported {
return scope, path, false
}
return a.manager.Scope(), a.derivationPath, true
} | go | func (a *managedAddress) DerivationInfo() (KeyScope, DerivationPath, bool) {
var (
scope KeyScope
path DerivationPath
)
// If this key is imported, then we can't return any information as we
// don't know precisely how the key was derived.
if a.imported {
return scope, path, false
}
return a.manager.Scope(), a.derivationPath, true
} | [
"func",
"(",
"a",
"*",
"managedAddress",
")",
"DerivationInfo",
"(",
")",
"(",
"KeyScope",
",",
"DerivationPath",
",",
"bool",
")",
"{",
"var",
"(",
"scope",
"KeyScope",
"\n",
"path",
"DerivationPath",
"\n",
")",
"\n\n",
"// If this key is imported, then we can't return any information as we",
"// don't know precisely how the key was derived.",
"if",
"a",
".",
"imported",
"{",
"return",
"scope",
",",
"path",
",",
"false",
"\n",
"}",
"\n\n",
"return",
"a",
".",
"manager",
".",
"Scope",
"(",
")",
",",
"a",
".",
"derivationPath",
",",
"true",
"\n",
"}"
] | // Derivationinfo contains the information required to derive the key that
// backs the address via traditional methods from the HD root. For imported
// keys, the first value will be set to false to indicate that we don't know
// exactly how the key was derived.
//
// This is part of the ManagedPubKeyAddress interface implementation. | [
"Derivationinfo",
"contains",
"the",
"information",
"required",
"to",
"derive",
"the",
"key",
"that",
"backs",
"the",
"address",
"via",
"traditional",
"methods",
"from",
"the",
"HD",
"root",
".",
"For",
"imported",
"keys",
"the",
"first",
"value",
"will",
"be",
"set",
"to",
"false",
"to",
"indicate",
"that",
"we",
"don",
"t",
"know",
"exactly",
"how",
"the",
"key",
"was",
"derived",
".",
"This",
"is",
"part",
"of",
"the",
"ManagedPubKeyAddress",
"interface",
"implementation",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/address.go#L325-L338 | train |
btcsuite/btcwallet | waddrmgr/address.go | newManagedAddressWithoutPrivKey | func newManagedAddressWithoutPrivKey(m *ScopedKeyManager,
derivationPath DerivationPath, pubKey *btcec.PublicKey, compressed bool,
addrType AddressType) (*managedAddress, error) {
// Create a pay-to-pubkey-hash address from the public key.
var pubKeyHash []byte
if compressed {
pubKeyHash = btcutil.Hash160(pubKey.SerializeCompressed())
} else {
pubKeyHash = btcutil.Hash160(pubKey.SerializeUncompressed())
}
var address btcutil.Address
var err error
switch addrType {
case NestedWitnessPubKey:
// For this address type we'l generate an address which is
// backwards compatible to Bitcoin nodes running 0.6.0 onwards, but
// allows us to take advantage of segwit's scripting improvments,
// and malleability fixes.
// First, we'll generate a normal p2wkh address from the pubkey hash.
witAddr, err := btcutil.NewAddressWitnessPubKeyHash(
pubKeyHash, m.rootManager.chainParams,
)
if err != nil {
return nil, err
}
// Next we'll generate the witness program which can be used as a
// pkScript to pay to this generated address.
witnessProgram, err := txscript.PayToAddrScript(witAddr)
if err != nil {
return nil, err
}
// Finally, we'll use the witness program itself as the pre-image
// to a p2sh address. In order to spend, we first use the
// witnessProgram as the sigScript, then present the proper
// <sig, pubkey> pair as the witness.
address, err = btcutil.NewAddressScriptHash(
witnessProgram, m.rootManager.chainParams,
)
if err != nil {
return nil, err
}
case PubKeyHash:
address, err = btcutil.NewAddressPubKeyHash(
pubKeyHash, m.rootManager.chainParams,
)
if err != nil {
return nil, err
}
case WitnessPubKey:
address, err = btcutil.NewAddressWitnessPubKeyHash(
pubKeyHash, m.rootManager.chainParams,
)
if err != nil {
return nil, err
}
}
return &managedAddress{
manager: m,
address: address,
derivationPath: derivationPath,
imported: false,
internal: false,
addrType: addrType,
compressed: compressed,
pubKey: pubKey,
privKeyEncrypted: nil,
privKeyCT: nil,
}, nil
} | go | func newManagedAddressWithoutPrivKey(m *ScopedKeyManager,
derivationPath DerivationPath, pubKey *btcec.PublicKey, compressed bool,
addrType AddressType) (*managedAddress, error) {
// Create a pay-to-pubkey-hash address from the public key.
var pubKeyHash []byte
if compressed {
pubKeyHash = btcutil.Hash160(pubKey.SerializeCompressed())
} else {
pubKeyHash = btcutil.Hash160(pubKey.SerializeUncompressed())
}
var address btcutil.Address
var err error
switch addrType {
case NestedWitnessPubKey:
// For this address type we'l generate an address which is
// backwards compatible to Bitcoin nodes running 0.6.0 onwards, but
// allows us to take advantage of segwit's scripting improvments,
// and malleability fixes.
// First, we'll generate a normal p2wkh address from the pubkey hash.
witAddr, err := btcutil.NewAddressWitnessPubKeyHash(
pubKeyHash, m.rootManager.chainParams,
)
if err != nil {
return nil, err
}
// Next we'll generate the witness program which can be used as a
// pkScript to pay to this generated address.
witnessProgram, err := txscript.PayToAddrScript(witAddr)
if err != nil {
return nil, err
}
// Finally, we'll use the witness program itself as the pre-image
// to a p2sh address. In order to spend, we first use the
// witnessProgram as the sigScript, then present the proper
// <sig, pubkey> pair as the witness.
address, err = btcutil.NewAddressScriptHash(
witnessProgram, m.rootManager.chainParams,
)
if err != nil {
return nil, err
}
case PubKeyHash:
address, err = btcutil.NewAddressPubKeyHash(
pubKeyHash, m.rootManager.chainParams,
)
if err != nil {
return nil, err
}
case WitnessPubKey:
address, err = btcutil.NewAddressWitnessPubKeyHash(
pubKeyHash, m.rootManager.chainParams,
)
if err != nil {
return nil, err
}
}
return &managedAddress{
manager: m,
address: address,
derivationPath: derivationPath,
imported: false,
internal: false,
addrType: addrType,
compressed: compressed,
pubKey: pubKey,
privKeyEncrypted: nil,
privKeyCT: nil,
}, nil
} | [
"func",
"newManagedAddressWithoutPrivKey",
"(",
"m",
"*",
"ScopedKeyManager",
",",
"derivationPath",
"DerivationPath",
",",
"pubKey",
"*",
"btcec",
".",
"PublicKey",
",",
"compressed",
"bool",
",",
"addrType",
"AddressType",
")",
"(",
"*",
"managedAddress",
",",
"error",
")",
"{",
"// Create a pay-to-pubkey-hash address from the public key.",
"var",
"pubKeyHash",
"[",
"]",
"byte",
"\n",
"if",
"compressed",
"{",
"pubKeyHash",
"=",
"btcutil",
".",
"Hash160",
"(",
"pubKey",
".",
"SerializeCompressed",
"(",
")",
")",
"\n",
"}",
"else",
"{",
"pubKeyHash",
"=",
"btcutil",
".",
"Hash160",
"(",
"pubKey",
".",
"SerializeUncompressed",
"(",
")",
")",
"\n",
"}",
"\n\n",
"var",
"address",
"btcutil",
".",
"Address",
"\n",
"var",
"err",
"error",
"\n\n",
"switch",
"addrType",
"{",
"case",
"NestedWitnessPubKey",
":",
"// For this address type we'l generate an address which is",
"// backwards compatible to Bitcoin nodes running 0.6.0 onwards, but",
"// allows us to take advantage of segwit's scripting improvments,",
"// and malleability fixes.",
"// First, we'll generate a normal p2wkh address from the pubkey hash.",
"witAddr",
",",
"err",
":=",
"btcutil",
".",
"NewAddressWitnessPubKeyHash",
"(",
"pubKeyHash",
",",
"m",
".",
"rootManager",
".",
"chainParams",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Next we'll generate the witness program which can be used as a",
"// pkScript to pay to this generated address.",
"witnessProgram",
",",
"err",
":=",
"txscript",
".",
"PayToAddrScript",
"(",
"witAddr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Finally, we'll use the witness program itself as the pre-image",
"// to a p2sh address. In order to spend, we first use the",
"// witnessProgram as the sigScript, then present the proper",
"// <sig, pubkey> pair as the witness.",
"address",
",",
"err",
"=",
"btcutil",
".",
"NewAddressScriptHash",
"(",
"witnessProgram",
",",
"m",
".",
"rootManager",
".",
"chainParams",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"case",
"PubKeyHash",
":",
"address",
",",
"err",
"=",
"btcutil",
".",
"NewAddressPubKeyHash",
"(",
"pubKeyHash",
",",
"m",
".",
"rootManager",
".",
"chainParams",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"case",
"WitnessPubKey",
":",
"address",
",",
"err",
"=",
"btcutil",
".",
"NewAddressWitnessPubKeyHash",
"(",
"pubKeyHash",
",",
"m",
".",
"rootManager",
".",
"chainParams",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"&",
"managedAddress",
"{",
"manager",
":",
"m",
",",
"address",
":",
"address",
",",
"derivationPath",
":",
"derivationPath",
",",
"imported",
":",
"false",
",",
"internal",
":",
"false",
",",
"addrType",
":",
"addrType",
",",
"compressed",
":",
"compressed",
",",
"pubKey",
":",
"pubKey",
",",
"privKeyEncrypted",
":",
"nil",
",",
"privKeyCT",
":",
"nil",
",",
"}",
",",
"nil",
"\n",
"}"
] | // newManagedAddressWithoutPrivKey returns a new managed address based on the
// passed account, public key, and whether or not the public key should be
// compressed. | [
"newManagedAddressWithoutPrivKey",
"returns",
"a",
"new",
"managed",
"address",
"based",
"on",
"the",
"passed",
"account",
"public",
"key",
"and",
"whether",
"or",
"not",
"the",
"public",
"key",
"should",
"be",
"compressed",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/address.go#L343-L421 | train |
btcsuite/btcwallet | waddrmgr/address.go | newManagedAddress | func newManagedAddress(s *ScopedKeyManager, derivationPath DerivationPath,
privKey *btcec.PrivateKey, compressed bool,
addrType AddressType) (*managedAddress, error) {
// Encrypt the private key.
//
// NOTE: The privKeyBytes here are set into the managed address which
// are cleared when locked, so they aren't cleared here.
privKeyBytes := privKey.Serialize()
privKeyEncrypted, err := s.rootManager.cryptoKeyPriv.Encrypt(privKeyBytes)
if err != nil {
str := "failed to encrypt private key"
return nil, managerError(ErrCrypto, str, err)
}
// Leverage the code to create a managed address without a private key
// and then add the private key to it.
ecPubKey := (*btcec.PublicKey)(&privKey.PublicKey)
managedAddr, err := newManagedAddressWithoutPrivKey(
s, derivationPath, ecPubKey, compressed, addrType,
)
if err != nil {
return nil, err
}
managedAddr.privKeyEncrypted = privKeyEncrypted
managedAddr.privKeyCT = privKeyBytes
return managedAddr, nil
} | go | func newManagedAddress(s *ScopedKeyManager, derivationPath DerivationPath,
privKey *btcec.PrivateKey, compressed bool,
addrType AddressType) (*managedAddress, error) {
// Encrypt the private key.
//
// NOTE: The privKeyBytes here are set into the managed address which
// are cleared when locked, so they aren't cleared here.
privKeyBytes := privKey.Serialize()
privKeyEncrypted, err := s.rootManager.cryptoKeyPriv.Encrypt(privKeyBytes)
if err != nil {
str := "failed to encrypt private key"
return nil, managerError(ErrCrypto, str, err)
}
// Leverage the code to create a managed address without a private key
// and then add the private key to it.
ecPubKey := (*btcec.PublicKey)(&privKey.PublicKey)
managedAddr, err := newManagedAddressWithoutPrivKey(
s, derivationPath, ecPubKey, compressed, addrType,
)
if err != nil {
return nil, err
}
managedAddr.privKeyEncrypted = privKeyEncrypted
managedAddr.privKeyCT = privKeyBytes
return managedAddr, nil
} | [
"func",
"newManagedAddress",
"(",
"s",
"*",
"ScopedKeyManager",
",",
"derivationPath",
"DerivationPath",
",",
"privKey",
"*",
"btcec",
".",
"PrivateKey",
",",
"compressed",
"bool",
",",
"addrType",
"AddressType",
")",
"(",
"*",
"managedAddress",
",",
"error",
")",
"{",
"// Encrypt the private key.",
"//",
"// NOTE: The privKeyBytes here are set into the managed address which",
"// are cleared when locked, so they aren't cleared here.",
"privKeyBytes",
":=",
"privKey",
".",
"Serialize",
"(",
")",
"\n",
"privKeyEncrypted",
",",
"err",
":=",
"s",
".",
"rootManager",
".",
"cryptoKeyPriv",
".",
"Encrypt",
"(",
"privKeyBytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"str",
":=",
"\"",
"\"",
"\n",
"return",
"nil",
",",
"managerError",
"(",
"ErrCrypto",
",",
"str",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Leverage the code to create a managed address without a private key",
"// and then add the private key to it.",
"ecPubKey",
":=",
"(",
"*",
"btcec",
".",
"PublicKey",
")",
"(",
"&",
"privKey",
".",
"PublicKey",
")",
"\n",
"managedAddr",
",",
"err",
":=",
"newManagedAddressWithoutPrivKey",
"(",
"s",
",",
"derivationPath",
",",
"ecPubKey",
",",
"compressed",
",",
"addrType",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"managedAddr",
".",
"privKeyEncrypted",
"=",
"privKeyEncrypted",
"\n",
"managedAddr",
".",
"privKeyCT",
"=",
"privKeyBytes",
"\n\n",
"return",
"managedAddr",
",",
"nil",
"\n",
"}"
] | // newManagedAddress returns a new managed address based on the passed account,
// private key, and whether or not the public key is compressed. The managed
// address will have access to the private and public keys. | [
"newManagedAddress",
"returns",
"a",
"new",
"managed",
"address",
"based",
"on",
"the",
"passed",
"account",
"private",
"key",
"and",
"whether",
"or",
"not",
"the",
"public",
"key",
"is",
"compressed",
".",
"The",
"managed",
"address",
"will",
"have",
"access",
"to",
"the",
"private",
"and",
"public",
"keys",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/address.go#L426-L454 | train |
btcsuite/btcwallet | waddrmgr/address.go | newManagedAddressFromExtKey | func newManagedAddressFromExtKey(s *ScopedKeyManager,
derivationPath DerivationPath, key *hdkeychain.ExtendedKey,
addrType AddressType) (*managedAddress, error) {
// Create a new managed address based on the public or private key
// depending on whether the generated key is private.
var managedAddr *managedAddress
if key.IsPrivate() {
privKey, err := key.ECPrivKey()
if err != nil {
return nil, err
}
// Ensure the temp private key big integer is cleared after
// use.
managedAddr, err = newManagedAddress(
s, derivationPath, privKey, true, addrType,
)
if err != nil {
return nil, err
}
} else {
pubKey, err := key.ECPubKey()
if err != nil {
return nil, err
}
managedAddr, err = newManagedAddressWithoutPrivKey(
s, derivationPath, pubKey, true,
addrType,
)
if err != nil {
return nil, err
}
}
return managedAddr, nil
} | go | func newManagedAddressFromExtKey(s *ScopedKeyManager,
derivationPath DerivationPath, key *hdkeychain.ExtendedKey,
addrType AddressType) (*managedAddress, error) {
// Create a new managed address based on the public or private key
// depending on whether the generated key is private.
var managedAddr *managedAddress
if key.IsPrivate() {
privKey, err := key.ECPrivKey()
if err != nil {
return nil, err
}
// Ensure the temp private key big integer is cleared after
// use.
managedAddr, err = newManagedAddress(
s, derivationPath, privKey, true, addrType,
)
if err != nil {
return nil, err
}
} else {
pubKey, err := key.ECPubKey()
if err != nil {
return nil, err
}
managedAddr, err = newManagedAddressWithoutPrivKey(
s, derivationPath, pubKey, true,
addrType,
)
if err != nil {
return nil, err
}
}
return managedAddr, nil
} | [
"func",
"newManagedAddressFromExtKey",
"(",
"s",
"*",
"ScopedKeyManager",
",",
"derivationPath",
"DerivationPath",
",",
"key",
"*",
"hdkeychain",
".",
"ExtendedKey",
",",
"addrType",
"AddressType",
")",
"(",
"*",
"managedAddress",
",",
"error",
")",
"{",
"// Create a new managed address based on the public or private key",
"// depending on whether the generated key is private.",
"var",
"managedAddr",
"*",
"managedAddress",
"\n",
"if",
"key",
".",
"IsPrivate",
"(",
")",
"{",
"privKey",
",",
"err",
":=",
"key",
".",
"ECPrivKey",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Ensure the temp private key big integer is cleared after",
"// use.",
"managedAddr",
",",
"err",
"=",
"newManagedAddress",
"(",
"s",
",",
"derivationPath",
",",
"privKey",
",",
"true",
",",
"addrType",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"else",
"{",
"pubKey",
",",
"err",
":=",
"key",
".",
"ECPubKey",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"managedAddr",
",",
"err",
"=",
"newManagedAddressWithoutPrivKey",
"(",
"s",
",",
"derivationPath",
",",
"pubKey",
",",
"true",
",",
"addrType",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"managedAddr",
",",
"nil",
"\n",
"}"
] | // newManagedAddressFromExtKey returns a new managed address based on the passed
// account and extended key. The managed address will have access to the
// private and public keys if the provided extended key is private, otherwise it
// will only have access to the public key. | [
"newManagedAddressFromExtKey",
"returns",
"a",
"new",
"managed",
"address",
"based",
"on",
"the",
"passed",
"account",
"and",
"extended",
"key",
".",
"The",
"managed",
"address",
"will",
"have",
"access",
"to",
"the",
"private",
"and",
"public",
"keys",
"if",
"the",
"provided",
"extended",
"key",
"is",
"private",
"otherwise",
"it",
"will",
"only",
"have",
"access",
"to",
"the",
"public",
"key",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/address.go#L460-L497 | train |
btcsuite/btcwallet | waddrmgr/address.go | unlock | func (a *scriptAddress) unlock(key EncryptorDecryptor) ([]byte, error) {
// Protect concurrent access to clear text script.
a.scriptMutex.Lock()
defer a.scriptMutex.Unlock()
if len(a.scriptCT) == 0 {
script, err := key.Decrypt(a.scriptEncrypted)
if err != nil {
str := fmt.Sprintf("failed to decrypt script for %s",
a.address)
return nil, managerError(ErrCrypto, str, err)
}
a.scriptCT = script
}
scriptCopy := make([]byte, len(a.scriptCT))
copy(scriptCopy, a.scriptCT)
return scriptCopy, nil
} | go | func (a *scriptAddress) unlock(key EncryptorDecryptor) ([]byte, error) {
// Protect concurrent access to clear text script.
a.scriptMutex.Lock()
defer a.scriptMutex.Unlock()
if len(a.scriptCT) == 0 {
script, err := key.Decrypt(a.scriptEncrypted)
if err != nil {
str := fmt.Sprintf("failed to decrypt script for %s",
a.address)
return nil, managerError(ErrCrypto, str, err)
}
a.scriptCT = script
}
scriptCopy := make([]byte, len(a.scriptCT))
copy(scriptCopy, a.scriptCT)
return scriptCopy, nil
} | [
"func",
"(",
"a",
"*",
"scriptAddress",
")",
"unlock",
"(",
"key",
"EncryptorDecryptor",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"// Protect concurrent access to clear text script.",
"a",
".",
"scriptMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"a",
".",
"scriptMutex",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"len",
"(",
"a",
".",
"scriptCT",
")",
"==",
"0",
"{",
"script",
",",
"err",
":=",
"key",
".",
"Decrypt",
"(",
"a",
".",
"scriptEncrypted",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"a",
".",
"address",
")",
"\n",
"return",
"nil",
",",
"managerError",
"(",
"ErrCrypto",
",",
"str",
",",
"err",
")",
"\n",
"}",
"\n\n",
"a",
".",
"scriptCT",
"=",
"script",
"\n",
"}",
"\n\n",
"scriptCopy",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"a",
".",
"scriptCT",
")",
")",
"\n",
"copy",
"(",
"scriptCopy",
",",
"a",
".",
"scriptCT",
")",
"\n",
"return",
"scriptCopy",
",",
"nil",
"\n",
"}"
] | // unlock decrypts and stores the associated script. It will fail if the key is
// invalid or the encrypted script is not available. The returned clear text
// script will always be a copy that may be safely used by the caller without
// worrying about it being zeroed during an address lock. | [
"unlock",
"decrypts",
"and",
"stores",
"the",
"associated",
"script",
".",
"It",
"will",
"fail",
"if",
"the",
"key",
"is",
"invalid",
"or",
"the",
"encrypted",
"script",
"is",
"not",
"available",
".",
"The",
"returned",
"clear",
"text",
"script",
"will",
"always",
"be",
"a",
"copy",
"that",
"may",
"be",
"safely",
"used",
"by",
"the",
"caller",
"without",
"worrying",
"about",
"it",
"being",
"zeroed",
"during",
"an",
"address",
"lock",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/address.go#L517-L536 | train |
btcsuite/btcwallet | waddrmgr/address.go | Script | func (a *scriptAddress) Script() ([]byte, error) {
// No script is available for a watching-only address manager.
if a.manager.rootManager.WatchOnly() {
return nil, managerError(ErrWatchingOnly, errWatchingOnly, nil)
}
a.manager.mtx.Lock()
defer a.manager.mtx.Unlock()
// Account manager must be unlocked to decrypt the script.
if a.manager.rootManager.IsLocked() {
return nil, managerError(ErrLocked, errLocked, nil)
}
// Decrypt the script as needed. Also, make sure it's a copy since the
// script stored in memory can be cleared at any time. Otherwise,
// the returned script could be invalidated from under the caller.
return a.unlock(a.manager.rootManager.cryptoKeyScript)
} | go | func (a *scriptAddress) Script() ([]byte, error) {
// No script is available for a watching-only address manager.
if a.manager.rootManager.WatchOnly() {
return nil, managerError(ErrWatchingOnly, errWatchingOnly, nil)
}
a.manager.mtx.Lock()
defer a.manager.mtx.Unlock()
// Account manager must be unlocked to decrypt the script.
if a.manager.rootManager.IsLocked() {
return nil, managerError(ErrLocked, errLocked, nil)
}
// Decrypt the script as needed. Also, make sure it's a copy since the
// script stored in memory can be cleared at any time. Otherwise,
// the returned script could be invalidated from under the caller.
return a.unlock(a.manager.rootManager.cryptoKeyScript)
} | [
"func",
"(",
"a",
"*",
"scriptAddress",
")",
"Script",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"// No script is available for a watching-only address manager.",
"if",
"a",
".",
"manager",
".",
"rootManager",
".",
"WatchOnly",
"(",
")",
"{",
"return",
"nil",
",",
"managerError",
"(",
"ErrWatchingOnly",
",",
"errWatchingOnly",
",",
"nil",
")",
"\n",
"}",
"\n\n",
"a",
".",
"manager",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"a",
".",
"manager",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"// Account manager must be unlocked to decrypt the script.",
"if",
"a",
".",
"manager",
".",
"rootManager",
".",
"IsLocked",
"(",
")",
"{",
"return",
"nil",
",",
"managerError",
"(",
"ErrLocked",
",",
"errLocked",
",",
"nil",
")",
"\n",
"}",
"\n\n",
"// Decrypt the script as needed. Also, make sure it's a copy since the",
"// script stored in memory can be cleared at any time. Otherwise,",
"// the returned script could be invalidated from under the caller.",
"return",
"a",
".",
"unlock",
"(",
"a",
".",
"manager",
".",
"rootManager",
".",
"cryptoKeyScript",
")",
"\n",
"}"
] | // Script returns the script associated with the address.
//
// This implements the ScriptAddress interface. | [
"Script",
"returns",
"the",
"script",
"associated",
"with",
"the",
"address",
".",
"This",
"implements",
"the",
"ScriptAddress",
"interface",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/address.go#L611-L629 | train |
btcsuite/btcwallet | waddrmgr/address.go | newScriptAddress | func newScriptAddress(m *ScopedKeyManager, account uint32, scriptHash,
scriptEncrypted []byte) (*scriptAddress, error) {
address, err := btcutil.NewAddressScriptHashFromHash(
scriptHash, m.rootManager.chainParams,
)
if err != nil {
return nil, err
}
return &scriptAddress{
manager: m,
account: account,
address: address,
scriptEncrypted: scriptEncrypted,
}, nil
} | go | func newScriptAddress(m *ScopedKeyManager, account uint32, scriptHash,
scriptEncrypted []byte) (*scriptAddress, error) {
address, err := btcutil.NewAddressScriptHashFromHash(
scriptHash, m.rootManager.chainParams,
)
if err != nil {
return nil, err
}
return &scriptAddress{
manager: m,
account: account,
address: address,
scriptEncrypted: scriptEncrypted,
}, nil
} | [
"func",
"newScriptAddress",
"(",
"m",
"*",
"ScopedKeyManager",
",",
"account",
"uint32",
",",
"scriptHash",
",",
"scriptEncrypted",
"[",
"]",
"byte",
")",
"(",
"*",
"scriptAddress",
",",
"error",
")",
"{",
"address",
",",
"err",
":=",
"btcutil",
".",
"NewAddressScriptHashFromHash",
"(",
"scriptHash",
",",
"m",
".",
"rootManager",
".",
"chainParams",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"scriptAddress",
"{",
"manager",
":",
"m",
",",
"account",
":",
"account",
",",
"address",
":",
"address",
",",
"scriptEncrypted",
":",
"scriptEncrypted",
",",
"}",
",",
"nil",
"\n",
"}"
] | // newScriptAddress initializes and returns a new pay-to-script-hash address. | [
"newScriptAddress",
"initializes",
"and",
"returns",
"a",
"new",
"pay",
"-",
"to",
"-",
"script",
"-",
"hash",
"address",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/address.go#L632-L648 | train |
btcsuite/btcwallet | walletdb/bdb/db.go | convertErr | func convertErr(err error) error {
switch err {
// Database open/create errors.
case bbolt.ErrDatabaseNotOpen:
return walletdb.ErrDbNotOpen
case bbolt.ErrInvalid:
return walletdb.ErrInvalid
// Transaction errors.
case bbolt.ErrTxNotWritable:
return walletdb.ErrTxNotWritable
case bbolt.ErrTxClosed:
return walletdb.ErrTxClosed
// Value/bucket errors.
case bbolt.ErrBucketNotFound:
return walletdb.ErrBucketNotFound
case bbolt.ErrBucketExists:
return walletdb.ErrBucketExists
case bbolt.ErrBucketNameRequired:
return walletdb.ErrBucketNameRequired
case bbolt.ErrKeyRequired:
return walletdb.ErrKeyRequired
case bbolt.ErrKeyTooLarge:
return walletdb.ErrKeyTooLarge
case bbolt.ErrValueTooLarge:
return walletdb.ErrValueTooLarge
case bbolt.ErrIncompatibleValue:
return walletdb.ErrIncompatibleValue
}
// Return the original error if none of the above applies.
return err
} | go | func convertErr(err error) error {
switch err {
// Database open/create errors.
case bbolt.ErrDatabaseNotOpen:
return walletdb.ErrDbNotOpen
case bbolt.ErrInvalid:
return walletdb.ErrInvalid
// Transaction errors.
case bbolt.ErrTxNotWritable:
return walletdb.ErrTxNotWritable
case bbolt.ErrTxClosed:
return walletdb.ErrTxClosed
// Value/bucket errors.
case bbolt.ErrBucketNotFound:
return walletdb.ErrBucketNotFound
case bbolt.ErrBucketExists:
return walletdb.ErrBucketExists
case bbolt.ErrBucketNameRequired:
return walletdb.ErrBucketNameRequired
case bbolt.ErrKeyRequired:
return walletdb.ErrKeyRequired
case bbolt.ErrKeyTooLarge:
return walletdb.ErrKeyTooLarge
case bbolt.ErrValueTooLarge:
return walletdb.ErrValueTooLarge
case bbolt.ErrIncompatibleValue:
return walletdb.ErrIncompatibleValue
}
// Return the original error if none of the above applies.
return err
} | [
"func",
"convertErr",
"(",
"err",
"error",
")",
"error",
"{",
"switch",
"err",
"{",
"// Database open/create errors.",
"case",
"bbolt",
".",
"ErrDatabaseNotOpen",
":",
"return",
"walletdb",
".",
"ErrDbNotOpen",
"\n",
"case",
"bbolt",
".",
"ErrInvalid",
":",
"return",
"walletdb",
".",
"ErrInvalid",
"\n\n",
"// Transaction errors.",
"case",
"bbolt",
".",
"ErrTxNotWritable",
":",
"return",
"walletdb",
".",
"ErrTxNotWritable",
"\n",
"case",
"bbolt",
".",
"ErrTxClosed",
":",
"return",
"walletdb",
".",
"ErrTxClosed",
"\n\n",
"// Value/bucket errors.",
"case",
"bbolt",
".",
"ErrBucketNotFound",
":",
"return",
"walletdb",
".",
"ErrBucketNotFound",
"\n",
"case",
"bbolt",
".",
"ErrBucketExists",
":",
"return",
"walletdb",
".",
"ErrBucketExists",
"\n",
"case",
"bbolt",
".",
"ErrBucketNameRequired",
":",
"return",
"walletdb",
".",
"ErrBucketNameRequired",
"\n",
"case",
"bbolt",
".",
"ErrKeyRequired",
":",
"return",
"walletdb",
".",
"ErrKeyRequired",
"\n",
"case",
"bbolt",
".",
"ErrKeyTooLarge",
":",
"return",
"walletdb",
".",
"ErrKeyTooLarge",
"\n",
"case",
"bbolt",
".",
"ErrValueTooLarge",
":",
"return",
"walletdb",
".",
"ErrValueTooLarge",
"\n",
"case",
"bbolt",
".",
"ErrIncompatibleValue",
":",
"return",
"walletdb",
".",
"ErrIncompatibleValue",
"\n",
"}",
"\n\n",
"// Return the original error if none of the above applies.",
"return",
"err",
"\n",
"}"
] | // convertErr converts some bolt errors to the equivalent walletdb error. | [
"convertErr",
"converts",
"some",
"bolt",
"errors",
"to",
"the",
"equivalent",
"walletdb",
"error",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/walletdb/bdb/db.go#L16-L49 | train |
btcsuite/btcwallet | walletdb/bdb/db.go | NestedReadWriteBucket | func (b *bucket) NestedReadWriteBucket(key []byte) walletdb.ReadWriteBucket {
boltBucket := (*bbolt.Bucket)(b).Bucket(key)
// Don't return a non-nil interface to a nil pointer.
if boltBucket == nil {
return nil
}
return (*bucket)(boltBucket)
} | go | func (b *bucket) NestedReadWriteBucket(key []byte) walletdb.ReadWriteBucket {
boltBucket := (*bbolt.Bucket)(b).Bucket(key)
// Don't return a non-nil interface to a nil pointer.
if boltBucket == nil {
return nil
}
return (*bucket)(boltBucket)
} | [
"func",
"(",
"b",
"*",
"bucket",
")",
"NestedReadWriteBucket",
"(",
"key",
"[",
"]",
"byte",
")",
"walletdb",
".",
"ReadWriteBucket",
"{",
"boltBucket",
":=",
"(",
"*",
"bbolt",
".",
"Bucket",
")",
"(",
"b",
")",
".",
"Bucket",
"(",
"key",
")",
"\n",
"// Don't return a non-nil interface to a nil pointer.",
"if",
"boltBucket",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"(",
"*",
"bucket",
")",
"(",
"boltBucket",
")",
"\n",
"}"
] | // NestedReadWriteBucket retrieves a nested bucket with the given key. Returns
// nil if the bucket does not exist.
//
// This function is part of the walletdb.ReadWriteBucket interface implementation. | [
"NestedReadWriteBucket",
"retrieves",
"a",
"nested",
"bucket",
"with",
"the",
"given",
"key",
".",
"Returns",
"nil",
"if",
"the",
"bucket",
"does",
"not",
"exist",
".",
"This",
"function",
"is",
"part",
"of",
"the",
"walletdb",
".",
"ReadWriteBucket",
"interface",
"implementation",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/walletdb/bdb/db.go#L121-L128 | train |
btcsuite/btcwallet | walletdb/bdb/db.go | CreateBucket | func (b *bucket) CreateBucket(key []byte) (walletdb.ReadWriteBucket, error) {
boltBucket, err := (*bbolt.Bucket)(b).CreateBucket(key)
if err != nil {
return nil, convertErr(err)
}
return (*bucket)(boltBucket), nil
} | go | func (b *bucket) CreateBucket(key []byte) (walletdb.ReadWriteBucket, error) {
boltBucket, err := (*bbolt.Bucket)(b).CreateBucket(key)
if err != nil {
return nil, convertErr(err)
}
return (*bucket)(boltBucket), nil
} | [
"func",
"(",
"b",
"*",
"bucket",
")",
"CreateBucket",
"(",
"key",
"[",
"]",
"byte",
")",
"(",
"walletdb",
".",
"ReadWriteBucket",
",",
"error",
")",
"{",
"boltBucket",
",",
"err",
":=",
"(",
"*",
"bbolt",
".",
"Bucket",
")",
"(",
"b",
")",
".",
"CreateBucket",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"convertErr",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"(",
"*",
"bucket",
")",
"(",
"boltBucket",
")",
",",
"nil",
"\n",
"}"
] | // CreateBucket creates and returns a new nested bucket with the given key.
// Returns ErrBucketExists if the bucket already exists, ErrBucketNameRequired
// if the key is empty, or ErrIncompatibleValue if the key value is otherwise
// invalid.
//
// This function is part of the walletdb.ReadWriteBucket interface implementation. | [
"CreateBucket",
"creates",
"and",
"returns",
"a",
"new",
"nested",
"bucket",
"with",
"the",
"given",
"key",
".",
"Returns",
"ErrBucketExists",
"if",
"the",
"bucket",
"already",
"exists",
"ErrBucketNameRequired",
"if",
"the",
"key",
"is",
"empty",
"or",
"ErrIncompatibleValue",
"if",
"the",
"key",
"value",
"is",
"otherwise",
"invalid",
".",
"This",
"function",
"is",
"part",
"of",
"the",
"walletdb",
".",
"ReadWriteBucket",
"interface",
"implementation",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/walletdb/bdb/db.go#L140-L146 | train |
btcsuite/btcwallet | walletdb/bdb/db.go | DeleteNestedBucket | func (b *bucket) DeleteNestedBucket(key []byte) error {
return convertErr((*bbolt.Bucket)(b).DeleteBucket(key))
} | go | func (b *bucket) DeleteNestedBucket(key []byte) error {
return convertErr((*bbolt.Bucket)(b).DeleteBucket(key))
} | [
"func",
"(",
"b",
"*",
"bucket",
")",
"DeleteNestedBucket",
"(",
"key",
"[",
"]",
"byte",
")",
"error",
"{",
"return",
"convertErr",
"(",
"(",
"*",
"bbolt",
".",
"Bucket",
")",
"(",
"b",
")",
".",
"DeleteBucket",
"(",
"key",
")",
")",
"\n",
"}"
] | // DeleteNestedBucket removes a nested bucket with the given key. Returns
// ErrTxNotWritable if attempted against a read-only transaction and
// ErrBucketNotFound if the specified bucket does not exist.
//
// This function is part of the walletdb.ReadWriteBucket interface implementation. | [
"DeleteNestedBucket",
"removes",
"a",
"nested",
"bucket",
"with",
"the",
"given",
"key",
".",
"Returns",
"ErrTxNotWritable",
"if",
"attempted",
"against",
"a",
"read",
"-",
"only",
"transaction",
"and",
"ErrBucketNotFound",
"if",
"the",
"specified",
"bucket",
"does",
"not",
"exist",
".",
"This",
"function",
"is",
"part",
"of",
"the",
"walletdb",
".",
"ReadWriteBucket",
"interface",
"implementation",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/walletdb/bdb/db.go#L166-L168 | train |
btcsuite/btcwallet | walletdb/bdb/db.go | Delete | func (b *bucket) Delete(key []byte) error {
return convertErr((*bbolt.Bucket)(b).Delete(key))
} | go | func (b *bucket) Delete(key []byte) error {
return convertErr((*bbolt.Bucket)(b).Delete(key))
} | [
"func",
"(",
"b",
"*",
"bucket",
")",
"Delete",
"(",
"key",
"[",
"]",
"byte",
")",
"error",
"{",
"return",
"convertErr",
"(",
"(",
"*",
"bbolt",
".",
"Bucket",
")",
"(",
"b",
")",
".",
"Delete",
"(",
"key",
")",
")",
"\n",
"}"
] | // Delete removes the specified key from the bucket. Deleting a key that does
// not exist does not return an error. Returns ErrTxNotWritable if attempted
// against a read-only transaction.
//
// This function is part of the walletdb.ReadWriteBucket interface implementation. | [
"Delete",
"removes",
"the",
"specified",
"key",
"from",
"the",
"bucket",
".",
"Deleting",
"a",
"key",
"that",
"does",
"not",
"exist",
"does",
"not",
"return",
"an",
"error",
".",
"Returns",
"ErrTxNotWritable",
"if",
"attempted",
"against",
"a",
"read",
"-",
"only",
"transaction",
".",
"This",
"function",
"is",
"part",
"of",
"the",
"walletdb",
".",
"ReadWriteBucket",
"interface",
"implementation",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/walletdb/bdb/db.go#L209-L211 | train |
btcsuite/btcwallet | walletdb/bdb/db.go | Tx | func (b *bucket) Tx() walletdb.ReadWriteTx {
return &transaction{
(*bbolt.Bucket)(b).Tx(),
}
} | go | func (b *bucket) Tx() walletdb.ReadWriteTx {
return &transaction{
(*bbolt.Bucket)(b).Tx(),
}
} | [
"func",
"(",
"b",
"*",
"bucket",
")",
"Tx",
"(",
")",
"walletdb",
".",
"ReadWriteTx",
"{",
"return",
"&",
"transaction",
"{",
"(",
"*",
"bbolt",
".",
"Bucket",
")",
"(",
"b",
")",
".",
"Tx",
"(",
")",
",",
"}",
"\n",
"}"
] | // Tx returns the bucket's transaction.
//
// This function is part of the walletdb.ReadWriteBucket interface implementation. | [
"Tx",
"returns",
"the",
"bucket",
"s",
"transaction",
".",
"This",
"function",
"is",
"part",
"of",
"the",
"walletdb",
".",
"ReadWriteBucket",
"interface",
"implementation",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/walletdb/bdb/db.go#L228-L232 | train |
btcsuite/btcwallet | walletdb/bdb/db.go | Seek | func (c *cursor) Seek(seek []byte) (key, value []byte) {
return (*bbolt.Cursor)(c).Seek(seek)
} | go | func (c *cursor) Seek(seek []byte) (key, value []byte) {
return (*bbolt.Cursor)(c).Seek(seek)
} | [
"func",
"(",
"c",
"*",
"cursor",
")",
"Seek",
"(",
"seek",
"[",
"]",
"byte",
")",
"(",
"key",
",",
"value",
"[",
"]",
"byte",
")",
"{",
"return",
"(",
"*",
"bbolt",
".",
"Cursor",
")",
"(",
"c",
")",
".",
"Seek",
"(",
"seek",
")",
"\n",
"}"
] | // Seek positions the cursor at the passed seek key. If the key does not exist,
// the cursor is moved to the next key after seek. Returns the new pair.
//
// This function is part of the walletdb.ReadCursor interface implementation. | [
"Seek",
"positions",
"the",
"cursor",
"at",
"the",
"passed",
"seek",
"key",
".",
"If",
"the",
"key",
"does",
"not",
"exist",
"the",
"cursor",
"is",
"moved",
"to",
"the",
"next",
"key",
"after",
"seek",
".",
"Returns",
"the",
"new",
"pair",
".",
"This",
"function",
"is",
"part",
"of",
"the",
"walletdb",
".",
"ReadCursor",
"interface",
"implementation",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/walletdb/bdb/db.go#L285-L287 | train |
btcsuite/btcwallet | walletdb/bdb/db.go | Copy | func (db *db) Copy(w io.Writer) error {
return convertErr((*bbolt.DB)(db).View(func(tx *bbolt.Tx) error {
return tx.Copy(w)
}))
} | go | func (db *db) Copy(w io.Writer) error {
return convertErr((*bbolt.DB)(db).View(func(tx *bbolt.Tx) error {
return tx.Copy(w)
}))
} | [
"func",
"(",
"db",
"*",
"db",
")",
"Copy",
"(",
"w",
"io",
".",
"Writer",
")",
"error",
"{",
"return",
"convertErr",
"(",
"(",
"*",
"bbolt",
".",
"DB",
")",
"(",
"db",
")",
".",
"View",
"(",
"func",
"(",
"tx",
"*",
"bbolt",
".",
"Tx",
")",
"error",
"{",
"return",
"tx",
".",
"Copy",
"(",
"w",
")",
"\n",
"}",
")",
")",
"\n",
"}"
] | // Copy writes a copy of the database to the provided writer. This call will
// start a read-only transaction to perform all operations.
//
// This function is part of the walletdb.Db interface implementation. | [
"Copy",
"writes",
"a",
"copy",
"of",
"the",
"database",
"to",
"the",
"provided",
"writer",
".",
"This",
"call",
"will",
"start",
"a",
"read",
"-",
"only",
"transaction",
"to",
"perform",
"all",
"operations",
".",
"This",
"function",
"is",
"part",
"of",
"the",
"walletdb",
".",
"Db",
"interface",
"implementation",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/walletdb/bdb/db.go#L317-L321 | train |
btcsuite/btcwallet | walletdb/bdb/db.go | openDB | func openDB(dbPath string, create bool) (walletdb.DB, error) {
if !create && !fileExists(dbPath) {
return nil, walletdb.ErrDbDoesNotExist
}
boltDB, err := bbolt.Open(dbPath, 0600, nil)
return (*db)(boltDB), convertErr(err)
} | go | func openDB(dbPath string, create bool) (walletdb.DB, error) {
if !create && !fileExists(dbPath) {
return nil, walletdb.ErrDbDoesNotExist
}
boltDB, err := bbolt.Open(dbPath, 0600, nil)
return (*db)(boltDB), convertErr(err)
} | [
"func",
"openDB",
"(",
"dbPath",
"string",
",",
"create",
"bool",
")",
"(",
"walletdb",
".",
"DB",
",",
"error",
")",
"{",
"if",
"!",
"create",
"&&",
"!",
"fileExists",
"(",
"dbPath",
")",
"{",
"return",
"nil",
",",
"walletdb",
".",
"ErrDbDoesNotExist",
"\n",
"}",
"\n\n",
"boltDB",
",",
"err",
":=",
"bbolt",
".",
"Open",
"(",
"dbPath",
",",
"0600",
",",
"nil",
")",
"\n",
"return",
"(",
"*",
"db",
")",
"(",
"boltDB",
")",
",",
"convertErr",
"(",
"err",
")",
"\n",
"}"
] | // openDB opens the database at the provided path. walletdb.ErrDbDoesNotExist
// is returned if the database doesn't exist and the create flag is not set. | [
"openDB",
"opens",
"the",
"database",
"at",
"the",
"provided",
"path",
".",
"walletdb",
".",
"ErrDbDoesNotExist",
"is",
"returned",
"if",
"the",
"database",
"doesn",
"t",
"exist",
"and",
"the",
"create",
"flag",
"is",
"not",
"set",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/walletdb/bdb/db.go#L342-L349 | train |
btcsuite/btcwallet | wallet/createtx.go | validateMsgTx | func validateMsgTx(tx *wire.MsgTx, prevScripts [][]byte, inputValues []btcutil.Amount) error {
hashCache := txscript.NewTxSigHashes(tx)
for i, prevScript := range prevScripts {
vm, err := txscript.NewEngine(prevScript, tx, i,
txscript.StandardVerifyFlags, nil, hashCache, int64(inputValues[i]))
if err != nil {
return fmt.Errorf("cannot create script engine: %s", err)
}
err = vm.Execute()
if err != nil {
return fmt.Errorf("cannot validate transaction: %s", err)
}
}
return nil
} | go | func validateMsgTx(tx *wire.MsgTx, prevScripts [][]byte, inputValues []btcutil.Amount) error {
hashCache := txscript.NewTxSigHashes(tx)
for i, prevScript := range prevScripts {
vm, err := txscript.NewEngine(prevScript, tx, i,
txscript.StandardVerifyFlags, nil, hashCache, int64(inputValues[i]))
if err != nil {
return fmt.Errorf("cannot create script engine: %s", err)
}
err = vm.Execute()
if err != nil {
return fmt.Errorf("cannot validate transaction: %s", err)
}
}
return nil
} | [
"func",
"validateMsgTx",
"(",
"tx",
"*",
"wire",
".",
"MsgTx",
",",
"prevScripts",
"[",
"]",
"[",
"]",
"byte",
",",
"inputValues",
"[",
"]",
"btcutil",
".",
"Amount",
")",
"error",
"{",
"hashCache",
":=",
"txscript",
".",
"NewTxSigHashes",
"(",
"tx",
")",
"\n",
"for",
"i",
",",
"prevScript",
":=",
"range",
"prevScripts",
"{",
"vm",
",",
"err",
":=",
"txscript",
".",
"NewEngine",
"(",
"prevScript",
",",
"tx",
",",
"i",
",",
"txscript",
".",
"StandardVerifyFlags",
",",
"nil",
",",
"hashCache",
",",
"int64",
"(",
"inputValues",
"[",
"i",
"]",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"err",
"=",
"vm",
".",
"Execute",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // validateMsgTx verifies transaction input scripts for tx. All previous output
// scripts from outputs redeemed by the transaction, in the same order they are
// spent, must be passed in the prevScripts slice. | [
"validateMsgTx",
"verifies",
"transaction",
"input",
"scripts",
"for",
"tx",
".",
"All",
"previous",
"output",
"scripts",
"from",
"outputs",
"redeemed",
"by",
"the",
"transaction",
"in",
"the",
"same",
"order",
"they",
"are",
"spent",
"must",
"be",
"passed",
"in",
"the",
"prevScripts",
"slice",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/createtx.go#L270-L284 | train |
btcsuite/btcwallet | btcwallet.go | rpcClientConnectLoop | func rpcClientConnectLoop(legacyRPCServer *legacyrpc.Server, loader *wallet.Loader) {
var certs []byte
if !cfg.UseSPV {
certs = readCAFile()
}
for {
var (
chainClient chain.Interface
err error
)
if cfg.UseSPV {
var (
chainService *neutrino.ChainService
spvdb walletdb.DB
)
netDir := networkDir(cfg.AppDataDir.Value, activeNet.Params)
spvdb, err = walletdb.Create("bdb",
filepath.Join(netDir, "neutrino.db"))
defer spvdb.Close()
if err != nil {
log.Errorf("Unable to create Neutrino DB: %s", err)
continue
}
chainService, err = neutrino.NewChainService(
neutrino.Config{
DataDir: netDir,
Database: spvdb,
ChainParams: *activeNet.Params,
ConnectPeers: cfg.ConnectPeers,
AddPeers: cfg.AddPeers,
})
if err != nil {
log.Errorf("Couldn't create Neutrino ChainService: %s", err)
continue
}
chainClient = chain.NewNeutrinoClient(activeNet.Params, chainService)
err = chainClient.Start()
if err != nil {
log.Errorf("Couldn't start Neutrino client: %s", err)
}
} else {
chainClient, err = startChainRPC(certs)
if err != nil {
log.Errorf("Unable to open connection to consensus RPC server: %v", err)
continue
}
}
// Rather than inlining this logic directly into the loader
// callback, a function variable is used to avoid running any of
// this after the client disconnects by setting it to nil. This
// prevents the callback from associating a wallet loaded at a
// later time with a client that has already disconnected. A
// mutex is used to make this concurrent safe.
associateRPCClient := func(w *wallet.Wallet) {
w.SynchronizeRPC(chainClient)
if legacyRPCServer != nil {
legacyRPCServer.SetChainServer(chainClient)
}
}
mu := new(sync.Mutex)
loader.RunAfterLoad(func(w *wallet.Wallet) {
mu.Lock()
associate := associateRPCClient
mu.Unlock()
if associate != nil {
associate(w)
}
})
chainClient.WaitForShutdown()
mu.Lock()
associateRPCClient = nil
mu.Unlock()
loadedWallet, ok := loader.LoadedWallet()
if ok {
// Do not attempt a reconnect when the wallet was
// explicitly stopped.
if loadedWallet.ShuttingDown() {
return
}
loadedWallet.SetChainSynced(false)
// TODO: Rework the wallet so changing the RPC client
// does not require stopping and restarting everything.
loadedWallet.Stop()
loadedWallet.WaitForShutdown()
loadedWallet.Start()
}
}
} | go | func rpcClientConnectLoop(legacyRPCServer *legacyrpc.Server, loader *wallet.Loader) {
var certs []byte
if !cfg.UseSPV {
certs = readCAFile()
}
for {
var (
chainClient chain.Interface
err error
)
if cfg.UseSPV {
var (
chainService *neutrino.ChainService
spvdb walletdb.DB
)
netDir := networkDir(cfg.AppDataDir.Value, activeNet.Params)
spvdb, err = walletdb.Create("bdb",
filepath.Join(netDir, "neutrino.db"))
defer spvdb.Close()
if err != nil {
log.Errorf("Unable to create Neutrino DB: %s", err)
continue
}
chainService, err = neutrino.NewChainService(
neutrino.Config{
DataDir: netDir,
Database: spvdb,
ChainParams: *activeNet.Params,
ConnectPeers: cfg.ConnectPeers,
AddPeers: cfg.AddPeers,
})
if err != nil {
log.Errorf("Couldn't create Neutrino ChainService: %s", err)
continue
}
chainClient = chain.NewNeutrinoClient(activeNet.Params, chainService)
err = chainClient.Start()
if err != nil {
log.Errorf("Couldn't start Neutrino client: %s", err)
}
} else {
chainClient, err = startChainRPC(certs)
if err != nil {
log.Errorf("Unable to open connection to consensus RPC server: %v", err)
continue
}
}
// Rather than inlining this logic directly into the loader
// callback, a function variable is used to avoid running any of
// this after the client disconnects by setting it to nil. This
// prevents the callback from associating a wallet loaded at a
// later time with a client that has already disconnected. A
// mutex is used to make this concurrent safe.
associateRPCClient := func(w *wallet.Wallet) {
w.SynchronizeRPC(chainClient)
if legacyRPCServer != nil {
legacyRPCServer.SetChainServer(chainClient)
}
}
mu := new(sync.Mutex)
loader.RunAfterLoad(func(w *wallet.Wallet) {
mu.Lock()
associate := associateRPCClient
mu.Unlock()
if associate != nil {
associate(w)
}
})
chainClient.WaitForShutdown()
mu.Lock()
associateRPCClient = nil
mu.Unlock()
loadedWallet, ok := loader.LoadedWallet()
if ok {
// Do not attempt a reconnect when the wallet was
// explicitly stopped.
if loadedWallet.ShuttingDown() {
return
}
loadedWallet.SetChainSynced(false)
// TODO: Rework the wallet so changing the RPC client
// does not require stopping and restarting everything.
loadedWallet.Stop()
loadedWallet.WaitForShutdown()
loadedWallet.Start()
}
}
} | [
"func",
"rpcClientConnectLoop",
"(",
"legacyRPCServer",
"*",
"legacyrpc",
".",
"Server",
",",
"loader",
"*",
"wallet",
".",
"Loader",
")",
"{",
"var",
"certs",
"[",
"]",
"byte",
"\n",
"if",
"!",
"cfg",
".",
"UseSPV",
"{",
"certs",
"=",
"readCAFile",
"(",
")",
"\n",
"}",
"\n\n",
"for",
"{",
"var",
"(",
"chainClient",
"chain",
".",
"Interface",
"\n",
"err",
"error",
"\n",
")",
"\n\n",
"if",
"cfg",
".",
"UseSPV",
"{",
"var",
"(",
"chainService",
"*",
"neutrino",
".",
"ChainService",
"\n",
"spvdb",
"walletdb",
".",
"DB",
"\n",
")",
"\n",
"netDir",
":=",
"networkDir",
"(",
"cfg",
".",
"AppDataDir",
".",
"Value",
",",
"activeNet",
".",
"Params",
")",
"\n",
"spvdb",
",",
"err",
"=",
"walletdb",
".",
"Create",
"(",
"\"",
"\"",
",",
"filepath",
".",
"Join",
"(",
"netDir",
",",
"\"",
"\"",
")",
")",
"\n",
"defer",
"spvdb",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"chainService",
",",
"err",
"=",
"neutrino",
".",
"NewChainService",
"(",
"neutrino",
".",
"Config",
"{",
"DataDir",
":",
"netDir",
",",
"Database",
":",
"spvdb",
",",
"ChainParams",
":",
"*",
"activeNet",
".",
"Params",
",",
"ConnectPeers",
":",
"cfg",
".",
"ConnectPeers",
",",
"AddPeers",
":",
"cfg",
".",
"AddPeers",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"chainClient",
"=",
"chain",
".",
"NewNeutrinoClient",
"(",
"activeNet",
".",
"Params",
",",
"chainService",
")",
"\n",
"err",
"=",
"chainClient",
".",
"Start",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"chainClient",
",",
"err",
"=",
"startChainRPC",
"(",
"certs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Rather than inlining this logic directly into the loader",
"// callback, a function variable is used to avoid running any of",
"// this after the client disconnects by setting it to nil. This",
"// prevents the callback from associating a wallet loaded at a",
"// later time with a client that has already disconnected. A",
"// mutex is used to make this concurrent safe.",
"associateRPCClient",
":=",
"func",
"(",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"{",
"w",
".",
"SynchronizeRPC",
"(",
"chainClient",
")",
"\n",
"if",
"legacyRPCServer",
"!=",
"nil",
"{",
"legacyRPCServer",
".",
"SetChainServer",
"(",
"chainClient",
")",
"\n",
"}",
"\n",
"}",
"\n",
"mu",
":=",
"new",
"(",
"sync",
".",
"Mutex",
")",
"\n",
"loader",
".",
"RunAfterLoad",
"(",
"func",
"(",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"{",
"mu",
".",
"Lock",
"(",
")",
"\n",
"associate",
":=",
"associateRPCClient",
"\n",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"associate",
"!=",
"nil",
"{",
"associate",
"(",
"w",
")",
"\n",
"}",
"\n",
"}",
")",
"\n\n",
"chainClient",
".",
"WaitForShutdown",
"(",
")",
"\n\n",
"mu",
".",
"Lock",
"(",
")",
"\n",
"associateRPCClient",
"=",
"nil",
"\n",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"loadedWallet",
",",
"ok",
":=",
"loader",
".",
"LoadedWallet",
"(",
")",
"\n",
"if",
"ok",
"{",
"// Do not attempt a reconnect when the wallet was",
"// explicitly stopped.",
"if",
"loadedWallet",
".",
"ShuttingDown",
"(",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"loadedWallet",
".",
"SetChainSynced",
"(",
"false",
")",
"\n\n",
"// TODO: Rework the wallet so changing the RPC client",
"// does not require stopping and restarting everything.",
"loadedWallet",
".",
"Stop",
"(",
")",
"\n",
"loadedWallet",
".",
"WaitForShutdown",
"(",
")",
"\n",
"loadedWallet",
".",
"Start",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // rpcClientConnectLoop continuously attempts a connection to the consensus RPC
// server. When a connection is established, the client is used to sync the
// loaded wallet, either immediately or when loaded at a later time.
//
// The legacy RPC is optional. If set, the connected RPC client will be
// associated with the server for RPC passthrough and to enable additional
// methods. | [
"rpcClientConnectLoop",
"continuously",
"attempts",
"a",
"connection",
"to",
"the",
"consensus",
"RPC",
"server",
".",
"When",
"a",
"connection",
"is",
"established",
"the",
"client",
"is",
"used",
"to",
"sync",
"the",
"loaded",
"wallet",
"either",
"immediately",
"or",
"when",
"loaded",
"at",
"a",
"later",
"time",
".",
"The",
"legacy",
"RPC",
"is",
"optional",
".",
"If",
"set",
"the",
"connected",
"RPC",
"client",
"will",
"be",
"associated",
"with",
"the",
"server",
"for",
"RPC",
"passthrough",
"and",
"to",
"enable",
"additional",
"methods",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/btcwallet.go#L145-L240 | train |
btcsuite/btcwallet | btcwallet.go | startChainRPC | func startChainRPC(certs []byte) (*chain.RPCClient, error) {
log.Infof("Attempting RPC client connection to %v", cfg.RPCConnect)
rpcc, err := chain.NewRPCClient(activeNet.Params, cfg.RPCConnect,
cfg.BtcdUsername, cfg.BtcdPassword, certs, cfg.DisableClientTLS, 0)
if err != nil {
return nil, err
}
err = rpcc.Start()
return rpcc, err
} | go | func startChainRPC(certs []byte) (*chain.RPCClient, error) {
log.Infof("Attempting RPC client connection to %v", cfg.RPCConnect)
rpcc, err := chain.NewRPCClient(activeNet.Params, cfg.RPCConnect,
cfg.BtcdUsername, cfg.BtcdPassword, certs, cfg.DisableClientTLS, 0)
if err != nil {
return nil, err
}
err = rpcc.Start()
return rpcc, err
} | [
"func",
"startChainRPC",
"(",
"certs",
"[",
"]",
"byte",
")",
"(",
"*",
"chain",
".",
"RPCClient",
",",
"error",
")",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"cfg",
".",
"RPCConnect",
")",
"\n",
"rpcc",
",",
"err",
":=",
"chain",
".",
"NewRPCClient",
"(",
"activeNet",
".",
"Params",
",",
"cfg",
".",
"RPCConnect",
",",
"cfg",
".",
"BtcdUsername",
",",
"cfg",
".",
"BtcdPassword",
",",
"certs",
",",
"cfg",
".",
"DisableClientTLS",
",",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"err",
"=",
"rpcc",
".",
"Start",
"(",
")",
"\n",
"return",
"rpcc",
",",
"err",
"\n",
"}"
] | // startChainRPC opens a RPC client connection to a btcd server for blockchain
// services. This function uses the RPC options from the global config and
// there is no recovery in case the server is not available or if there is an
// authentication error. Instead, all requests to the client will simply error. | [
"startChainRPC",
"opens",
"a",
"RPC",
"client",
"connection",
"to",
"a",
"btcd",
"server",
"for",
"blockchain",
"services",
".",
"This",
"function",
"uses",
"the",
"RPC",
"options",
"from",
"the",
"global",
"config",
"and",
"there",
"is",
"no",
"recovery",
"in",
"case",
"the",
"server",
"is",
"not",
"available",
"or",
"if",
"there",
"is",
"an",
"authentication",
"error",
".",
"Instead",
"all",
"requests",
"to",
"the",
"client",
"will",
"simply",
"error",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/btcwallet.go#L265-L274 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | binaryRead | func binaryRead(r io.Reader, order binary.ByteOrder, data interface{}) (n int64, err error) {
var read int
buf := make([]byte, binary.Size(data))
if read, err = io.ReadFull(r, buf); err != nil {
return int64(read), err
}
return int64(read), binary.Read(bytes.NewBuffer(buf), order, data)
} | go | func binaryRead(r io.Reader, order binary.ByteOrder, data interface{}) (n int64, err error) {
var read int
buf := make([]byte, binary.Size(data))
if read, err = io.ReadFull(r, buf); err != nil {
return int64(read), err
}
return int64(read), binary.Read(bytes.NewBuffer(buf), order, data)
} | [
"func",
"binaryRead",
"(",
"r",
"io",
".",
"Reader",
",",
"order",
"binary",
".",
"ByteOrder",
",",
"data",
"interface",
"{",
"}",
")",
"(",
"n",
"int64",
",",
"err",
"error",
")",
"{",
"var",
"read",
"int",
"\n",
"buf",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"binary",
".",
"Size",
"(",
"data",
")",
")",
"\n",
"if",
"read",
",",
"err",
"=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"buf",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"int64",
"(",
"read",
")",
",",
"err",
"\n",
"}",
"\n",
"return",
"int64",
"(",
"read",
")",
",",
"binary",
".",
"Read",
"(",
"bytes",
".",
"NewBuffer",
"(",
"buf",
")",
",",
"order",
",",
"data",
")",
"\n",
"}"
] | // We want to use binaryRead and binaryWrite instead of binary.Read
// and binary.Write because those from the binary package do not return
// the number of bytes actually written or read. We need to return
// this value to correctly support the io.ReaderFrom and io.WriterTo
// interfaces. | [
"We",
"want",
"to",
"use",
"binaryRead",
"and",
"binaryWrite",
"instead",
"of",
"binary",
".",
"Read",
"and",
"binary",
".",
"Write",
"because",
"those",
"from",
"the",
"binary",
"package",
"do",
"not",
"return",
"the",
"number",
"of",
"bytes",
"actually",
"written",
"or",
"read",
".",
"We",
"need",
"to",
"return",
"this",
"value",
"to",
"correctly",
"support",
"the",
"io",
".",
"ReaderFrom",
"and",
"io",
".",
"WriterTo",
"interfaces",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L81-L88 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | pubkeyFromPrivkey | func pubkeyFromPrivkey(privkey []byte, compress bool) (pubkey []byte) {
_, pk := btcec.PrivKeyFromBytes(btcec.S256(), privkey)
if compress {
return pk.SerializeCompressed()
}
return pk.SerializeUncompressed()
} | go | func pubkeyFromPrivkey(privkey []byte, compress bool) (pubkey []byte) {
_, pk := btcec.PrivKeyFromBytes(btcec.S256(), privkey)
if compress {
return pk.SerializeCompressed()
}
return pk.SerializeUncompressed()
} | [
"func",
"pubkeyFromPrivkey",
"(",
"privkey",
"[",
"]",
"byte",
",",
"compress",
"bool",
")",
"(",
"pubkey",
"[",
"]",
"byte",
")",
"{",
"_",
",",
"pk",
":=",
"btcec",
".",
"PrivKeyFromBytes",
"(",
"btcec",
".",
"S256",
"(",
")",
",",
"privkey",
")",
"\n\n",
"if",
"compress",
"{",
"return",
"pk",
".",
"SerializeCompressed",
"(",
")",
"\n",
"}",
"\n",
"return",
"pk",
".",
"SerializeUncompressed",
"(",
")",
"\n",
"}"
] | // pubkeyFromPrivkey creates an encoded pubkey based on a
// 32-byte privkey. The returned pubkey is 33 bytes if compressed,
// or 65 bytes if uncompressed. | [
"pubkeyFromPrivkey",
"creates",
"an",
"encoded",
"pubkey",
"based",
"on",
"a",
"32",
"-",
"byte",
"privkey",
".",
"The",
"returned",
"pubkey",
"is",
"33",
"bytes",
"if",
"compressed",
"or",
"65",
"bytes",
"if",
"uncompressed",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L104-L111 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | chainedPrivKey | func chainedPrivKey(privkey, pubkey, chaincode []byte) ([]byte, error) {
if len(privkey) != 32 {
return nil, fmt.Errorf("invalid privkey length %d (must be 32)",
len(privkey))
}
if len(chaincode) != 32 {
return nil, fmt.Errorf("invalid chaincode length %d (must be 32)",
len(chaincode))
}
switch n := len(pubkey); n {
case btcec.PubKeyBytesLenUncompressed, btcec.PubKeyBytesLenCompressed:
// Correct length
default:
return nil, fmt.Errorf("invalid pubkey length %d", n)
}
xorbytes := make([]byte, 32)
chainMod := chainhash.DoubleHashB(pubkey)
for i := range xorbytes {
xorbytes[i] = chainMod[i] ^ chaincode[i]
}
chainXor := new(big.Int).SetBytes(xorbytes)
privint := new(big.Int).SetBytes(privkey)
t := new(big.Int).Mul(chainXor, privint)
b := t.Mod(t, btcec.S256().N).Bytes()
return pad(32, b), nil
} | go | func chainedPrivKey(privkey, pubkey, chaincode []byte) ([]byte, error) {
if len(privkey) != 32 {
return nil, fmt.Errorf("invalid privkey length %d (must be 32)",
len(privkey))
}
if len(chaincode) != 32 {
return nil, fmt.Errorf("invalid chaincode length %d (must be 32)",
len(chaincode))
}
switch n := len(pubkey); n {
case btcec.PubKeyBytesLenUncompressed, btcec.PubKeyBytesLenCompressed:
// Correct length
default:
return nil, fmt.Errorf("invalid pubkey length %d", n)
}
xorbytes := make([]byte, 32)
chainMod := chainhash.DoubleHashB(pubkey)
for i := range xorbytes {
xorbytes[i] = chainMod[i] ^ chaincode[i]
}
chainXor := new(big.Int).SetBytes(xorbytes)
privint := new(big.Int).SetBytes(privkey)
t := new(big.Int).Mul(chainXor, privint)
b := t.Mod(t, btcec.S256().N).Bytes()
return pad(32, b), nil
} | [
"func",
"chainedPrivKey",
"(",
"privkey",
",",
"pubkey",
",",
"chaincode",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"len",
"(",
"privkey",
")",
"!=",
"32",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"privkey",
")",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"chaincode",
")",
"!=",
"32",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"chaincode",
")",
")",
"\n",
"}",
"\n",
"switch",
"n",
":=",
"len",
"(",
"pubkey",
")",
";",
"n",
"{",
"case",
"btcec",
".",
"PubKeyBytesLenUncompressed",
",",
"btcec",
".",
"PubKeyBytesLenCompressed",
":",
"// Correct length",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"n",
")",
"\n",
"}",
"\n\n",
"xorbytes",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"32",
")",
"\n",
"chainMod",
":=",
"chainhash",
".",
"DoubleHashB",
"(",
"pubkey",
")",
"\n",
"for",
"i",
":=",
"range",
"xorbytes",
"{",
"xorbytes",
"[",
"i",
"]",
"=",
"chainMod",
"[",
"i",
"]",
"^",
"chaincode",
"[",
"i",
"]",
"\n",
"}",
"\n",
"chainXor",
":=",
"new",
"(",
"big",
".",
"Int",
")",
".",
"SetBytes",
"(",
"xorbytes",
")",
"\n",
"privint",
":=",
"new",
"(",
"big",
".",
"Int",
")",
".",
"SetBytes",
"(",
"privkey",
")",
"\n\n",
"t",
":=",
"new",
"(",
"big",
".",
"Int",
")",
".",
"Mul",
"(",
"chainXor",
",",
"privint",
")",
"\n",
"b",
":=",
"t",
".",
"Mod",
"(",
"t",
",",
"btcec",
".",
"S256",
"(",
")",
".",
"N",
")",
".",
"Bytes",
"(",
")",
"\n",
"return",
"pad",
"(",
"32",
",",
"b",
")",
",",
"nil",
"\n",
"}"
] | // chainedPrivKey deterministically generates a new private key using a
// previous address and chaincode. privkey and chaincode must be 32
// bytes long, and pubkey may either be 33 or 65 bytes. | [
"chainedPrivKey",
"deterministically",
"generates",
"a",
"new",
"private",
"key",
"using",
"a",
"previous",
"address",
"and",
"chaincode",
".",
"privkey",
"and",
"chaincode",
"must",
"be",
"32",
"bytes",
"long",
"and",
"pubkey",
"may",
"either",
"be",
"33",
"or",
"65",
"bytes",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L177-L204 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | chainedPubKey | func chainedPubKey(pubkey, chaincode []byte) ([]byte, error) {
var compressed bool
switch n := len(pubkey); n {
case btcec.PubKeyBytesLenUncompressed:
compressed = false
case btcec.PubKeyBytesLenCompressed:
compressed = true
default:
// Incorrect serialized pubkey length
return nil, fmt.Errorf("invalid pubkey length %d", n)
}
if len(chaincode) != 32 {
return nil, fmt.Errorf("invalid chaincode length %d (must be 32)",
len(chaincode))
}
xorbytes := make([]byte, 32)
chainMod := chainhash.DoubleHashB(pubkey)
for i := range xorbytes {
xorbytes[i] = chainMod[i] ^ chaincode[i]
}
oldPk, err := btcec.ParsePubKey(pubkey, btcec.S256())
if err != nil {
return nil, err
}
newX, newY := btcec.S256().ScalarMult(oldPk.X, oldPk.Y, xorbytes)
if err != nil {
return nil, err
}
newPk := &btcec.PublicKey{
Curve: btcec.S256(),
X: newX,
Y: newY,
}
if compressed {
return newPk.SerializeCompressed(), nil
}
return newPk.SerializeUncompressed(), nil
} | go | func chainedPubKey(pubkey, chaincode []byte) ([]byte, error) {
var compressed bool
switch n := len(pubkey); n {
case btcec.PubKeyBytesLenUncompressed:
compressed = false
case btcec.PubKeyBytesLenCompressed:
compressed = true
default:
// Incorrect serialized pubkey length
return nil, fmt.Errorf("invalid pubkey length %d", n)
}
if len(chaincode) != 32 {
return nil, fmt.Errorf("invalid chaincode length %d (must be 32)",
len(chaincode))
}
xorbytes := make([]byte, 32)
chainMod := chainhash.DoubleHashB(pubkey)
for i := range xorbytes {
xorbytes[i] = chainMod[i] ^ chaincode[i]
}
oldPk, err := btcec.ParsePubKey(pubkey, btcec.S256())
if err != nil {
return nil, err
}
newX, newY := btcec.S256().ScalarMult(oldPk.X, oldPk.Y, xorbytes)
if err != nil {
return nil, err
}
newPk := &btcec.PublicKey{
Curve: btcec.S256(),
X: newX,
Y: newY,
}
if compressed {
return newPk.SerializeCompressed(), nil
}
return newPk.SerializeUncompressed(), nil
} | [
"func",
"chainedPubKey",
"(",
"pubkey",
",",
"chaincode",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"compressed",
"bool",
"\n",
"switch",
"n",
":=",
"len",
"(",
"pubkey",
")",
";",
"n",
"{",
"case",
"btcec",
".",
"PubKeyBytesLenUncompressed",
":",
"compressed",
"=",
"false",
"\n",
"case",
"btcec",
".",
"PubKeyBytesLenCompressed",
":",
"compressed",
"=",
"true",
"\n",
"default",
":",
"// Incorrect serialized pubkey length",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"n",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"chaincode",
")",
"!=",
"32",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"chaincode",
")",
")",
"\n",
"}",
"\n\n",
"xorbytes",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"32",
")",
"\n",
"chainMod",
":=",
"chainhash",
".",
"DoubleHashB",
"(",
"pubkey",
")",
"\n",
"for",
"i",
":=",
"range",
"xorbytes",
"{",
"xorbytes",
"[",
"i",
"]",
"=",
"chainMod",
"[",
"i",
"]",
"^",
"chaincode",
"[",
"i",
"]",
"\n",
"}",
"\n\n",
"oldPk",
",",
"err",
":=",
"btcec",
".",
"ParsePubKey",
"(",
"pubkey",
",",
"btcec",
".",
"S256",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"newX",
",",
"newY",
":=",
"btcec",
".",
"S256",
"(",
")",
".",
"ScalarMult",
"(",
"oldPk",
".",
"X",
",",
"oldPk",
".",
"Y",
",",
"xorbytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"newPk",
":=",
"&",
"btcec",
".",
"PublicKey",
"{",
"Curve",
":",
"btcec",
".",
"S256",
"(",
")",
",",
"X",
":",
"newX",
",",
"Y",
":",
"newY",
",",
"}",
"\n\n",
"if",
"compressed",
"{",
"return",
"newPk",
".",
"SerializeCompressed",
"(",
")",
",",
"nil",
"\n",
"}",
"\n",
"return",
"newPk",
".",
"SerializeUncompressed",
"(",
")",
",",
"nil",
"\n",
"}"
] | // chainedPubKey deterministically generates a new public key using a
// previous public key and chaincode. pubkey must be 33 or 65 bytes, and
// chaincode must be 32 bytes long. | [
"chainedPubKey",
"deterministically",
"generates",
"a",
"new",
"public",
"key",
"using",
"a",
"previous",
"public",
"key",
"and",
"chaincode",
".",
"pubkey",
"must",
"be",
"33",
"or",
"65",
"bytes",
"and",
"chaincode",
"must",
"be",
"32",
"bytes",
"long",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L209-L249 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | LT | func (v version) LT(v2 version) bool {
switch {
case v.major < v2.major:
return true
case v.minor < v2.minor:
return true
case v.bugfix < v2.bugfix:
return true
case v.autoincrement < v2.autoincrement:
return true
default:
return false
}
} | go | func (v version) LT(v2 version) bool {
switch {
case v.major < v2.major:
return true
case v.minor < v2.minor:
return true
case v.bugfix < v2.bugfix:
return true
case v.autoincrement < v2.autoincrement:
return true
default:
return false
}
} | [
"func",
"(",
"v",
"version",
")",
"LT",
"(",
"v2",
"version",
")",
"bool",
"{",
"switch",
"{",
"case",
"v",
".",
"major",
"<",
"v2",
".",
"major",
":",
"return",
"true",
"\n\n",
"case",
"v",
".",
"minor",
"<",
"v2",
".",
"minor",
":",
"return",
"true",
"\n\n",
"case",
"v",
".",
"bugfix",
"<",
"v2",
".",
"bugfix",
":",
"return",
"true",
"\n\n",
"case",
"v",
".",
"autoincrement",
"<",
"v2",
".",
"autoincrement",
":",
"return",
"true",
"\n\n",
"default",
":",
"return",
"false",
"\n",
"}",
"\n",
"}"
] | // LT returns whether v is an earlier version than v2. | [
"LT",
"returns",
"whether",
"v",
"is",
"an",
"earlier",
"version",
"than",
"v2",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L313-L330 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | New | func New(dir string, desc string, passphrase []byte, net *chaincfg.Params,
createdAt *BlockStamp) (*Store, error) {
// Check sizes of inputs.
if len(desc) > 256 {
return nil, errors.New("desc exceeds 256 byte maximum size")
}
// Randomly-generate rootkey and chaincode.
rootkey := make([]byte, 32)
if _, err := rand.Read(rootkey); err != nil {
return nil, err
}
chaincode := make([]byte, 32)
if _, err := rand.Read(chaincode); err != nil {
return nil, err
}
// Compute AES key and encrypt root address.
kdfp, err := computeKdfParameters(defaultKdfComputeTime, defaultKdfMaxMem)
if err != nil {
return nil, err
}
aeskey := kdf(passphrase, kdfp)
// Create and fill key store.
s := &Store{
path: filepath.Join(dir, Filename),
dir: dir,
file: Filename,
vers: VersCurrent,
net: (*netParams)(net),
flags: walletFlags{
useEncryption: true,
watchingOnly: false,
},
createDate: time.Now().Unix(),
highestUsed: rootKeyChainIdx,
kdfParams: *kdfp,
recent: recentBlocks{
lastHeight: createdAt.Height,
hashes: []*chainhash.Hash{
createdAt.Hash,
},
},
addrMap: make(map[addressKey]walletAddress),
chainIdxMap: make(map[int64]btcutil.Address),
lastChainIdx: rootKeyChainIdx,
missingKeysStart: rootKeyChainIdx,
secret: aeskey,
}
copy(s.desc[:], []byte(desc))
// Create new root address from key and chaincode.
root, err := newRootBtcAddress(s, rootkey, nil, chaincode,
createdAt)
if err != nil {
return nil, err
}
// Verify root address keypairs.
if err := root.verifyKeypairs(); err != nil {
return nil, err
}
if err := root.encrypt(aeskey); err != nil {
return nil, err
}
s.keyGenerator = *root
// Add root address to maps.
rootAddr := s.keyGenerator.Address()
s.addrMap[getAddressKey(rootAddr)] = &s.keyGenerator
s.chainIdxMap[rootKeyChainIdx] = rootAddr
// key store must be returned locked.
if err := s.Lock(); err != nil {
return nil, err
}
return s, nil
} | go | func New(dir string, desc string, passphrase []byte, net *chaincfg.Params,
createdAt *BlockStamp) (*Store, error) {
// Check sizes of inputs.
if len(desc) > 256 {
return nil, errors.New("desc exceeds 256 byte maximum size")
}
// Randomly-generate rootkey and chaincode.
rootkey := make([]byte, 32)
if _, err := rand.Read(rootkey); err != nil {
return nil, err
}
chaincode := make([]byte, 32)
if _, err := rand.Read(chaincode); err != nil {
return nil, err
}
// Compute AES key and encrypt root address.
kdfp, err := computeKdfParameters(defaultKdfComputeTime, defaultKdfMaxMem)
if err != nil {
return nil, err
}
aeskey := kdf(passphrase, kdfp)
// Create and fill key store.
s := &Store{
path: filepath.Join(dir, Filename),
dir: dir,
file: Filename,
vers: VersCurrent,
net: (*netParams)(net),
flags: walletFlags{
useEncryption: true,
watchingOnly: false,
},
createDate: time.Now().Unix(),
highestUsed: rootKeyChainIdx,
kdfParams: *kdfp,
recent: recentBlocks{
lastHeight: createdAt.Height,
hashes: []*chainhash.Hash{
createdAt.Hash,
},
},
addrMap: make(map[addressKey]walletAddress),
chainIdxMap: make(map[int64]btcutil.Address),
lastChainIdx: rootKeyChainIdx,
missingKeysStart: rootKeyChainIdx,
secret: aeskey,
}
copy(s.desc[:], []byte(desc))
// Create new root address from key and chaincode.
root, err := newRootBtcAddress(s, rootkey, nil, chaincode,
createdAt)
if err != nil {
return nil, err
}
// Verify root address keypairs.
if err := root.verifyKeypairs(); err != nil {
return nil, err
}
if err := root.encrypt(aeskey); err != nil {
return nil, err
}
s.keyGenerator = *root
// Add root address to maps.
rootAddr := s.keyGenerator.Address()
s.addrMap[getAddressKey(rootAddr)] = &s.keyGenerator
s.chainIdxMap[rootKeyChainIdx] = rootAddr
// key store must be returned locked.
if err := s.Lock(); err != nil {
return nil, err
}
return s, nil
} | [
"func",
"New",
"(",
"dir",
"string",
",",
"desc",
"string",
",",
"passphrase",
"[",
"]",
"byte",
",",
"net",
"*",
"chaincfg",
".",
"Params",
",",
"createdAt",
"*",
"BlockStamp",
")",
"(",
"*",
"Store",
",",
"error",
")",
"{",
"// Check sizes of inputs.",
"if",
"len",
"(",
"desc",
")",
">",
"256",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Randomly-generate rootkey and chaincode.",
"rootkey",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"32",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"rand",
".",
"Read",
"(",
"rootkey",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"chaincode",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"32",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"rand",
".",
"Read",
"(",
"chaincode",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Compute AES key and encrypt root address.",
"kdfp",
",",
"err",
":=",
"computeKdfParameters",
"(",
"defaultKdfComputeTime",
",",
"defaultKdfMaxMem",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"aeskey",
":=",
"kdf",
"(",
"passphrase",
",",
"kdfp",
")",
"\n\n",
"// Create and fill key store.",
"s",
":=",
"&",
"Store",
"{",
"path",
":",
"filepath",
".",
"Join",
"(",
"dir",
",",
"Filename",
")",
",",
"dir",
":",
"dir",
",",
"file",
":",
"Filename",
",",
"vers",
":",
"VersCurrent",
",",
"net",
":",
"(",
"*",
"netParams",
")",
"(",
"net",
")",
",",
"flags",
":",
"walletFlags",
"{",
"useEncryption",
":",
"true",
",",
"watchingOnly",
":",
"false",
",",
"}",
",",
"createDate",
":",
"time",
".",
"Now",
"(",
")",
".",
"Unix",
"(",
")",
",",
"highestUsed",
":",
"rootKeyChainIdx",
",",
"kdfParams",
":",
"*",
"kdfp",
",",
"recent",
":",
"recentBlocks",
"{",
"lastHeight",
":",
"createdAt",
".",
"Height",
",",
"hashes",
":",
"[",
"]",
"*",
"chainhash",
".",
"Hash",
"{",
"createdAt",
".",
"Hash",
",",
"}",
",",
"}",
",",
"addrMap",
":",
"make",
"(",
"map",
"[",
"addressKey",
"]",
"walletAddress",
")",
",",
"chainIdxMap",
":",
"make",
"(",
"map",
"[",
"int64",
"]",
"btcutil",
".",
"Address",
")",
",",
"lastChainIdx",
":",
"rootKeyChainIdx",
",",
"missingKeysStart",
":",
"rootKeyChainIdx",
",",
"secret",
":",
"aeskey",
",",
"}",
"\n",
"copy",
"(",
"s",
".",
"desc",
"[",
":",
"]",
",",
"[",
"]",
"byte",
"(",
"desc",
")",
")",
"\n\n",
"// Create new root address from key and chaincode.",
"root",
",",
"err",
":=",
"newRootBtcAddress",
"(",
"s",
",",
"rootkey",
",",
"nil",
",",
"chaincode",
",",
"createdAt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Verify root address keypairs.",
"if",
"err",
":=",
"root",
".",
"verifyKeypairs",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"root",
".",
"encrypt",
"(",
"aeskey",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"s",
".",
"keyGenerator",
"=",
"*",
"root",
"\n\n",
"// Add root address to maps.",
"rootAddr",
":=",
"s",
".",
"keyGenerator",
".",
"Address",
"(",
")",
"\n",
"s",
".",
"addrMap",
"[",
"getAddressKey",
"(",
"rootAddr",
")",
"]",
"=",
"&",
"s",
".",
"keyGenerator",
"\n",
"s",
".",
"chainIdxMap",
"[",
"rootKeyChainIdx",
"]",
"=",
"rootAddr",
"\n\n",
"// key store must be returned locked.",
"if",
"err",
":=",
"s",
".",
"Lock",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"s",
",",
"nil",
"\n",
"}"
] | // New creates and initializes a new Store. name's and desc's byte length
// must not exceed 32 and 256 bytes, respectively. All address private keys
// are encrypted with passphrase. The key store is returned locked. | [
"New",
"creates",
"and",
"initializes",
"a",
"new",
"Store",
".",
"name",
"s",
"and",
"desc",
"s",
"byte",
"length",
"must",
"not",
"exceed",
"32",
"and",
"256",
"bytes",
"respectively",
".",
"All",
"address",
"private",
"keys",
"are",
"encrypted",
"with",
"passphrase",
".",
"The",
"key",
"store",
"is",
"returned",
"locked",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L552-L634 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | WriteTo | func (s *Store) WriteTo(w io.Writer) (n int64, err error) {
s.mtx.RLock()
defer s.mtx.RUnlock()
return s.writeTo(w)
} | go | func (s *Store) WriteTo(w io.Writer) (n int64, err error) {
s.mtx.RLock()
defer s.mtx.RUnlock()
return s.writeTo(w)
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"WriteTo",
"(",
"w",
"io",
".",
"Writer",
")",
"(",
"n",
"int64",
",",
"err",
"error",
")",
"{",
"s",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n\n",
"return",
"s",
".",
"writeTo",
"(",
"w",
")",
"\n",
"}"
] | // WriteTo serializes a key store and writes it to a io.Writer,
// returning the number of bytes written and any errors encountered. | [
"WriteTo",
"serializes",
"a",
"key",
"store",
"and",
"writes",
"it",
"to",
"a",
"io",
".",
"Writer",
"returning",
"the",
"number",
"of",
"bytes",
"written",
"and",
"any",
"errors",
"encountered",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L742-L747 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | Unlock | func (s *Store) Unlock(passphrase []byte) error {
s.mtx.Lock()
defer s.mtx.Unlock()
if s.flags.watchingOnly {
return ErrWatchingOnly
}
// Derive key from KDF parameters and passphrase.
key := kdf(passphrase, &s.kdfParams)
// Unlock root address with derived key.
if _, err := s.keyGenerator.unlock(key); err != nil {
return err
}
// If unlock was successful, save the passphrase and aes key.
s.passphrase = passphrase
s.secret = key
return s.createMissingPrivateKeys()
} | go | func (s *Store) Unlock(passphrase []byte) error {
s.mtx.Lock()
defer s.mtx.Unlock()
if s.flags.watchingOnly {
return ErrWatchingOnly
}
// Derive key from KDF parameters and passphrase.
key := kdf(passphrase, &s.kdfParams)
// Unlock root address with derived key.
if _, err := s.keyGenerator.unlock(key); err != nil {
return err
}
// If unlock was successful, save the passphrase and aes key.
s.passphrase = passphrase
s.secret = key
return s.createMissingPrivateKeys()
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"Unlock",
"(",
"passphrase",
"[",
"]",
"byte",
")",
"error",
"{",
"s",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"s",
".",
"flags",
".",
"watchingOnly",
"{",
"return",
"ErrWatchingOnly",
"\n",
"}",
"\n\n",
"// Derive key from KDF parameters and passphrase.",
"key",
":=",
"kdf",
"(",
"passphrase",
",",
"&",
"s",
".",
"kdfParams",
")",
"\n\n",
"// Unlock root address with derived key.",
"if",
"_",
",",
"err",
":=",
"s",
".",
"keyGenerator",
".",
"unlock",
"(",
"key",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// If unlock was successful, save the passphrase and aes key.",
"s",
".",
"passphrase",
"=",
"passphrase",
"\n",
"s",
".",
"secret",
"=",
"key",
"\n\n",
"return",
"s",
".",
"createMissingPrivateKeys",
"(",
")",
"\n",
"}"
] | // Unlock derives an AES key from passphrase and key store's KDF
// parameters and unlocks the root key of the key store. If
// the unlock was successful, the key store's secret key is saved,
// allowing the decryption of any encrypted private key. Any
// addresses created while the key store was locked without private
// keys are created at this time. | [
"Unlock",
"derives",
"an",
"AES",
"key",
"from",
"passphrase",
"and",
"key",
"store",
"s",
"KDF",
"parameters",
"and",
"unlocks",
"the",
"root",
"key",
"of",
"the",
"key",
"store",
".",
"If",
"the",
"unlock",
"was",
"successful",
"the",
"key",
"store",
"s",
"secret",
"key",
"is",
"saved",
"allowing",
"the",
"decryption",
"of",
"any",
"encrypted",
"private",
"key",
".",
"Any",
"addresses",
"created",
"while",
"the",
"key",
"store",
"was",
"locked",
"without",
"private",
"keys",
"are",
"created",
"at",
"this",
"time",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L893-L914 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | Lock | func (s *Store) Lock() (err error) {
s.mtx.Lock()
defer s.mtx.Unlock()
if s.flags.watchingOnly {
return ErrWatchingOnly
}
// Remove clear text passphrase from key store.
if s.isLocked() {
err = ErrLocked
} else {
zero(s.passphrase)
s.passphrase = nil
zero(s.secret)
s.secret = nil
}
// Remove clear text private keys from all address entries.
for _, addr := range s.addrMap {
if baddr, ok := addr.(*btcAddress); ok {
_ = baddr.lock()
}
}
return err
} | go | func (s *Store) Lock() (err error) {
s.mtx.Lock()
defer s.mtx.Unlock()
if s.flags.watchingOnly {
return ErrWatchingOnly
}
// Remove clear text passphrase from key store.
if s.isLocked() {
err = ErrLocked
} else {
zero(s.passphrase)
s.passphrase = nil
zero(s.secret)
s.secret = nil
}
// Remove clear text private keys from all address entries.
for _, addr := range s.addrMap {
if baddr, ok := addr.(*btcAddress); ok {
_ = baddr.lock()
}
}
return err
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"Lock",
"(",
")",
"(",
"err",
"error",
")",
"{",
"s",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"s",
".",
"flags",
".",
"watchingOnly",
"{",
"return",
"ErrWatchingOnly",
"\n",
"}",
"\n\n",
"// Remove clear text passphrase from key store.",
"if",
"s",
".",
"isLocked",
"(",
")",
"{",
"err",
"=",
"ErrLocked",
"\n",
"}",
"else",
"{",
"zero",
"(",
"s",
".",
"passphrase",
")",
"\n",
"s",
".",
"passphrase",
"=",
"nil",
"\n",
"zero",
"(",
"s",
".",
"secret",
")",
"\n",
"s",
".",
"secret",
"=",
"nil",
"\n",
"}",
"\n\n",
"// Remove clear text private keys from all address entries.",
"for",
"_",
",",
"addr",
":=",
"range",
"s",
".",
"addrMap",
"{",
"if",
"baddr",
",",
"ok",
":=",
"addr",
".",
"(",
"*",
"btcAddress",
")",
";",
"ok",
"{",
"_",
"=",
"baddr",
".",
"lock",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"err",
"\n",
"}"
] | // Lock performs a best try effort to remove and zero all secret keys
// associated with the key store. | [
"Lock",
"performs",
"a",
"best",
"try",
"effort",
"to",
"remove",
"and",
"zero",
"all",
"secret",
"keys",
"associated",
"with",
"the",
"key",
"store",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L918-L944 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | ChangePassphrase | func (s *Store) ChangePassphrase(new []byte) error {
s.mtx.Lock()
defer s.mtx.Unlock()
if s.flags.watchingOnly {
return ErrWatchingOnly
}
if s.isLocked() {
return ErrLocked
}
oldkey := s.secret
newkey := kdf(new, &s.kdfParams)
for _, wa := range s.addrMap {
// Only btcAddresses curently have private keys.
a, ok := wa.(*btcAddress)
if !ok {
continue
}
if err := a.changeEncryptionKey(oldkey, newkey); err != nil {
return err
}
}
// zero old secrets.
zero(s.passphrase)
zero(s.secret)
// Save new secrets.
s.passphrase = new
s.secret = newkey
return nil
} | go | func (s *Store) ChangePassphrase(new []byte) error {
s.mtx.Lock()
defer s.mtx.Unlock()
if s.flags.watchingOnly {
return ErrWatchingOnly
}
if s.isLocked() {
return ErrLocked
}
oldkey := s.secret
newkey := kdf(new, &s.kdfParams)
for _, wa := range s.addrMap {
// Only btcAddresses curently have private keys.
a, ok := wa.(*btcAddress)
if !ok {
continue
}
if err := a.changeEncryptionKey(oldkey, newkey); err != nil {
return err
}
}
// zero old secrets.
zero(s.passphrase)
zero(s.secret)
// Save new secrets.
s.passphrase = new
s.secret = newkey
return nil
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"ChangePassphrase",
"(",
"new",
"[",
"]",
"byte",
")",
"error",
"{",
"s",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"s",
".",
"flags",
".",
"watchingOnly",
"{",
"return",
"ErrWatchingOnly",
"\n",
"}",
"\n\n",
"if",
"s",
".",
"isLocked",
"(",
")",
"{",
"return",
"ErrLocked",
"\n",
"}",
"\n\n",
"oldkey",
":=",
"s",
".",
"secret",
"\n",
"newkey",
":=",
"kdf",
"(",
"new",
",",
"&",
"s",
".",
"kdfParams",
")",
"\n\n",
"for",
"_",
",",
"wa",
":=",
"range",
"s",
".",
"addrMap",
"{",
"// Only btcAddresses curently have private keys.",
"a",
",",
"ok",
":=",
"wa",
".",
"(",
"*",
"btcAddress",
")",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"a",
".",
"changeEncryptionKey",
"(",
"oldkey",
",",
"newkey",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// zero old secrets.",
"zero",
"(",
"s",
".",
"passphrase",
")",
"\n",
"zero",
"(",
"s",
".",
"secret",
")",
"\n\n",
"// Save new secrets.",
"s",
".",
"passphrase",
"=",
"new",
"\n",
"s",
".",
"secret",
"=",
"newkey",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // ChangePassphrase creates a new AES key from a new passphrase and
// re-encrypts all encrypted private keys with the new key. | [
"ChangePassphrase",
"creates",
"a",
"new",
"AES",
"key",
"from",
"a",
"new",
"passphrase",
"and",
"re",
"-",
"encrypts",
"all",
"encrypted",
"private",
"keys",
"with",
"the",
"new",
"key",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L948-L984 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | NextChainedAddress | func (s *Store) NextChainedAddress(bs *BlockStamp) (btcutil.Address, error) {
s.mtx.Lock()
defer s.mtx.Unlock()
return s.nextChainedAddress(bs)
} | go | func (s *Store) NextChainedAddress(bs *BlockStamp) (btcutil.Address, error) {
s.mtx.Lock()
defer s.mtx.Unlock()
return s.nextChainedAddress(bs)
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"NextChainedAddress",
"(",
"bs",
"*",
"BlockStamp",
")",
"(",
"btcutil",
".",
"Address",
",",
"error",
")",
"{",
"s",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"s",
".",
"nextChainedAddress",
"(",
"bs",
")",
"\n",
"}"
] | // NextChainedAddress attempts to get the next chained address. If the key
// store is unlocked, the next pubkey and private key of the address chain are
// derived. If the key store is locke, only the next pubkey is derived, and
// the private key will be generated on next unlock. | [
"NextChainedAddress",
"attempts",
"to",
"get",
"the",
"next",
"chained",
"address",
".",
"If",
"the",
"key",
"store",
"is",
"unlocked",
"the",
"next",
"pubkey",
"and",
"private",
"key",
"of",
"the",
"address",
"chain",
"are",
"derived",
".",
"If",
"the",
"key",
"store",
"is",
"locke",
"only",
"the",
"next",
"pubkey",
"is",
"derived",
"and",
"the",
"private",
"key",
"will",
"be",
"generated",
"on",
"next",
"unlock",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L1009-L1014 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | ChangeAddress | func (s *Store) ChangeAddress(bs *BlockStamp) (btcutil.Address, error) {
s.mtx.Lock()
defer s.mtx.Unlock()
addr, err := s.nextChainedBtcAddress(bs)
if err != nil {
return nil, err
}
addr.flags.change = true
// Create and return payment address for address hash.
return addr.Address(), nil
} | go | func (s *Store) ChangeAddress(bs *BlockStamp) (btcutil.Address, error) {
s.mtx.Lock()
defer s.mtx.Unlock()
addr, err := s.nextChainedBtcAddress(bs)
if err != nil {
return nil, err
}
addr.flags.change = true
// Create and return payment address for address hash.
return addr.Address(), nil
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"ChangeAddress",
"(",
"bs",
"*",
"BlockStamp",
")",
"(",
"btcutil",
".",
"Address",
",",
"error",
")",
"{",
"s",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"addr",
",",
"err",
":=",
"s",
".",
"nextChainedBtcAddress",
"(",
"bs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"addr",
".",
"flags",
".",
"change",
"=",
"true",
"\n\n",
"// Create and return payment address for address hash.",
"return",
"addr",
".",
"Address",
"(",
")",
",",
"nil",
"\n",
"}"
] | // ChangeAddress returns the next chained address from the key store, marking
// the address for a change transaction output. | [
"ChangeAddress",
"returns",
"the",
"next",
"chained",
"address",
"from",
"the",
"key",
"store",
"marking",
"the",
"address",
"for",
"a",
"change",
"transaction",
"output",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L1026-L1039 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | LastChainedAddress | func (s *Store) LastChainedAddress() btcutil.Address {
s.mtx.RLock()
defer s.mtx.RUnlock()
return s.chainIdxMap[s.highestUsed]
} | go | func (s *Store) LastChainedAddress() btcutil.Address {
s.mtx.RLock()
defer s.mtx.RUnlock()
return s.chainIdxMap[s.highestUsed]
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"LastChainedAddress",
"(",
")",
"btcutil",
".",
"Address",
"{",
"s",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n\n",
"return",
"s",
".",
"chainIdxMap",
"[",
"s",
".",
"highestUsed",
"]",
"\n",
"}"
] | // LastChainedAddress returns the most recently requested chained
// address from calling NextChainedAddress, or the root address if
// no chained addresses have been requested. | [
"LastChainedAddress",
"returns",
"the",
"most",
"recently",
"requested",
"chained",
"address",
"from",
"calling",
"NextChainedAddress",
"or",
"the",
"root",
"address",
"if",
"no",
"chained",
"addresses",
"have",
"been",
"requested",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L1083-L1088 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | extendUnlocked | func (s *Store) extendUnlocked(bs *BlockStamp) error {
// Get last chained address. New chained addresses will be
// chained off of this address's chaincode and private key.
a := s.chainIdxMap[s.lastChainIdx]
waddr, ok := s.addrMap[getAddressKey(a)]
if !ok {
return errors.New("expected last chained address not found")
}
if s.isLocked() {
return ErrLocked
}
lastAddr, ok := waddr.(*btcAddress)
if !ok {
return errors.New("found non-pubkey chained address")
}
privkey, err := lastAddr.unlock(s.secret)
if err != nil {
return err
}
cc := lastAddr.chaincode[:]
privkey, err = chainedPrivKey(privkey, lastAddr.pubKeyBytes(), cc)
if err != nil {
return err
}
newAddr, err := newBtcAddress(s, privkey, nil, bs, true)
if err != nil {
return err
}
if err := newAddr.verifyKeypairs(); err != nil {
return err
}
if err = newAddr.encrypt(s.secret); err != nil {
return err
}
a = newAddr.Address()
s.addrMap[getAddressKey(a)] = newAddr
newAddr.chainIndex = lastAddr.chainIndex + 1
s.chainIdxMap[newAddr.chainIndex] = a
s.lastChainIdx++
copy(newAddr.chaincode[:], cc)
return nil
} | go | func (s *Store) extendUnlocked(bs *BlockStamp) error {
// Get last chained address. New chained addresses will be
// chained off of this address's chaincode and private key.
a := s.chainIdxMap[s.lastChainIdx]
waddr, ok := s.addrMap[getAddressKey(a)]
if !ok {
return errors.New("expected last chained address not found")
}
if s.isLocked() {
return ErrLocked
}
lastAddr, ok := waddr.(*btcAddress)
if !ok {
return errors.New("found non-pubkey chained address")
}
privkey, err := lastAddr.unlock(s.secret)
if err != nil {
return err
}
cc := lastAddr.chaincode[:]
privkey, err = chainedPrivKey(privkey, lastAddr.pubKeyBytes(), cc)
if err != nil {
return err
}
newAddr, err := newBtcAddress(s, privkey, nil, bs, true)
if err != nil {
return err
}
if err := newAddr.verifyKeypairs(); err != nil {
return err
}
if err = newAddr.encrypt(s.secret); err != nil {
return err
}
a = newAddr.Address()
s.addrMap[getAddressKey(a)] = newAddr
newAddr.chainIndex = lastAddr.chainIndex + 1
s.chainIdxMap[newAddr.chainIndex] = a
s.lastChainIdx++
copy(newAddr.chaincode[:], cc)
return nil
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"extendUnlocked",
"(",
"bs",
"*",
"BlockStamp",
")",
"error",
"{",
"// Get last chained address. New chained addresses will be",
"// chained off of this address's chaincode and private key.",
"a",
":=",
"s",
".",
"chainIdxMap",
"[",
"s",
".",
"lastChainIdx",
"]",
"\n",
"waddr",
",",
"ok",
":=",
"s",
".",
"addrMap",
"[",
"getAddressKey",
"(",
"a",
")",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"s",
".",
"isLocked",
"(",
")",
"{",
"return",
"ErrLocked",
"\n",
"}",
"\n\n",
"lastAddr",
",",
"ok",
":=",
"waddr",
".",
"(",
"*",
"btcAddress",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"privkey",
",",
"err",
":=",
"lastAddr",
".",
"unlock",
"(",
"s",
".",
"secret",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"cc",
":=",
"lastAddr",
".",
"chaincode",
"[",
":",
"]",
"\n\n",
"privkey",
",",
"err",
"=",
"chainedPrivKey",
"(",
"privkey",
",",
"lastAddr",
".",
"pubKeyBytes",
"(",
")",
",",
"cc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"newAddr",
",",
"err",
":=",
"newBtcAddress",
"(",
"s",
",",
"privkey",
",",
"nil",
",",
"bs",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"newAddr",
".",
"verifyKeypairs",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
"=",
"newAddr",
".",
"encrypt",
"(",
"s",
".",
"secret",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"a",
"=",
"newAddr",
".",
"Address",
"(",
")",
"\n",
"s",
".",
"addrMap",
"[",
"getAddressKey",
"(",
"a",
")",
"]",
"=",
"newAddr",
"\n",
"newAddr",
".",
"chainIndex",
"=",
"lastAddr",
".",
"chainIndex",
"+",
"1",
"\n",
"s",
".",
"chainIdxMap",
"[",
"newAddr",
".",
"chainIndex",
"]",
"=",
"a",
"\n",
"s",
".",
"lastChainIdx",
"++",
"\n",
"copy",
"(",
"newAddr",
".",
"chaincode",
"[",
":",
"]",
",",
"cc",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // extendUnlocked grows address chain for an unlocked keystore. | [
"extendUnlocked",
"grows",
"address",
"chain",
"for",
"an",
"unlocked",
"keystore",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L1091-L1137 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | Net | func (s *Store) Net() *chaincfg.Params {
s.mtx.RLock()
defer s.mtx.RUnlock()
return s.netParams()
} | go | func (s *Store) Net() *chaincfg.Params {
s.mtx.RLock()
defer s.mtx.RUnlock()
return s.netParams()
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"Net",
"(",
")",
"*",
"chaincfg",
".",
"Params",
"{",
"s",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n\n",
"return",
"s",
".",
"netParams",
"(",
")",
"\n",
"}"
] | // Net returns the bitcoin network parameters for this key store. | [
"Net",
"returns",
"the",
"bitcoin",
"network",
"parameters",
"for",
"this",
"key",
"store",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L1260-L1265 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | SetSyncStatus | func (s *Store) SetSyncStatus(a btcutil.Address, ss SyncStatus) error {
s.mtx.Lock()
defer s.mtx.Unlock()
wa, ok := s.addrMap[getAddressKey(a)]
if !ok {
return ErrAddressNotFound
}
wa.setSyncStatus(ss)
return nil
} | go | func (s *Store) SetSyncStatus(a btcutil.Address, ss SyncStatus) error {
s.mtx.Lock()
defer s.mtx.Unlock()
wa, ok := s.addrMap[getAddressKey(a)]
if !ok {
return ErrAddressNotFound
}
wa.setSyncStatus(ss)
return nil
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"SetSyncStatus",
"(",
"a",
"btcutil",
".",
"Address",
",",
"ss",
"SyncStatus",
")",
"error",
"{",
"s",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"wa",
",",
"ok",
":=",
"s",
".",
"addrMap",
"[",
"getAddressKey",
"(",
"a",
")",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"ErrAddressNotFound",
"\n",
"}",
"\n",
"wa",
".",
"setSyncStatus",
"(",
"ss",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // SetSyncStatus sets the sync status for a single key store address. This
// may error if the address is not found in the key store.
//
// When marking an address as unsynced, only the type Unsynced matters.
// The value is ignored. | [
"SetSyncStatus",
"sets",
"the",
"sync",
"status",
"for",
"a",
"single",
"key",
"store",
"address",
".",
"This",
"may",
"error",
"if",
"the",
"address",
"is",
"not",
"found",
"in",
"the",
"key",
"store",
".",
"When",
"marking",
"an",
"address",
"as",
"unsynced",
"only",
"the",
"type",
"Unsynced",
"matters",
".",
"The",
"value",
"is",
"ignored",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L1276-L1286 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | SetSyncedWith | func (s *Store) SetSyncedWith(bs *BlockStamp) {
s.mtx.Lock()
defer s.mtx.Unlock()
if bs == nil {
s.recent.hashes = s.recent.hashes[:0]
s.recent.lastHeight = s.keyGenerator.firstBlock
s.keyGenerator.setSyncStatus(Unsynced(s.keyGenerator.firstBlock))
return
}
// Check if we're trying to rollback the last seen history.
// If so, and this bs is already saved, remove anything
// after and return. Otherwire, remove previous hashes.
if bs.Height < s.recent.lastHeight {
maybeIdx := len(s.recent.hashes) - 1 - int(s.recent.lastHeight-bs.Height)
if maybeIdx >= 0 && maybeIdx < len(s.recent.hashes) &&
*s.recent.hashes[maybeIdx] == *bs.Hash {
s.recent.lastHeight = bs.Height
// subslice out the removed hashes.
s.recent.hashes = s.recent.hashes[:maybeIdx]
return
}
s.recent.hashes = nil
}
if bs.Height != s.recent.lastHeight+1 {
s.recent.hashes = nil
}
s.recent.lastHeight = bs.Height
if len(s.recent.hashes) == 20 {
// Make room for the most recent hash.
copy(s.recent.hashes, s.recent.hashes[1:])
// Set new block in the last position.
s.recent.hashes[19] = bs.Hash
} else {
s.recent.hashes = append(s.recent.hashes, bs.Hash)
}
} | go | func (s *Store) SetSyncedWith(bs *BlockStamp) {
s.mtx.Lock()
defer s.mtx.Unlock()
if bs == nil {
s.recent.hashes = s.recent.hashes[:0]
s.recent.lastHeight = s.keyGenerator.firstBlock
s.keyGenerator.setSyncStatus(Unsynced(s.keyGenerator.firstBlock))
return
}
// Check if we're trying to rollback the last seen history.
// If so, and this bs is already saved, remove anything
// after and return. Otherwire, remove previous hashes.
if bs.Height < s.recent.lastHeight {
maybeIdx := len(s.recent.hashes) - 1 - int(s.recent.lastHeight-bs.Height)
if maybeIdx >= 0 && maybeIdx < len(s.recent.hashes) &&
*s.recent.hashes[maybeIdx] == *bs.Hash {
s.recent.lastHeight = bs.Height
// subslice out the removed hashes.
s.recent.hashes = s.recent.hashes[:maybeIdx]
return
}
s.recent.hashes = nil
}
if bs.Height != s.recent.lastHeight+1 {
s.recent.hashes = nil
}
s.recent.lastHeight = bs.Height
if len(s.recent.hashes) == 20 {
// Make room for the most recent hash.
copy(s.recent.hashes, s.recent.hashes[1:])
// Set new block in the last position.
s.recent.hashes[19] = bs.Hash
} else {
s.recent.hashes = append(s.recent.hashes, bs.Hash)
}
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"SetSyncedWith",
"(",
"bs",
"*",
"BlockStamp",
")",
"{",
"s",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"bs",
"==",
"nil",
"{",
"s",
".",
"recent",
".",
"hashes",
"=",
"s",
".",
"recent",
".",
"hashes",
"[",
":",
"0",
"]",
"\n",
"s",
".",
"recent",
".",
"lastHeight",
"=",
"s",
".",
"keyGenerator",
".",
"firstBlock",
"\n",
"s",
".",
"keyGenerator",
".",
"setSyncStatus",
"(",
"Unsynced",
"(",
"s",
".",
"keyGenerator",
".",
"firstBlock",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Check if we're trying to rollback the last seen history.",
"// If so, and this bs is already saved, remove anything",
"// after and return. Otherwire, remove previous hashes.",
"if",
"bs",
".",
"Height",
"<",
"s",
".",
"recent",
".",
"lastHeight",
"{",
"maybeIdx",
":=",
"len",
"(",
"s",
".",
"recent",
".",
"hashes",
")",
"-",
"1",
"-",
"int",
"(",
"s",
".",
"recent",
".",
"lastHeight",
"-",
"bs",
".",
"Height",
")",
"\n",
"if",
"maybeIdx",
">=",
"0",
"&&",
"maybeIdx",
"<",
"len",
"(",
"s",
".",
"recent",
".",
"hashes",
")",
"&&",
"*",
"s",
".",
"recent",
".",
"hashes",
"[",
"maybeIdx",
"]",
"==",
"*",
"bs",
".",
"Hash",
"{",
"s",
".",
"recent",
".",
"lastHeight",
"=",
"bs",
".",
"Height",
"\n",
"// subslice out the removed hashes.",
"s",
".",
"recent",
".",
"hashes",
"=",
"s",
".",
"recent",
".",
"hashes",
"[",
":",
"maybeIdx",
"]",
"\n",
"return",
"\n",
"}",
"\n",
"s",
".",
"recent",
".",
"hashes",
"=",
"nil",
"\n",
"}",
"\n\n",
"if",
"bs",
".",
"Height",
"!=",
"s",
".",
"recent",
".",
"lastHeight",
"+",
"1",
"{",
"s",
".",
"recent",
".",
"hashes",
"=",
"nil",
"\n",
"}",
"\n\n",
"s",
".",
"recent",
".",
"lastHeight",
"=",
"bs",
".",
"Height",
"\n\n",
"if",
"len",
"(",
"s",
".",
"recent",
".",
"hashes",
")",
"==",
"20",
"{",
"// Make room for the most recent hash.",
"copy",
"(",
"s",
".",
"recent",
".",
"hashes",
",",
"s",
".",
"recent",
".",
"hashes",
"[",
"1",
":",
"]",
")",
"\n\n",
"// Set new block in the last position.",
"s",
".",
"recent",
".",
"hashes",
"[",
"19",
"]",
"=",
"bs",
".",
"Hash",
"\n",
"}",
"else",
"{",
"s",
".",
"recent",
".",
"hashes",
"=",
"append",
"(",
"s",
".",
"recent",
".",
"hashes",
",",
"bs",
".",
"Hash",
")",
"\n",
"}",
"\n",
"}"
] | // SetSyncedWith marks already synced addresses in the key store to be in
// sync with the recently-seen block described by the blockstamp.
// Unsynced addresses are unaffected by this method and must be marked
// as in sync with MarkAddressSynced or MarkAllSynced to be considered
// in sync with bs.
//
// If bs is nil, the entire key store is marked unsynced. | [
"SetSyncedWith",
"marks",
"already",
"synced",
"addresses",
"in",
"the",
"key",
"store",
"to",
"be",
"in",
"sync",
"with",
"the",
"recently",
"-",
"seen",
"block",
"described",
"by",
"the",
"blockstamp",
".",
"Unsynced",
"addresses",
"are",
"unaffected",
"by",
"this",
"method",
"and",
"must",
"be",
"marked",
"as",
"in",
"sync",
"with",
"MarkAddressSynced",
"or",
"MarkAllSynced",
"to",
"be",
"considered",
"in",
"sync",
"with",
"bs",
".",
"If",
"bs",
"is",
"nil",
"the",
"entire",
"key",
"store",
"is",
"marked",
"unsynced",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L1295-L1337 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | NewIterateRecentBlocks | func (s *Store) NewIterateRecentBlocks() *BlockIterator {
s.mtx.RLock()
defer s.mtx.RUnlock()
return s.recent.iter(s)
} | go | func (s *Store) NewIterateRecentBlocks() *BlockIterator {
s.mtx.RLock()
defer s.mtx.RUnlock()
return s.recent.iter(s)
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"NewIterateRecentBlocks",
"(",
")",
"*",
"BlockIterator",
"{",
"s",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n\n",
"return",
"s",
".",
"recent",
".",
"iter",
"(",
"s",
")",
"\n",
"}"
] | // NewIterateRecentBlocks returns an iterator for recently-seen blocks.
// The iterator starts at the most recently-added block, and Prev should
// be used to access earlier blocks. | [
"NewIterateRecentBlocks",
"returns",
"an",
"iterator",
"for",
"recently",
"-",
"seen",
"blocks",
".",
"The",
"iterator",
"starts",
"at",
"the",
"most",
"recently",
"-",
"added",
"block",
"and",
"Prev",
"should",
"be",
"used",
"to",
"access",
"earlier",
"blocks",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L1385-L1390 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | ImportPrivateKey | func (s *Store) ImportPrivateKey(wif *btcutil.WIF, bs *BlockStamp) (btcutil.Address, error) {
s.mtx.Lock()
defer s.mtx.Unlock()
if s.flags.watchingOnly {
return nil, ErrWatchingOnly
}
// First, must check that the key being imported will not result
// in a duplicate address.
pkh := btcutil.Hash160(wif.SerializePubKey())
if _, ok := s.addrMap[addressKey(pkh)]; ok {
return nil, ErrDuplicate
}
// The key store must be unlocked to encrypt the imported private key.
if s.isLocked() {
return nil, ErrLocked
}
// Create new address with this private key.
privKey := wif.PrivKey.Serialize()
btcaddr, err := newBtcAddress(s, privKey, nil, bs, wif.CompressPubKey)
if err != nil {
return nil, err
}
btcaddr.chainIndex = importedKeyChainIdx
// Mark as unsynced if import height is below currently-synced
// height.
if len(s.recent.hashes) != 0 && bs.Height < s.recent.lastHeight {
btcaddr.flags.unsynced = true
}
// Encrypt imported address with the derived AES key.
if err = btcaddr.encrypt(s.secret); err != nil {
return nil, err
}
addr := btcaddr.Address()
// Add address to key store's bookkeeping structures. Adding to
// the map will result in the imported address being serialized
// on the next WriteTo call.
s.addrMap[getAddressKey(addr)] = btcaddr
s.importedAddrs = append(s.importedAddrs, btcaddr)
// Create and return address.
return addr, nil
} | go | func (s *Store) ImportPrivateKey(wif *btcutil.WIF, bs *BlockStamp) (btcutil.Address, error) {
s.mtx.Lock()
defer s.mtx.Unlock()
if s.flags.watchingOnly {
return nil, ErrWatchingOnly
}
// First, must check that the key being imported will not result
// in a duplicate address.
pkh := btcutil.Hash160(wif.SerializePubKey())
if _, ok := s.addrMap[addressKey(pkh)]; ok {
return nil, ErrDuplicate
}
// The key store must be unlocked to encrypt the imported private key.
if s.isLocked() {
return nil, ErrLocked
}
// Create new address with this private key.
privKey := wif.PrivKey.Serialize()
btcaddr, err := newBtcAddress(s, privKey, nil, bs, wif.CompressPubKey)
if err != nil {
return nil, err
}
btcaddr.chainIndex = importedKeyChainIdx
// Mark as unsynced if import height is below currently-synced
// height.
if len(s.recent.hashes) != 0 && bs.Height < s.recent.lastHeight {
btcaddr.flags.unsynced = true
}
// Encrypt imported address with the derived AES key.
if err = btcaddr.encrypt(s.secret); err != nil {
return nil, err
}
addr := btcaddr.Address()
// Add address to key store's bookkeeping structures. Adding to
// the map will result in the imported address being serialized
// on the next WriteTo call.
s.addrMap[getAddressKey(addr)] = btcaddr
s.importedAddrs = append(s.importedAddrs, btcaddr)
// Create and return address.
return addr, nil
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"ImportPrivateKey",
"(",
"wif",
"*",
"btcutil",
".",
"WIF",
",",
"bs",
"*",
"BlockStamp",
")",
"(",
"btcutil",
".",
"Address",
",",
"error",
")",
"{",
"s",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"s",
".",
"flags",
".",
"watchingOnly",
"{",
"return",
"nil",
",",
"ErrWatchingOnly",
"\n",
"}",
"\n\n",
"// First, must check that the key being imported will not result",
"// in a duplicate address.",
"pkh",
":=",
"btcutil",
".",
"Hash160",
"(",
"wif",
".",
"SerializePubKey",
"(",
")",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"s",
".",
"addrMap",
"[",
"addressKey",
"(",
"pkh",
")",
"]",
";",
"ok",
"{",
"return",
"nil",
",",
"ErrDuplicate",
"\n",
"}",
"\n\n",
"// The key store must be unlocked to encrypt the imported private key.",
"if",
"s",
".",
"isLocked",
"(",
")",
"{",
"return",
"nil",
",",
"ErrLocked",
"\n",
"}",
"\n\n",
"// Create new address with this private key.",
"privKey",
":=",
"wif",
".",
"PrivKey",
".",
"Serialize",
"(",
")",
"\n",
"btcaddr",
",",
"err",
":=",
"newBtcAddress",
"(",
"s",
",",
"privKey",
",",
"nil",
",",
"bs",
",",
"wif",
".",
"CompressPubKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"btcaddr",
".",
"chainIndex",
"=",
"importedKeyChainIdx",
"\n\n",
"// Mark as unsynced if import height is below currently-synced",
"// height.",
"if",
"len",
"(",
"s",
".",
"recent",
".",
"hashes",
")",
"!=",
"0",
"&&",
"bs",
".",
"Height",
"<",
"s",
".",
"recent",
".",
"lastHeight",
"{",
"btcaddr",
".",
"flags",
".",
"unsynced",
"=",
"true",
"\n",
"}",
"\n\n",
"// Encrypt imported address with the derived AES key.",
"if",
"err",
"=",
"btcaddr",
".",
"encrypt",
"(",
"s",
".",
"secret",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"addr",
":=",
"btcaddr",
".",
"Address",
"(",
")",
"\n",
"// Add address to key store's bookkeeping structures. Adding to",
"// the map will result in the imported address being serialized",
"// on the next WriteTo call.",
"s",
".",
"addrMap",
"[",
"getAddressKey",
"(",
"addr",
")",
"]",
"=",
"btcaddr",
"\n",
"s",
".",
"importedAddrs",
"=",
"append",
"(",
"s",
".",
"importedAddrs",
",",
"btcaddr",
")",
"\n\n",
"// Create and return address.",
"return",
"addr",
",",
"nil",
"\n",
"}"
] | // ImportPrivateKey imports a WIF private key into the keystore. The imported
// address is created using either a compressed or uncompressed serialized
// public key, depending on the CompressPubKey bool of the WIF. | [
"ImportPrivateKey",
"imports",
"a",
"WIF",
"private",
"key",
"into",
"the",
"keystore",
".",
"The",
"imported",
"address",
"is",
"created",
"using",
"either",
"a",
"compressed",
"or",
"uncompressed",
"serialized",
"public",
"key",
"depending",
"on",
"the",
"CompressPubKey",
"bool",
"of",
"the",
"WIF",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L1395-L1443 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | ImportScript | func (s *Store) ImportScript(script []byte, bs *BlockStamp) (btcutil.Address, error) {
s.mtx.Lock()
defer s.mtx.Unlock()
if s.flags.watchingOnly {
return nil, ErrWatchingOnly
}
if _, ok := s.addrMap[addressKey(btcutil.Hash160(script))]; ok {
return nil, ErrDuplicate
}
// Create new address with this private key.
scriptaddr, err := newScriptAddress(s, script, bs)
if err != nil {
return nil, err
}
// Mark as unsynced if import height is below currently-synced
// height.
if len(s.recent.hashes) != 0 && bs.Height < s.recent.lastHeight {
scriptaddr.flags.unsynced = true
}
// Add address to key store's bookkeeping structures. Adding to
// the map will result in the imported address being serialized
// on the next WriteTo call.
addr := scriptaddr.Address()
s.addrMap[getAddressKey(addr)] = scriptaddr
s.importedAddrs = append(s.importedAddrs, scriptaddr)
// Create and return address.
return addr, nil
} | go | func (s *Store) ImportScript(script []byte, bs *BlockStamp) (btcutil.Address, error) {
s.mtx.Lock()
defer s.mtx.Unlock()
if s.flags.watchingOnly {
return nil, ErrWatchingOnly
}
if _, ok := s.addrMap[addressKey(btcutil.Hash160(script))]; ok {
return nil, ErrDuplicate
}
// Create new address with this private key.
scriptaddr, err := newScriptAddress(s, script, bs)
if err != nil {
return nil, err
}
// Mark as unsynced if import height is below currently-synced
// height.
if len(s.recent.hashes) != 0 && bs.Height < s.recent.lastHeight {
scriptaddr.flags.unsynced = true
}
// Add address to key store's bookkeeping structures. Adding to
// the map will result in the imported address being serialized
// on the next WriteTo call.
addr := scriptaddr.Address()
s.addrMap[getAddressKey(addr)] = scriptaddr
s.importedAddrs = append(s.importedAddrs, scriptaddr)
// Create and return address.
return addr, nil
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"ImportScript",
"(",
"script",
"[",
"]",
"byte",
",",
"bs",
"*",
"BlockStamp",
")",
"(",
"btcutil",
".",
"Address",
",",
"error",
")",
"{",
"s",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"s",
".",
"flags",
".",
"watchingOnly",
"{",
"return",
"nil",
",",
"ErrWatchingOnly",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"ok",
":=",
"s",
".",
"addrMap",
"[",
"addressKey",
"(",
"btcutil",
".",
"Hash160",
"(",
"script",
")",
")",
"]",
";",
"ok",
"{",
"return",
"nil",
",",
"ErrDuplicate",
"\n",
"}",
"\n\n",
"// Create new address with this private key.",
"scriptaddr",
",",
"err",
":=",
"newScriptAddress",
"(",
"s",
",",
"script",
",",
"bs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Mark as unsynced if import height is below currently-synced",
"// height.",
"if",
"len",
"(",
"s",
".",
"recent",
".",
"hashes",
")",
"!=",
"0",
"&&",
"bs",
".",
"Height",
"<",
"s",
".",
"recent",
".",
"lastHeight",
"{",
"scriptaddr",
".",
"flags",
".",
"unsynced",
"=",
"true",
"\n",
"}",
"\n\n",
"// Add address to key store's bookkeeping structures. Adding to",
"// the map will result in the imported address being serialized",
"// on the next WriteTo call.",
"addr",
":=",
"scriptaddr",
".",
"Address",
"(",
")",
"\n",
"s",
".",
"addrMap",
"[",
"getAddressKey",
"(",
"addr",
")",
"]",
"=",
"scriptaddr",
"\n",
"s",
".",
"importedAddrs",
"=",
"append",
"(",
"s",
".",
"importedAddrs",
",",
"scriptaddr",
")",
"\n\n",
"// Create and return address.",
"return",
"addr",
",",
"nil",
"\n",
"}"
] | // ImportScript creates a new scriptAddress with a user-provided script
// and adds it to the key store. | [
"ImportScript",
"creates",
"a",
"new",
"scriptAddress",
"with",
"a",
"user",
"-",
"provided",
"script",
"and",
"adds",
"it",
"to",
"the",
"key",
"store",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L1447-L1480 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | CreateDate | func (s *Store) CreateDate() int64 {
s.mtx.RLock()
defer s.mtx.RUnlock()
return s.createDate
} | go | func (s *Store) CreateDate() int64 {
s.mtx.RLock()
defer s.mtx.RUnlock()
return s.createDate
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"CreateDate",
"(",
")",
"int64",
"{",
"s",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n\n",
"return",
"s",
".",
"createDate",
"\n",
"}"
] | // CreateDate returns the Unix time of the key store creation time. This
// is used to compare the key store creation time against block headers and
// set a better minimum block height of where to being rescans. | [
"CreateDate",
"returns",
"the",
"Unix",
"time",
"of",
"the",
"key",
"store",
"creation",
"time",
".",
"This",
"is",
"used",
"to",
"compare",
"the",
"key",
"store",
"creation",
"time",
"against",
"block",
"headers",
"and",
"set",
"a",
"better",
"minimum",
"block",
"height",
"of",
"where",
"to",
"being",
"rescans",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L1485-L1490 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | SortedActiveAddresses | func (s *Store) SortedActiveAddresses() []WalletAddress {
s.mtx.RLock()
defer s.mtx.RUnlock()
addrs := make([]WalletAddress, 0,
s.highestUsed+int64(len(s.importedAddrs))+1)
for i := int64(rootKeyChainIdx); i <= s.highestUsed; i++ {
a := s.chainIdxMap[i]
info, ok := s.addrMap[getAddressKey(a)]
if ok {
addrs = append(addrs, info)
}
}
for _, addr := range s.importedAddrs {
addrs = append(addrs, addr)
}
return addrs
} | go | func (s *Store) SortedActiveAddresses() []WalletAddress {
s.mtx.RLock()
defer s.mtx.RUnlock()
addrs := make([]WalletAddress, 0,
s.highestUsed+int64(len(s.importedAddrs))+1)
for i := int64(rootKeyChainIdx); i <= s.highestUsed; i++ {
a := s.chainIdxMap[i]
info, ok := s.addrMap[getAddressKey(a)]
if ok {
addrs = append(addrs, info)
}
}
for _, addr := range s.importedAddrs {
addrs = append(addrs, addr)
}
return addrs
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"SortedActiveAddresses",
"(",
")",
"[",
"]",
"WalletAddress",
"{",
"s",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n\n",
"addrs",
":=",
"make",
"(",
"[",
"]",
"WalletAddress",
",",
"0",
",",
"s",
".",
"highestUsed",
"+",
"int64",
"(",
"len",
"(",
"s",
".",
"importedAddrs",
")",
")",
"+",
"1",
")",
"\n",
"for",
"i",
":=",
"int64",
"(",
"rootKeyChainIdx",
")",
";",
"i",
"<=",
"s",
".",
"highestUsed",
";",
"i",
"++",
"{",
"a",
":=",
"s",
".",
"chainIdxMap",
"[",
"i",
"]",
"\n",
"info",
",",
"ok",
":=",
"s",
".",
"addrMap",
"[",
"getAddressKey",
"(",
"a",
")",
"]",
"\n",
"if",
"ok",
"{",
"addrs",
"=",
"append",
"(",
"addrs",
",",
"info",
")",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"addr",
":=",
"range",
"s",
".",
"importedAddrs",
"{",
"addrs",
"=",
"append",
"(",
"addrs",
",",
"addr",
")",
"\n",
"}",
"\n",
"return",
"addrs",
"\n",
"}"
] | // SortedActiveAddresses returns all key store addresses that have been
// requested to be generated. These do not include unused addresses in
// the key pool. Use this when ordered addresses are needed. Otherwise,
// ActiveAddresses is preferred. | [
"SortedActiveAddresses",
"returns",
"all",
"key",
"store",
"addresses",
"that",
"have",
"been",
"requested",
"to",
"be",
"generated",
".",
"These",
"do",
"not",
"include",
"unused",
"addresses",
"in",
"the",
"key",
"pool",
".",
"Use",
"this",
"when",
"ordered",
"addresses",
"are",
"needed",
".",
"Otherwise",
"ActiveAddresses",
"is",
"preferred",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L1617-L1634 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | ActiveAddresses | func (s *Store) ActiveAddresses() map[btcutil.Address]WalletAddress {
s.mtx.RLock()
defer s.mtx.RUnlock()
addrs := make(map[btcutil.Address]WalletAddress)
for i := int64(rootKeyChainIdx); i <= s.highestUsed; i++ {
a := s.chainIdxMap[i]
addr := s.addrMap[getAddressKey(a)]
addrs[addr.Address()] = addr
}
for _, addr := range s.importedAddrs {
addrs[addr.Address()] = addr
}
return addrs
} | go | func (s *Store) ActiveAddresses() map[btcutil.Address]WalletAddress {
s.mtx.RLock()
defer s.mtx.RUnlock()
addrs := make(map[btcutil.Address]WalletAddress)
for i := int64(rootKeyChainIdx); i <= s.highestUsed; i++ {
a := s.chainIdxMap[i]
addr := s.addrMap[getAddressKey(a)]
addrs[addr.Address()] = addr
}
for _, addr := range s.importedAddrs {
addrs[addr.Address()] = addr
}
return addrs
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"ActiveAddresses",
"(",
")",
"map",
"[",
"btcutil",
".",
"Address",
"]",
"WalletAddress",
"{",
"s",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n\n",
"addrs",
":=",
"make",
"(",
"map",
"[",
"btcutil",
".",
"Address",
"]",
"WalletAddress",
")",
"\n",
"for",
"i",
":=",
"int64",
"(",
"rootKeyChainIdx",
")",
";",
"i",
"<=",
"s",
".",
"highestUsed",
";",
"i",
"++",
"{",
"a",
":=",
"s",
".",
"chainIdxMap",
"[",
"i",
"]",
"\n",
"addr",
":=",
"s",
".",
"addrMap",
"[",
"getAddressKey",
"(",
"a",
")",
"]",
"\n",
"addrs",
"[",
"addr",
".",
"Address",
"(",
")",
"]",
"=",
"addr",
"\n",
"}",
"\n",
"for",
"_",
",",
"addr",
":=",
"range",
"s",
".",
"importedAddrs",
"{",
"addrs",
"[",
"addr",
".",
"Address",
"(",
")",
"]",
"=",
"addr",
"\n",
"}",
"\n",
"return",
"addrs",
"\n",
"}"
] | // ActiveAddresses returns a map between active payment addresses
// and their full info. These do not include unused addresses in the
// key pool. If addresses must be sorted, use SortedActiveAddresses. | [
"ActiveAddresses",
"returns",
"a",
"map",
"between",
"active",
"payment",
"addresses",
"and",
"their",
"full",
"info",
".",
"These",
"do",
"not",
"include",
"unused",
"addresses",
"in",
"the",
"key",
"pool",
".",
"If",
"addresses",
"must",
"be",
"sorted",
"use",
"SortedActiveAddresses",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L1639-L1653 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | newRootBtcAddress | func newRootBtcAddress(s *Store, privKey, iv, chaincode []byte,
bs *BlockStamp) (addr *btcAddress, err error) {
if len(chaincode) != 32 {
return nil, errors.New("chaincode is not 32 bytes")
}
// Create new btcAddress with provided inputs. This will
// always use a compressed pubkey.
addr, err = newBtcAddress(s, privKey, iv, bs, true)
if err != nil {
return nil, err
}
copy(addr.chaincode[:], chaincode)
addr.chainIndex = rootKeyChainIdx
return addr, err
} | go | func newRootBtcAddress(s *Store, privKey, iv, chaincode []byte,
bs *BlockStamp) (addr *btcAddress, err error) {
if len(chaincode) != 32 {
return nil, errors.New("chaincode is not 32 bytes")
}
// Create new btcAddress with provided inputs. This will
// always use a compressed pubkey.
addr, err = newBtcAddress(s, privKey, iv, bs, true)
if err != nil {
return nil, err
}
copy(addr.chaincode[:], chaincode)
addr.chainIndex = rootKeyChainIdx
return addr, err
} | [
"func",
"newRootBtcAddress",
"(",
"s",
"*",
"Store",
",",
"privKey",
",",
"iv",
",",
"chaincode",
"[",
"]",
"byte",
",",
"bs",
"*",
"BlockStamp",
")",
"(",
"addr",
"*",
"btcAddress",
",",
"err",
"error",
")",
"{",
"if",
"len",
"(",
"chaincode",
")",
"!=",
"32",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Create new btcAddress with provided inputs. This will",
"// always use a compressed pubkey.",
"addr",
",",
"err",
"=",
"newBtcAddress",
"(",
"s",
",",
"privKey",
",",
"iv",
",",
"bs",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"copy",
"(",
"addr",
".",
"chaincode",
"[",
":",
"]",
",",
"chaincode",
")",
"\n",
"addr",
".",
"chainIndex",
"=",
"rootKeyChainIdx",
"\n\n",
"return",
"addr",
",",
"err",
"\n",
"}"
] | // newRootBtcAddress generates a new address, also setting the
// chaincode and chain index to represent this address as a root
// address. | [
"newRootBtcAddress",
"generates",
"a",
"new",
"address",
"also",
"setting",
"the",
"chaincode",
"and",
"chain",
"index",
"to",
"represent",
"this",
"address",
"as",
"a",
"root",
"address",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L2213-L2231 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | verifyKeypairs | func (a *btcAddress) verifyKeypairs() error {
if len(a.privKeyCT) != 32 {
return errors.New("private key unavailable")
}
privKey := &btcec.PrivateKey{
PublicKey: *a.pubKey.ToECDSA(),
D: new(big.Int).SetBytes(a.privKeyCT),
}
data := "String to sign."
sig, err := privKey.Sign([]byte(data))
if err != nil {
return err
}
ok := sig.Verify([]byte(data), privKey.PubKey())
if !ok {
return errors.New("pubkey verification failed")
}
return nil
} | go | func (a *btcAddress) verifyKeypairs() error {
if len(a.privKeyCT) != 32 {
return errors.New("private key unavailable")
}
privKey := &btcec.PrivateKey{
PublicKey: *a.pubKey.ToECDSA(),
D: new(big.Int).SetBytes(a.privKeyCT),
}
data := "String to sign."
sig, err := privKey.Sign([]byte(data))
if err != nil {
return err
}
ok := sig.Verify([]byte(data), privKey.PubKey())
if !ok {
return errors.New("pubkey verification failed")
}
return nil
} | [
"func",
"(",
"a",
"*",
"btcAddress",
")",
"verifyKeypairs",
"(",
")",
"error",
"{",
"if",
"len",
"(",
"a",
".",
"privKeyCT",
")",
"!=",
"32",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"privKey",
":=",
"&",
"btcec",
".",
"PrivateKey",
"{",
"PublicKey",
":",
"*",
"a",
".",
"pubKey",
".",
"ToECDSA",
"(",
")",
",",
"D",
":",
"new",
"(",
"big",
".",
"Int",
")",
".",
"SetBytes",
"(",
"a",
".",
"privKeyCT",
")",
",",
"}",
"\n\n",
"data",
":=",
"\"",
"\"",
"\n",
"sig",
",",
"err",
":=",
"privKey",
".",
"Sign",
"(",
"[",
"]",
"byte",
"(",
"data",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"ok",
":=",
"sig",
".",
"Verify",
"(",
"[",
"]",
"byte",
"(",
"data",
")",
",",
"privKey",
".",
"PubKey",
"(",
")",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // verifyKeypairs creates a signature using the parsed private key and
// verifies the signature with the parsed public key. If either of these
// steps fail, the keypair generation failed and any funds sent to this
// address will be unspendable. This step requires an unencrypted or
// unlocked btcAddress. | [
"verifyKeypairs",
"creates",
"a",
"signature",
"using",
"the",
"parsed",
"private",
"key",
"and",
"verifies",
"the",
"signature",
"with",
"the",
"parsed",
"public",
"key",
".",
"If",
"either",
"of",
"these",
"steps",
"fail",
"the",
"keypair",
"generation",
"failed",
"and",
"any",
"funds",
"sent",
"to",
"this",
"address",
"will",
"be",
"unspendable",
".",
"This",
"step",
"requires",
"an",
"unencrypted",
"or",
"unlocked",
"btcAddress",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L2238-L2259 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | ReadFrom | func (a *btcAddress) ReadFrom(r io.Reader) (n int64, err error) {
var read int64
// Checksums
var chkPubKeyHash uint32
var chkChaincode uint32
var chkInitVector uint32
var chkPrivKey uint32
var chkPubKey uint32
var pubKeyHash [ripemd160.Size]byte
var pubKey publicKey
// Read serialized key store into addr fields and checksums.
datas := []interface{}{
&pubKeyHash,
&chkPubKeyHash,
make([]byte, 4), // version
&a.flags,
&a.chaincode,
&chkChaincode,
&a.chainIndex,
&a.chainDepth,
&a.initVector,
&chkInitVector,
&a.privKey,
&chkPrivKey,
&pubKey,
&chkPubKey,
&a.firstSeen,
&a.lastSeen,
&a.firstBlock,
&a.partialSyncHeight,
}
for _, data := range datas {
if rf, ok := data.(io.ReaderFrom); ok {
read, err = rf.ReadFrom(r)
} else {
read, err = binaryRead(r, binary.LittleEndian, data)
}
if err != nil {
return n + read, err
}
n += read
}
// Verify checksums, correct errors where possible.
checks := []struct {
data []byte
chk uint32
}{
{pubKeyHash[:], chkPubKeyHash},
{a.chaincode[:], chkChaincode},
{a.initVector[:], chkInitVector},
{a.privKey[:], chkPrivKey},
{pubKey, chkPubKey},
}
for i := range checks {
if err = verifyAndFix(checks[i].data, checks[i].chk); err != nil {
return n, err
}
}
if !a.flags.hasPubKey {
return n, errors.New("read in an address without a public key")
}
pk, err := btcec.ParsePubKey(pubKey, btcec.S256())
if err != nil {
return n, err
}
a.pubKey = pk
addr, err := btcutil.NewAddressPubKeyHash(pubKeyHash[:], a.store.netParams())
if err != nil {
return n, err
}
a.address = addr
return n, nil
} | go | func (a *btcAddress) ReadFrom(r io.Reader) (n int64, err error) {
var read int64
// Checksums
var chkPubKeyHash uint32
var chkChaincode uint32
var chkInitVector uint32
var chkPrivKey uint32
var chkPubKey uint32
var pubKeyHash [ripemd160.Size]byte
var pubKey publicKey
// Read serialized key store into addr fields and checksums.
datas := []interface{}{
&pubKeyHash,
&chkPubKeyHash,
make([]byte, 4), // version
&a.flags,
&a.chaincode,
&chkChaincode,
&a.chainIndex,
&a.chainDepth,
&a.initVector,
&chkInitVector,
&a.privKey,
&chkPrivKey,
&pubKey,
&chkPubKey,
&a.firstSeen,
&a.lastSeen,
&a.firstBlock,
&a.partialSyncHeight,
}
for _, data := range datas {
if rf, ok := data.(io.ReaderFrom); ok {
read, err = rf.ReadFrom(r)
} else {
read, err = binaryRead(r, binary.LittleEndian, data)
}
if err != nil {
return n + read, err
}
n += read
}
// Verify checksums, correct errors where possible.
checks := []struct {
data []byte
chk uint32
}{
{pubKeyHash[:], chkPubKeyHash},
{a.chaincode[:], chkChaincode},
{a.initVector[:], chkInitVector},
{a.privKey[:], chkPrivKey},
{pubKey, chkPubKey},
}
for i := range checks {
if err = verifyAndFix(checks[i].data, checks[i].chk); err != nil {
return n, err
}
}
if !a.flags.hasPubKey {
return n, errors.New("read in an address without a public key")
}
pk, err := btcec.ParsePubKey(pubKey, btcec.S256())
if err != nil {
return n, err
}
a.pubKey = pk
addr, err := btcutil.NewAddressPubKeyHash(pubKeyHash[:], a.store.netParams())
if err != nil {
return n, err
}
a.address = addr
return n, nil
} | [
"func",
"(",
"a",
"*",
"btcAddress",
")",
"ReadFrom",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"n",
"int64",
",",
"err",
"error",
")",
"{",
"var",
"read",
"int64",
"\n\n",
"// Checksums",
"var",
"chkPubKeyHash",
"uint32",
"\n",
"var",
"chkChaincode",
"uint32",
"\n",
"var",
"chkInitVector",
"uint32",
"\n",
"var",
"chkPrivKey",
"uint32",
"\n",
"var",
"chkPubKey",
"uint32",
"\n",
"var",
"pubKeyHash",
"[",
"ripemd160",
".",
"Size",
"]",
"byte",
"\n",
"var",
"pubKey",
"publicKey",
"\n\n",
"// Read serialized key store into addr fields and checksums.",
"datas",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"&",
"pubKeyHash",
",",
"&",
"chkPubKeyHash",
",",
"make",
"(",
"[",
"]",
"byte",
",",
"4",
")",
",",
"// version",
"&",
"a",
".",
"flags",
",",
"&",
"a",
".",
"chaincode",
",",
"&",
"chkChaincode",
",",
"&",
"a",
".",
"chainIndex",
",",
"&",
"a",
".",
"chainDepth",
",",
"&",
"a",
".",
"initVector",
",",
"&",
"chkInitVector",
",",
"&",
"a",
".",
"privKey",
",",
"&",
"chkPrivKey",
",",
"&",
"pubKey",
",",
"&",
"chkPubKey",
",",
"&",
"a",
".",
"firstSeen",
",",
"&",
"a",
".",
"lastSeen",
",",
"&",
"a",
".",
"firstBlock",
",",
"&",
"a",
".",
"partialSyncHeight",
",",
"}",
"\n",
"for",
"_",
",",
"data",
":=",
"range",
"datas",
"{",
"if",
"rf",
",",
"ok",
":=",
"data",
".",
"(",
"io",
".",
"ReaderFrom",
")",
";",
"ok",
"{",
"read",
",",
"err",
"=",
"rf",
".",
"ReadFrom",
"(",
"r",
")",
"\n",
"}",
"else",
"{",
"read",
",",
"err",
"=",
"binaryRead",
"(",
"r",
",",
"binary",
".",
"LittleEndian",
",",
"data",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"n",
"+",
"read",
",",
"err",
"\n",
"}",
"\n",
"n",
"+=",
"read",
"\n",
"}",
"\n\n",
"// Verify checksums, correct errors where possible.",
"checks",
":=",
"[",
"]",
"struct",
"{",
"data",
"[",
"]",
"byte",
"\n",
"chk",
"uint32",
"\n",
"}",
"{",
"{",
"pubKeyHash",
"[",
":",
"]",
",",
"chkPubKeyHash",
"}",
",",
"{",
"a",
".",
"chaincode",
"[",
":",
"]",
",",
"chkChaincode",
"}",
",",
"{",
"a",
".",
"initVector",
"[",
":",
"]",
",",
"chkInitVector",
"}",
",",
"{",
"a",
".",
"privKey",
"[",
":",
"]",
",",
"chkPrivKey",
"}",
",",
"{",
"pubKey",
",",
"chkPubKey",
"}",
",",
"}",
"\n",
"for",
"i",
":=",
"range",
"checks",
"{",
"if",
"err",
"=",
"verifyAndFix",
"(",
"checks",
"[",
"i",
"]",
".",
"data",
",",
"checks",
"[",
"i",
"]",
".",
"chk",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"n",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"!",
"a",
".",
"flags",
".",
"hasPubKey",
"{",
"return",
"n",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"pk",
",",
"err",
":=",
"btcec",
".",
"ParsePubKey",
"(",
"pubKey",
",",
"btcec",
".",
"S256",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"n",
",",
"err",
"\n",
"}",
"\n",
"a",
".",
"pubKey",
"=",
"pk",
"\n\n",
"addr",
",",
"err",
":=",
"btcutil",
".",
"NewAddressPubKeyHash",
"(",
"pubKeyHash",
"[",
":",
"]",
",",
"a",
".",
"store",
".",
"netParams",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"n",
",",
"err",
"\n",
"}",
"\n",
"a",
".",
"address",
"=",
"addr",
"\n\n",
"return",
"n",
",",
"nil",
"\n",
"}"
] | // ReadFrom reads an encrypted address from an io.Reader. | [
"ReadFrom",
"reads",
"an",
"encrypted",
"address",
"from",
"an",
"io",
".",
"Reader",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L2262-L2340 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | encrypt | func (a *btcAddress) encrypt(key []byte) error {
if a.flags.encrypted {
return ErrAlreadyEncrypted
}
if len(a.privKeyCT) != 32 {
return errors.New("invalid clear text private key")
}
aesBlockEncrypter, err := aes.NewCipher(key)
if err != nil {
return err
}
aesEncrypter := cipher.NewCFBEncrypter(aesBlockEncrypter, a.initVector[:])
aesEncrypter.XORKeyStream(a.privKey[:], a.privKeyCT)
a.flags.hasPrivKey = true
a.flags.encrypted = true
return nil
} | go | func (a *btcAddress) encrypt(key []byte) error {
if a.flags.encrypted {
return ErrAlreadyEncrypted
}
if len(a.privKeyCT) != 32 {
return errors.New("invalid clear text private key")
}
aesBlockEncrypter, err := aes.NewCipher(key)
if err != nil {
return err
}
aesEncrypter := cipher.NewCFBEncrypter(aesBlockEncrypter, a.initVector[:])
aesEncrypter.XORKeyStream(a.privKey[:], a.privKeyCT)
a.flags.hasPrivKey = true
a.flags.encrypted = true
return nil
} | [
"func",
"(",
"a",
"*",
"btcAddress",
")",
"encrypt",
"(",
"key",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"a",
".",
"flags",
".",
"encrypted",
"{",
"return",
"ErrAlreadyEncrypted",
"\n",
"}",
"\n",
"if",
"len",
"(",
"a",
".",
"privKeyCT",
")",
"!=",
"32",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"aesBlockEncrypter",
",",
"err",
":=",
"aes",
".",
"NewCipher",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"aesEncrypter",
":=",
"cipher",
".",
"NewCFBEncrypter",
"(",
"aesBlockEncrypter",
",",
"a",
".",
"initVector",
"[",
":",
"]",
")",
"\n\n",
"aesEncrypter",
".",
"XORKeyStream",
"(",
"a",
".",
"privKey",
"[",
":",
"]",
",",
"a",
".",
"privKeyCT",
")",
"\n\n",
"a",
".",
"flags",
".",
"hasPrivKey",
"=",
"true",
"\n",
"a",
".",
"flags",
".",
"encrypted",
"=",
"true",
"\n",
"return",
"nil",
"\n",
"}"
] | // encrypt attempts to encrypt an address's clear text private key,
// failing if the address is already encrypted or if the private key is
// not 32 bytes. If successful, the encryption flag is set. | [
"encrypt",
"attempts",
"to",
"encrypt",
"an",
"address",
"s",
"clear",
"text",
"private",
"key",
"failing",
"if",
"the",
"address",
"is",
"already",
"encrypted",
"or",
"if",
"the",
"private",
"key",
"is",
"not",
"32",
"bytes",
".",
"If",
"successful",
"the",
"encryption",
"flag",
"is",
"set",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L2385-L2404 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | lock | func (a *btcAddress) lock() error {
if !a.flags.encrypted {
return errors.New("unable to lock unencrypted address")
}
zero(a.privKeyCT)
a.privKeyCT = nil
return nil
} | go | func (a *btcAddress) lock() error {
if !a.flags.encrypted {
return errors.New("unable to lock unencrypted address")
}
zero(a.privKeyCT)
a.privKeyCT = nil
return nil
} | [
"func",
"(",
"a",
"*",
"btcAddress",
")",
"lock",
"(",
")",
"error",
"{",
"if",
"!",
"a",
".",
"flags",
".",
"encrypted",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"zero",
"(",
"a",
".",
"privKeyCT",
")",
"\n",
"a",
".",
"privKeyCT",
"=",
"nil",
"\n",
"return",
"nil",
"\n",
"}"
] | // lock removes the reference this address holds to its clear text
// private key. This function fails if the address is not encrypted. | [
"lock",
"removes",
"the",
"reference",
"this",
"address",
"holds",
"to",
"its",
"clear",
"text",
"private",
"key",
".",
"This",
"function",
"fails",
"if",
"the",
"address",
"is",
"not",
"encrypted",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L2408-L2416 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | unlock | func (a *btcAddress) unlock(key []byte) (privKeyCT []byte, err error) {
if !a.flags.encrypted {
return nil, errors.New("unable to unlock unencrypted address")
}
// Decrypt private key with AES key.
aesBlockDecrypter, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
aesDecrypter := cipher.NewCFBDecrypter(aesBlockDecrypter, a.initVector[:])
privkey := make([]byte, 32)
aesDecrypter.XORKeyStream(privkey, a.privKey[:])
// If secret is already saved, simply compare the bytes.
if len(a.privKeyCT) == 32 {
if !bytes.Equal(a.privKeyCT, privkey) {
return nil, ErrWrongPassphrase
}
privKeyCT := make([]byte, 32)
copy(privKeyCT, a.privKeyCT)
return privKeyCT, nil
}
x, y := btcec.S256().ScalarBaseMult(privkey)
if x.Cmp(a.pubKey.X) != 0 || y.Cmp(a.pubKey.Y) != 0 {
return nil, ErrWrongPassphrase
}
privkeyCopy := make([]byte, 32)
copy(privkeyCopy, privkey)
a.privKeyCT = privkey
return privkeyCopy, nil
} | go | func (a *btcAddress) unlock(key []byte) (privKeyCT []byte, err error) {
if !a.flags.encrypted {
return nil, errors.New("unable to unlock unencrypted address")
}
// Decrypt private key with AES key.
aesBlockDecrypter, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
aesDecrypter := cipher.NewCFBDecrypter(aesBlockDecrypter, a.initVector[:])
privkey := make([]byte, 32)
aesDecrypter.XORKeyStream(privkey, a.privKey[:])
// If secret is already saved, simply compare the bytes.
if len(a.privKeyCT) == 32 {
if !bytes.Equal(a.privKeyCT, privkey) {
return nil, ErrWrongPassphrase
}
privKeyCT := make([]byte, 32)
copy(privKeyCT, a.privKeyCT)
return privKeyCT, nil
}
x, y := btcec.S256().ScalarBaseMult(privkey)
if x.Cmp(a.pubKey.X) != 0 || y.Cmp(a.pubKey.Y) != 0 {
return nil, ErrWrongPassphrase
}
privkeyCopy := make([]byte, 32)
copy(privkeyCopy, privkey)
a.privKeyCT = privkey
return privkeyCopy, nil
} | [
"func",
"(",
"a",
"*",
"btcAddress",
")",
"unlock",
"(",
"key",
"[",
"]",
"byte",
")",
"(",
"privKeyCT",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"if",
"!",
"a",
".",
"flags",
".",
"encrypted",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Decrypt private key with AES key.",
"aesBlockDecrypter",
",",
"err",
":=",
"aes",
".",
"NewCipher",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"aesDecrypter",
":=",
"cipher",
".",
"NewCFBDecrypter",
"(",
"aesBlockDecrypter",
",",
"a",
".",
"initVector",
"[",
":",
"]",
")",
"\n",
"privkey",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"32",
")",
"\n",
"aesDecrypter",
".",
"XORKeyStream",
"(",
"privkey",
",",
"a",
".",
"privKey",
"[",
":",
"]",
")",
"\n\n",
"// If secret is already saved, simply compare the bytes.",
"if",
"len",
"(",
"a",
".",
"privKeyCT",
")",
"==",
"32",
"{",
"if",
"!",
"bytes",
".",
"Equal",
"(",
"a",
".",
"privKeyCT",
",",
"privkey",
")",
"{",
"return",
"nil",
",",
"ErrWrongPassphrase",
"\n",
"}",
"\n",
"privKeyCT",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"32",
")",
"\n",
"copy",
"(",
"privKeyCT",
",",
"a",
".",
"privKeyCT",
")",
"\n",
"return",
"privKeyCT",
",",
"nil",
"\n",
"}",
"\n\n",
"x",
",",
"y",
":=",
"btcec",
".",
"S256",
"(",
")",
".",
"ScalarBaseMult",
"(",
"privkey",
")",
"\n",
"if",
"x",
".",
"Cmp",
"(",
"a",
".",
"pubKey",
".",
"X",
")",
"!=",
"0",
"||",
"y",
".",
"Cmp",
"(",
"a",
".",
"pubKey",
".",
"Y",
")",
"!=",
"0",
"{",
"return",
"nil",
",",
"ErrWrongPassphrase",
"\n",
"}",
"\n\n",
"privkeyCopy",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"32",
")",
"\n",
"copy",
"(",
"privkeyCopy",
",",
"privkey",
")",
"\n",
"a",
".",
"privKeyCT",
"=",
"privkey",
"\n",
"return",
"privkeyCopy",
",",
"nil",
"\n",
"}"
] | // unlock decrypts and stores a pointer to an address's private key,
// failing if the address is not encrypted, or the provided key is
// incorrect. The returned clear text private key will always be a copy
// that may be safely used by the caller without worrying about it being
// zeroed during an address lock. | [
"unlock",
"decrypts",
"and",
"stores",
"a",
"pointer",
"to",
"an",
"address",
"s",
"private",
"key",
"failing",
"if",
"the",
"address",
"is",
"not",
"encrypted",
"or",
"the",
"provided",
"key",
"is",
"incorrect",
".",
"The",
"returned",
"clear",
"text",
"private",
"key",
"will",
"always",
"be",
"a",
"copy",
"that",
"may",
"be",
"safely",
"used",
"by",
"the",
"caller",
"without",
"worrying",
"about",
"it",
"being",
"zeroed",
"during",
"an",
"address",
"lock",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L2423-L2456 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | changeEncryptionKey | func (a *btcAddress) changeEncryptionKey(oldkey, newkey []byte) error {
// Address must have a private key and be encrypted to continue.
if !a.flags.hasPrivKey {
return errors.New("no private key")
}
if !a.flags.encrypted {
return errors.New("address is not encrypted")
}
privKeyCT, err := a.unlock(oldkey)
if err != nil {
return err
}
aesBlockEncrypter, err := aes.NewCipher(newkey)
if err != nil {
return err
}
newIV := make([]byte, len(a.initVector))
if _, err := rand.Read(newIV); err != nil {
return err
}
copy(a.initVector[:], newIV)
aesEncrypter := cipher.NewCFBEncrypter(aesBlockEncrypter, a.initVector[:])
aesEncrypter.XORKeyStream(a.privKey[:], privKeyCT)
return nil
} | go | func (a *btcAddress) changeEncryptionKey(oldkey, newkey []byte) error {
// Address must have a private key and be encrypted to continue.
if !a.flags.hasPrivKey {
return errors.New("no private key")
}
if !a.flags.encrypted {
return errors.New("address is not encrypted")
}
privKeyCT, err := a.unlock(oldkey)
if err != nil {
return err
}
aesBlockEncrypter, err := aes.NewCipher(newkey)
if err != nil {
return err
}
newIV := make([]byte, len(a.initVector))
if _, err := rand.Read(newIV); err != nil {
return err
}
copy(a.initVector[:], newIV)
aesEncrypter := cipher.NewCFBEncrypter(aesBlockEncrypter, a.initVector[:])
aesEncrypter.XORKeyStream(a.privKey[:], privKeyCT)
return nil
} | [
"func",
"(",
"a",
"*",
"btcAddress",
")",
"changeEncryptionKey",
"(",
"oldkey",
",",
"newkey",
"[",
"]",
"byte",
")",
"error",
"{",
"// Address must have a private key and be encrypted to continue.",
"if",
"!",
"a",
".",
"flags",
".",
"hasPrivKey",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"!",
"a",
".",
"flags",
".",
"encrypted",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"privKeyCT",
",",
"err",
":=",
"a",
".",
"unlock",
"(",
"oldkey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"aesBlockEncrypter",
",",
"err",
":=",
"aes",
".",
"NewCipher",
"(",
"newkey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"newIV",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"a",
".",
"initVector",
")",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"rand",
".",
"Read",
"(",
"newIV",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"copy",
"(",
"a",
".",
"initVector",
"[",
":",
"]",
",",
"newIV",
")",
"\n",
"aesEncrypter",
":=",
"cipher",
".",
"NewCFBEncrypter",
"(",
"aesBlockEncrypter",
",",
"a",
".",
"initVector",
"[",
":",
"]",
")",
"\n",
"aesEncrypter",
".",
"XORKeyStream",
"(",
"a",
".",
"privKey",
"[",
":",
"]",
",",
"privKeyCT",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // changeEncryptionKey re-encrypts the private keys for an address
// with a new AES encryption key. oldkey must be the old AES encryption key
// and is used to decrypt the private key. | [
"changeEncryptionKey",
"re",
"-",
"encrypts",
"the",
"private",
"keys",
"for",
"an",
"address",
"with",
"a",
"new",
"AES",
"encryption",
"key",
".",
"oldkey",
"must",
"be",
"the",
"old",
"AES",
"encryption",
"key",
"and",
"is",
"used",
"to",
"decrypt",
"the",
"private",
"key",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L2461-L2488 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | SyncStatus | func (a *btcAddress) SyncStatus() SyncStatus {
switch {
case a.flags.unsynced && !a.flags.partialSync:
return Unsynced(a.firstBlock)
case a.flags.unsynced && a.flags.partialSync:
return PartialSync(a.partialSyncHeight)
default:
return FullSync{}
}
} | go | func (a *btcAddress) SyncStatus() SyncStatus {
switch {
case a.flags.unsynced && !a.flags.partialSync:
return Unsynced(a.firstBlock)
case a.flags.unsynced && a.flags.partialSync:
return PartialSync(a.partialSyncHeight)
default:
return FullSync{}
}
} | [
"func",
"(",
"a",
"*",
"btcAddress",
")",
"SyncStatus",
"(",
")",
"SyncStatus",
"{",
"switch",
"{",
"case",
"a",
".",
"flags",
".",
"unsynced",
"&&",
"!",
"a",
".",
"flags",
".",
"partialSync",
":",
"return",
"Unsynced",
"(",
"a",
".",
"firstBlock",
")",
"\n",
"case",
"a",
".",
"flags",
".",
"unsynced",
"&&",
"a",
".",
"flags",
".",
"partialSync",
":",
"return",
"PartialSync",
"(",
"a",
".",
"partialSyncHeight",
")",
"\n",
"default",
":",
"return",
"FullSync",
"{",
"}",
"\n",
"}",
"\n",
"}"
] | // SyncStatus returns a SyncStatus type for how the address is currently
// synced. For an Unsynced type, the value is the recorded first seen
// block height of the address. | [
"SyncStatus",
"returns",
"a",
"SyncStatus",
"type",
"for",
"how",
"the",
"address",
"is",
"currently",
"synced",
".",
"For",
"an",
"Unsynced",
"type",
"the",
"value",
"is",
"the",
"recorded",
"first",
"seen",
"block",
"height",
"of",
"the",
"address",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L2527-L2536 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | PrivKey | func (a *btcAddress) PrivKey() (*btcec.PrivateKey, error) {
if a.store.flags.watchingOnly {
return nil, ErrWatchingOnly
}
if !a.flags.hasPrivKey {
return nil, errors.New("no private key for address")
}
// Key store must be unlocked to decrypt the private key.
if a.store.isLocked() {
return nil, ErrLocked
}
// Unlock address with key store secret. unlock returns a copy of
// the clear text private key, and may be used safely even
// during an address lock.
privKeyCT, err := a.unlock(a.store.secret)
if err != nil {
return nil, err
}
return &btcec.PrivateKey{
PublicKey: *a.pubKey.ToECDSA(),
D: new(big.Int).SetBytes(privKeyCT),
}, nil
} | go | func (a *btcAddress) PrivKey() (*btcec.PrivateKey, error) {
if a.store.flags.watchingOnly {
return nil, ErrWatchingOnly
}
if !a.flags.hasPrivKey {
return nil, errors.New("no private key for address")
}
// Key store must be unlocked to decrypt the private key.
if a.store.isLocked() {
return nil, ErrLocked
}
// Unlock address with key store secret. unlock returns a copy of
// the clear text private key, and may be used safely even
// during an address lock.
privKeyCT, err := a.unlock(a.store.secret)
if err != nil {
return nil, err
}
return &btcec.PrivateKey{
PublicKey: *a.pubKey.ToECDSA(),
D: new(big.Int).SetBytes(privKeyCT),
}, nil
} | [
"func",
"(",
"a",
"*",
"btcAddress",
")",
"PrivKey",
"(",
")",
"(",
"*",
"btcec",
".",
"PrivateKey",
",",
"error",
")",
"{",
"if",
"a",
".",
"store",
".",
"flags",
".",
"watchingOnly",
"{",
"return",
"nil",
",",
"ErrWatchingOnly",
"\n",
"}",
"\n\n",
"if",
"!",
"a",
".",
"flags",
".",
"hasPrivKey",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Key store must be unlocked to decrypt the private key.",
"if",
"a",
".",
"store",
".",
"isLocked",
"(",
")",
"{",
"return",
"nil",
",",
"ErrLocked",
"\n",
"}",
"\n\n",
"// Unlock address with key store secret. unlock returns a copy of",
"// the clear text private key, and may be used safely even",
"// during an address lock.",
"privKeyCT",
",",
"err",
":=",
"a",
".",
"unlock",
"(",
"a",
".",
"store",
".",
"secret",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"btcec",
".",
"PrivateKey",
"{",
"PublicKey",
":",
"*",
"a",
".",
"pubKey",
".",
"ToECDSA",
"(",
")",
",",
"D",
":",
"new",
"(",
"big",
".",
"Int",
")",
".",
"SetBytes",
"(",
"privKeyCT",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] | // PrivKey implements PubKeyAddress by returning the private key, or an error
// if the key store is locked, watching only or the private key is missing. | [
"PrivKey",
"implements",
"PubKeyAddress",
"by",
"returning",
"the",
"private",
"key",
"or",
"an",
"error",
"if",
"the",
"key",
"store",
"is",
"locked",
"watching",
"only",
"or",
"the",
"private",
"key",
"is",
"missing",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L2559-L2585 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | ExportPrivKey | func (a *btcAddress) ExportPrivKey() (*btcutil.WIF, error) {
pk, err := a.PrivKey()
if err != nil {
return nil, err
}
// NewWIF only errors if the network is nil. In this case, panic,
// as our program's assumptions are so broken that this needs to be
// caught immediately, and a stack trace here is more useful than
// elsewhere.
wif, err := btcutil.NewWIF((*btcec.PrivateKey)(pk), a.store.netParams(),
a.Compressed())
if err != nil {
panic(err)
}
return wif, nil
} | go | func (a *btcAddress) ExportPrivKey() (*btcutil.WIF, error) {
pk, err := a.PrivKey()
if err != nil {
return nil, err
}
// NewWIF only errors if the network is nil. In this case, panic,
// as our program's assumptions are so broken that this needs to be
// caught immediately, and a stack trace here is more useful than
// elsewhere.
wif, err := btcutil.NewWIF((*btcec.PrivateKey)(pk), a.store.netParams(),
a.Compressed())
if err != nil {
panic(err)
}
return wif, nil
} | [
"func",
"(",
"a",
"*",
"btcAddress",
")",
"ExportPrivKey",
"(",
")",
"(",
"*",
"btcutil",
".",
"WIF",
",",
"error",
")",
"{",
"pk",
",",
"err",
":=",
"a",
".",
"PrivKey",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// NewWIF only errors if the network is nil. In this case, panic,",
"// as our program's assumptions are so broken that this needs to be",
"// caught immediately, and a stack trace here is more useful than",
"// elsewhere.",
"wif",
",",
"err",
":=",
"btcutil",
".",
"NewWIF",
"(",
"(",
"*",
"btcec",
".",
"PrivateKey",
")",
"(",
"pk",
")",
",",
"a",
".",
"store",
".",
"netParams",
"(",
")",
",",
"a",
".",
"Compressed",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"wif",
",",
"nil",
"\n",
"}"
] | // ExportPrivKey exports the private key as a WIF for encoding as a string
// in the Wallet Import Formt. | [
"ExportPrivKey",
"exports",
"the",
"private",
"key",
"as",
"a",
"WIF",
"for",
"encoding",
"as",
"a",
"string",
"in",
"the",
"Wallet",
"Import",
"Formt",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L2589-L2604 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | watchingCopy | func (a *btcAddress) watchingCopy(s *Store) walletAddress {
return &btcAddress{
store: s,
address: a.address,
flags: addrFlags{
hasPrivKey: false,
hasPubKey: true,
encrypted: false,
createPrivKeyNextUnlock: false,
compressed: a.flags.compressed,
change: a.flags.change,
unsynced: a.flags.unsynced,
},
chaincode: a.chaincode,
chainIndex: a.chainIndex,
chainDepth: a.chainDepth,
pubKey: a.pubKey,
firstSeen: a.firstSeen,
lastSeen: a.lastSeen,
firstBlock: a.firstBlock,
partialSyncHeight: a.partialSyncHeight,
}
} | go | func (a *btcAddress) watchingCopy(s *Store) walletAddress {
return &btcAddress{
store: s,
address: a.address,
flags: addrFlags{
hasPrivKey: false,
hasPubKey: true,
encrypted: false,
createPrivKeyNextUnlock: false,
compressed: a.flags.compressed,
change: a.flags.change,
unsynced: a.flags.unsynced,
},
chaincode: a.chaincode,
chainIndex: a.chainIndex,
chainDepth: a.chainDepth,
pubKey: a.pubKey,
firstSeen: a.firstSeen,
lastSeen: a.lastSeen,
firstBlock: a.firstBlock,
partialSyncHeight: a.partialSyncHeight,
}
} | [
"func",
"(",
"a",
"*",
"btcAddress",
")",
"watchingCopy",
"(",
"s",
"*",
"Store",
")",
"walletAddress",
"{",
"return",
"&",
"btcAddress",
"{",
"store",
":",
"s",
",",
"address",
":",
"a",
".",
"address",
",",
"flags",
":",
"addrFlags",
"{",
"hasPrivKey",
":",
"false",
",",
"hasPubKey",
":",
"true",
",",
"encrypted",
":",
"false",
",",
"createPrivKeyNextUnlock",
":",
"false",
",",
"compressed",
":",
"a",
".",
"flags",
".",
"compressed",
",",
"change",
":",
"a",
".",
"flags",
".",
"change",
",",
"unsynced",
":",
"a",
".",
"flags",
".",
"unsynced",
",",
"}",
",",
"chaincode",
":",
"a",
".",
"chaincode",
",",
"chainIndex",
":",
"a",
".",
"chainIndex",
",",
"chainDepth",
":",
"a",
".",
"chainDepth",
",",
"pubKey",
":",
"a",
".",
"pubKey",
",",
"firstSeen",
":",
"a",
".",
"firstSeen",
",",
"lastSeen",
":",
"a",
".",
"lastSeen",
",",
"firstBlock",
":",
"a",
".",
"firstBlock",
",",
"partialSyncHeight",
":",
"a",
".",
"partialSyncHeight",
",",
"}",
"\n",
"}"
] | // watchingCopy creates a copy of an address without a private key.
// This is used to fill a watching a key store with addresses from a
// normal key store. | [
"watchingCopy",
"creates",
"a",
"copy",
"of",
"an",
"address",
"without",
"a",
"private",
"key",
".",
"This",
"is",
"used",
"to",
"fill",
"a",
"watching",
"a",
"key",
"store",
"with",
"addresses",
"from",
"a",
"normal",
"key",
"store",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L2609-L2631 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | ReadFrom | func (sf *scriptFlags) ReadFrom(r io.Reader) (int64, error) {
var b [8]byte
n, err := io.ReadFull(r, b[:])
if err != nil {
return int64(n), err
}
// We match bits from addrFlags for similar fields. hence hasScript uses
// the same bit as hasPubKey and the change bit is the same for both.
sf.hasScript = b[0]&(1<<1) != 0
sf.change = b[0]&(1<<5) != 0
sf.unsynced = b[0]&(1<<6) != 0
sf.partialSync = b[0]&(1<<7) != 0
return int64(n), nil
} | go | func (sf *scriptFlags) ReadFrom(r io.Reader) (int64, error) {
var b [8]byte
n, err := io.ReadFull(r, b[:])
if err != nil {
return int64(n), err
}
// We match bits from addrFlags for similar fields. hence hasScript uses
// the same bit as hasPubKey and the change bit is the same for both.
sf.hasScript = b[0]&(1<<1) != 0
sf.change = b[0]&(1<<5) != 0
sf.unsynced = b[0]&(1<<6) != 0
sf.partialSync = b[0]&(1<<7) != 0
return int64(n), nil
} | [
"func",
"(",
"sf",
"*",
"scriptFlags",
")",
"ReadFrom",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"int64",
",",
"error",
")",
"{",
"var",
"b",
"[",
"8",
"]",
"byte",
"\n",
"n",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"b",
"[",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"int64",
"(",
"n",
")",
",",
"err",
"\n",
"}",
"\n\n",
"// We match bits from addrFlags for similar fields. hence hasScript uses",
"// the same bit as hasPubKey and the change bit is the same for both.",
"sf",
".",
"hasScript",
"=",
"b",
"[",
"0",
"]",
"&",
"(",
"1",
"<<",
"1",
")",
"!=",
"0",
"\n",
"sf",
".",
"change",
"=",
"b",
"[",
"0",
"]",
"&",
"(",
"1",
"<<",
"5",
")",
"!=",
"0",
"\n",
"sf",
".",
"unsynced",
"=",
"b",
"[",
"0",
"]",
"&",
"(",
"1",
"<<",
"6",
")",
"!=",
"0",
"\n",
"sf",
".",
"partialSync",
"=",
"b",
"[",
"0",
"]",
"&",
"(",
"1",
"<<",
"7",
")",
"!=",
"0",
"\n\n",
"return",
"int64",
"(",
"n",
")",
",",
"nil",
"\n",
"}"
] | // ReadFrom implements the io.ReaderFrom interface by reading from r into sf. | [
"ReadFrom",
"implements",
"the",
"io",
".",
"ReaderFrom",
"interface",
"by",
"reading",
"from",
"r",
"into",
"sf",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L2667-L2682 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | WriteTo | func (sf *scriptFlags) WriteTo(w io.Writer) (int64, error) {
var b [8]byte
if sf.hasScript {
b[0] |= 1 << 1
}
if sf.change {
b[0] |= 1 << 5
}
if sf.unsynced {
b[0] |= 1 << 6
}
if sf.partialSync {
b[0] |= 1 << 7
}
n, err := w.Write(b[:])
return int64(n), err
} | go | func (sf *scriptFlags) WriteTo(w io.Writer) (int64, error) {
var b [8]byte
if sf.hasScript {
b[0] |= 1 << 1
}
if sf.change {
b[0] |= 1 << 5
}
if sf.unsynced {
b[0] |= 1 << 6
}
if sf.partialSync {
b[0] |= 1 << 7
}
n, err := w.Write(b[:])
return int64(n), err
} | [
"func",
"(",
"sf",
"*",
"scriptFlags",
")",
"WriteTo",
"(",
"w",
"io",
".",
"Writer",
")",
"(",
"int64",
",",
"error",
")",
"{",
"var",
"b",
"[",
"8",
"]",
"byte",
"\n",
"if",
"sf",
".",
"hasScript",
"{",
"b",
"[",
"0",
"]",
"|=",
"1",
"<<",
"1",
"\n",
"}",
"\n",
"if",
"sf",
".",
"change",
"{",
"b",
"[",
"0",
"]",
"|=",
"1",
"<<",
"5",
"\n",
"}",
"\n",
"if",
"sf",
".",
"unsynced",
"{",
"b",
"[",
"0",
"]",
"|=",
"1",
"<<",
"6",
"\n",
"}",
"\n",
"if",
"sf",
".",
"partialSync",
"{",
"b",
"[",
"0",
"]",
"|=",
"1",
"<<",
"7",
"\n",
"}",
"\n\n",
"n",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"b",
"[",
":",
"]",
")",
"\n",
"return",
"int64",
"(",
"n",
")",
",",
"err",
"\n",
"}"
] | // WriteTo implements the io.WriteTo interface by writing sf into w. | [
"WriteTo",
"implements",
"the",
"io",
".",
"WriteTo",
"interface",
"by",
"writing",
"sf",
"into",
"w",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L2685-L2702 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | ReadFrom | func (sa *scriptAddress) ReadFrom(r io.Reader) (n int64, err error) {
var read int64
// Checksums
var chkScriptHash uint32
var chkScript uint32
var scriptHash [ripemd160.Size]byte
// Read serialized key store into addr fields and checksums.
datas := []interface{}{
&scriptHash,
&chkScriptHash,
make([]byte, 4), // version
&sa.flags,
&sa.script,
&chkScript,
&sa.firstSeen,
&sa.lastSeen,
&sa.firstBlock,
&sa.partialSyncHeight,
}
for _, data := range datas {
if rf, ok := data.(io.ReaderFrom); ok {
read, err = rf.ReadFrom(r)
} else {
read, err = binaryRead(r, binary.LittleEndian, data)
}
if err != nil {
return n + read, err
}
n += read
}
// Verify checksums, correct errors where possible.
checks := []struct {
data []byte
chk uint32
}{
{scriptHash[:], chkScriptHash},
{sa.script, chkScript},
}
for i := range checks {
if err = verifyAndFix(checks[i].data, checks[i].chk); err != nil {
return n, err
}
}
address, err := btcutil.NewAddressScriptHashFromHash(scriptHash[:],
sa.store.netParams())
if err != nil {
return n, err
}
sa.address = address
if !sa.flags.hasScript {
return n, errors.New("read in an addresss with no script")
}
class, addresses, reqSigs, err :=
txscript.ExtractPkScriptAddrs(sa.script, sa.store.netParams())
if err != nil {
return n, err
}
sa.class = class
sa.addresses = addresses
sa.reqSigs = reqSigs
return n, nil
} | go | func (sa *scriptAddress) ReadFrom(r io.Reader) (n int64, err error) {
var read int64
// Checksums
var chkScriptHash uint32
var chkScript uint32
var scriptHash [ripemd160.Size]byte
// Read serialized key store into addr fields and checksums.
datas := []interface{}{
&scriptHash,
&chkScriptHash,
make([]byte, 4), // version
&sa.flags,
&sa.script,
&chkScript,
&sa.firstSeen,
&sa.lastSeen,
&sa.firstBlock,
&sa.partialSyncHeight,
}
for _, data := range datas {
if rf, ok := data.(io.ReaderFrom); ok {
read, err = rf.ReadFrom(r)
} else {
read, err = binaryRead(r, binary.LittleEndian, data)
}
if err != nil {
return n + read, err
}
n += read
}
// Verify checksums, correct errors where possible.
checks := []struct {
data []byte
chk uint32
}{
{scriptHash[:], chkScriptHash},
{sa.script, chkScript},
}
for i := range checks {
if err = verifyAndFix(checks[i].data, checks[i].chk); err != nil {
return n, err
}
}
address, err := btcutil.NewAddressScriptHashFromHash(scriptHash[:],
sa.store.netParams())
if err != nil {
return n, err
}
sa.address = address
if !sa.flags.hasScript {
return n, errors.New("read in an addresss with no script")
}
class, addresses, reqSigs, err :=
txscript.ExtractPkScriptAddrs(sa.script, sa.store.netParams())
if err != nil {
return n, err
}
sa.class = class
sa.addresses = addresses
sa.reqSigs = reqSigs
return n, nil
} | [
"func",
"(",
"sa",
"*",
"scriptAddress",
")",
"ReadFrom",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"n",
"int64",
",",
"err",
"error",
")",
"{",
"var",
"read",
"int64",
"\n\n",
"// Checksums",
"var",
"chkScriptHash",
"uint32",
"\n",
"var",
"chkScript",
"uint32",
"\n",
"var",
"scriptHash",
"[",
"ripemd160",
".",
"Size",
"]",
"byte",
"\n\n",
"// Read serialized key store into addr fields and checksums.",
"datas",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"&",
"scriptHash",
",",
"&",
"chkScriptHash",
",",
"make",
"(",
"[",
"]",
"byte",
",",
"4",
")",
",",
"// version",
"&",
"sa",
".",
"flags",
",",
"&",
"sa",
".",
"script",
",",
"&",
"chkScript",
",",
"&",
"sa",
".",
"firstSeen",
",",
"&",
"sa",
".",
"lastSeen",
",",
"&",
"sa",
".",
"firstBlock",
",",
"&",
"sa",
".",
"partialSyncHeight",
",",
"}",
"\n",
"for",
"_",
",",
"data",
":=",
"range",
"datas",
"{",
"if",
"rf",
",",
"ok",
":=",
"data",
".",
"(",
"io",
".",
"ReaderFrom",
")",
";",
"ok",
"{",
"read",
",",
"err",
"=",
"rf",
".",
"ReadFrom",
"(",
"r",
")",
"\n",
"}",
"else",
"{",
"read",
",",
"err",
"=",
"binaryRead",
"(",
"r",
",",
"binary",
".",
"LittleEndian",
",",
"data",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"n",
"+",
"read",
",",
"err",
"\n",
"}",
"\n",
"n",
"+=",
"read",
"\n",
"}",
"\n\n",
"// Verify checksums, correct errors where possible.",
"checks",
":=",
"[",
"]",
"struct",
"{",
"data",
"[",
"]",
"byte",
"\n",
"chk",
"uint32",
"\n",
"}",
"{",
"{",
"scriptHash",
"[",
":",
"]",
",",
"chkScriptHash",
"}",
",",
"{",
"sa",
".",
"script",
",",
"chkScript",
"}",
",",
"}",
"\n",
"for",
"i",
":=",
"range",
"checks",
"{",
"if",
"err",
"=",
"verifyAndFix",
"(",
"checks",
"[",
"i",
"]",
".",
"data",
",",
"checks",
"[",
"i",
"]",
".",
"chk",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"n",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"address",
",",
"err",
":=",
"btcutil",
".",
"NewAddressScriptHashFromHash",
"(",
"scriptHash",
"[",
":",
"]",
",",
"sa",
".",
"store",
".",
"netParams",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"n",
",",
"err",
"\n",
"}",
"\n\n",
"sa",
".",
"address",
"=",
"address",
"\n\n",
"if",
"!",
"sa",
".",
"flags",
".",
"hasScript",
"{",
"return",
"n",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"class",
",",
"addresses",
",",
"reqSigs",
",",
"err",
":=",
"txscript",
".",
"ExtractPkScriptAddrs",
"(",
"sa",
".",
"script",
",",
"sa",
".",
"store",
".",
"netParams",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"n",
",",
"err",
"\n",
"}",
"\n\n",
"sa",
".",
"class",
"=",
"class",
"\n",
"sa",
".",
"addresses",
"=",
"addresses",
"\n",
"sa",
".",
"reqSigs",
"=",
"reqSigs",
"\n\n",
"return",
"n",
",",
"nil",
"\n",
"}"
] | // ReadFrom reads an script address from an io.Reader. | [
"ReadFrom",
"reads",
"an",
"script",
"address",
"from",
"an",
"io",
".",
"Reader",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L2817-L2887 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | WriteTo | func (sa *scriptAddress) WriteTo(w io.Writer) (n int64, err error) {
var written int64
hash := sa.address.ScriptAddress()
datas := []interface{}{
&hash,
walletHash(hash),
make([]byte, 4), //version
&sa.flags,
&sa.script,
walletHash(sa.script),
&sa.firstSeen,
&sa.lastSeen,
&sa.firstBlock,
&sa.partialSyncHeight,
}
for _, data := range datas {
if wt, ok := data.(io.WriterTo); ok {
written, err = wt.WriteTo(w)
} else {
written, err = binaryWrite(w, binary.LittleEndian, data)
}
if err != nil {
return n + written, err
}
n += written
}
return n, nil
} | go | func (sa *scriptAddress) WriteTo(w io.Writer) (n int64, err error) {
var written int64
hash := sa.address.ScriptAddress()
datas := []interface{}{
&hash,
walletHash(hash),
make([]byte, 4), //version
&sa.flags,
&sa.script,
walletHash(sa.script),
&sa.firstSeen,
&sa.lastSeen,
&sa.firstBlock,
&sa.partialSyncHeight,
}
for _, data := range datas {
if wt, ok := data.(io.WriterTo); ok {
written, err = wt.WriteTo(w)
} else {
written, err = binaryWrite(w, binary.LittleEndian, data)
}
if err != nil {
return n + written, err
}
n += written
}
return n, nil
} | [
"func",
"(",
"sa",
"*",
"scriptAddress",
")",
"WriteTo",
"(",
"w",
"io",
".",
"Writer",
")",
"(",
"n",
"int64",
",",
"err",
"error",
")",
"{",
"var",
"written",
"int64",
"\n\n",
"hash",
":=",
"sa",
".",
"address",
".",
"ScriptAddress",
"(",
")",
"\n",
"datas",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"&",
"hash",
",",
"walletHash",
"(",
"hash",
")",
",",
"make",
"(",
"[",
"]",
"byte",
",",
"4",
")",
",",
"//version",
"&",
"sa",
".",
"flags",
",",
"&",
"sa",
".",
"script",
",",
"walletHash",
"(",
"sa",
".",
"script",
")",
",",
"&",
"sa",
".",
"firstSeen",
",",
"&",
"sa",
".",
"lastSeen",
",",
"&",
"sa",
".",
"firstBlock",
",",
"&",
"sa",
".",
"partialSyncHeight",
",",
"}",
"\n",
"for",
"_",
",",
"data",
":=",
"range",
"datas",
"{",
"if",
"wt",
",",
"ok",
":=",
"data",
".",
"(",
"io",
".",
"WriterTo",
")",
";",
"ok",
"{",
"written",
",",
"err",
"=",
"wt",
".",
"WriteTo",
"(",
"w",
")",
"\n",
"}",
"else",
"{",
"written",
",",
"err",
"=",
"binaryWrite",
"(",
"w",
",",
"binary",
".",
"LittleEndian",
",",
"data",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"n",
"+",
"written",
",",
"err",
"\n",
"}",
"\n",
"n",
"+=",
"written",
"\n",
"}",
"\n",
"return",
"n",
",",
"nil",
"\n",
"}"
] | // WriteTo implements io.WriterTo by writing the scriptAddress to w. | [
"WriteTo",
"implements",
"io",
".",
"WriterTo",
"by",
"writing",
"the",
"scriptAddress",
"to",
"w",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L2890-L2918 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | SyncStatus | func (sa *scriptAddress) SyncStatus() SyncStatus {
switch {
case sa.flags.unsynced && !sa.flags.partialSync:
return Unsynced(sa.firstBlock)
case sa.flags.unsynced && sa.flags.partialSync:
return PartialSync(sa.partialSyncHeight)
default:
return FullSync{}
}
} | go | func (sa *scriptAddress) SyncStatus() SyncStatus {
switch {
case sa.flags.unsynced && !sa.flags.partialSync:
return Unsynced(sa.firstBlock)
case sa.flags.unsynced && sa.flags.partialSync:
return PartialSync(sa.partialSyncHeight)
default:
return FullSync{}
}
} | [
"func",
"(",
"sa",
"*",
"scriptAddress",
")",
"SyncStatus",
"(",
")",
"SyncStatus",
"{",
"switch",
"{",
"case",
"sa",
".",
"flags",
".",
"unsynced",
"&&",
"!",
"sa",
".",
"flags",
".",
"partialSync",
":",
"return",
"Unsynced",
"(",
"sa",
".",
"firstBlock",
")",
"\n",
"case",
"sa",
".",
"flags",
".",
"unsynced",
"&&",
"sa",
".",
"flags",
".",
"partialSync",
":",
"return",
"PartialSync",
"(",
"sa",
".",
"partialSyncHeight",
")",
"\n",
"default",
":",
"return",
"FullSync",
"{",
"}",
"\n",
"}",
"\n",
"}"
] | // SyncStatus returns a SyncStatus type for how the address is currently
// synced. For an Unsynced type, the value is the recorded first seen
// block height of the address.
// Implements WalletAddress. | [
"SyncStatus",
"returns",
"a",
"SyncStatus",
"type",
"for",
"how",
"the",
"address",
"is",
"currently",
"synced",
".",
"For",
"an",
"Unsynced",
"type",
"the",
"value",
"is",
"the",
"recorded",
"first",
"seen",
"block",
"height",
"of",
"the",
"address",
".",
"Implements",
"WalletAddress",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L2977-L2986 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | watchingCopy | func (sa *scriptAddress) watchingCopy(s *Store) walletAddress {
return &scriptAddress{
store: s,
address: sa.address,
addresses: sa.addresses,
class: sa.class,
reqSigs: sa.reqSigs,
flags: scriptFlags{
change: sa.flags.change,
unsynced: sa.flags.unsynced,
},
script: sa.script,
firstSeen: sa.firstSeen,
lastSeen: sa.lastSeen,
firstBlock: sa.firstBlock,
partialSyncHeight: sa.partialSyncHeight,
}
} | go | func (sa *scriptAddress) watchingCopy(s *Store) walletAddress {
return &scriptAddress{
store: s,
address: sa.address,
addresses: sa.addresses,
class: sa.class,
reqSigs: sa.reqSigs,
flags: scriptFlags{
change: sa.flags.change,
unsynced: sa.flags.unsynced,
},
script: sa.script,
firstSeen: sa.firstSeen,
lastSeen: sa.lastSeen,
firstBlock: sa.firstBlock,
partialSyncHeight: sa.partialSyncHeight,
}
} | [
"func",
"(",
"sa",
"*",
"scriptAddress",
")",
"watchingCopy",
"(",
"s",
"*",
"Store",
")",
"walletAddress",
"{",
"return",
"&",
"scriptAddress",
"{",
"store",
":",
"s",
",",
"address",
":",
"sa",
".",
"address",
",",
"addresses",
":",
"sa",
".",
"addresses",
",",
"class",
":",
"sa",
".",
"class",
",",
"reqSigs",
":",
"sa",
".",
"reqSigs",
",",
"flags",
":",
"scriptFlags",
"{",
"change",
":",
"sa",
".",
"flags",
".",
"change",
",",
"unsynced",
":",
"sa",
".",
"flags",
".",
"unsynced",
",",
"}",
",",
"script",
":",
"sa",
".",
"script",
",",
"firstSeen",
":",
"sa",
".",
"firstSeen",
",",
"lastSeen",
":",
"sa",
".",
"lastSeen",
",",
"firstBlock",
":",
"sa",
".",
"firstBlock",
",",
"partialSyncHeight",
":",
"sa",
".",
"partialSyncHeight",
",",
"}",
"\n",
"}"
] | // watchingCopy creates a copy of an address without a private key.
// This is used to fill a watching key store with addresses from a
// normal key store. | [
"watchingCopy",
"creates",
"a",
"copy",
"of",
"an",
"address",
"without",
"a",
"private",
"key",
".",
"This",
"is",
"used",
"to",
"fill",
"a",
"watching",
"key",
"store",
"with",
"addresses",
"from",
"a",
"normal",
"key",
"store",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L3012-L3029 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | computeKdfParameters | func computeKdfParameters(targetSec float64, maxMem uint64) (*kdfParameters, error) {
params := &kdfParameters{}
if _, err := rand.Read(params.salt[:]); err != nil {
return nil, err
}
testKey := []byte("This is an example key to test KDF iteration speed")
memoryReqtBytes := uint64(1024)
approxSec := float64(0)
for approxSec <= targetSec/4 && memoryReqtBytes < maxMem {
memoryReqtBytes *= 2
before := time.Now()
_ = keyOneIter(testKey, params.salt[:], memoryReqtBytes)
approxSec = time.Since(before).Seconds()
}
allItersSec := float64(0)
nIter := uint32(1)
for allItersSec < 0.02 { // This is a magic number straight from armory's source.
nIter *= 2
before := time.Now()
for i := uint32(0); i < nIter; i++ {
_ = keyOneIter(testKey, params.salt[:], memoryReqtBytes)
}
allItersSec = time.Since(before).Seconds()
}
params.mem = memoryReqtBytes
params.nIter = nIter
return params, nil
} | go | func computeKdfParameters(targetSec float64, maxMem uint64) (*kdfParameters, error) {
params := &kdfParameters{}
if _, err := rand.Read(params.salt[:]); err != nil {
return nil, err
}
testKey := []byte("This is an example key to test KDF iteration speed")
memoryReqtBytes := uint64(1024)
approxSec := float64(0)
for approxSec <= targetSec/4 && memoryReqtBytes < maxMem {
memoryReqtBytes *= 2
before := time.Now()
_ = keyOneIter(testKey, params.salt[:], memoryReqtBytes)
approxSec = time.Since(before).Seconds()
}
allItersSec := float64(0)
nIter := uint32(1)
for allItersSec < 0.02 { // This is a magic number straight from armory's source.
nIter *= 2
before := time.Now()
for i := uint32(0); i < nIter; i++ {
_ = keyOneIter(testKey, params.salt[:], memoryReqtBytes)
}
allItersSec = time.Since(before).Seconds()
}
params.mem = memoryReqtBytes
params.nIter = nIter
return params, nil
} | [
"func",
"computeKdfParameters",
"(",
"targetSec",
"float64",
",",
"maxMem",
"uint64",
")",
"(",
"*",
"kdfParameters",
",",
"error",
")",
"{",
"params",
":=",
"&",
"kdfParameters",
"{",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"rand",
".",
"Read",
"(",
"params",
".",
"salt",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"testKey",
":=",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
"\n\n",
"memoryReqtBytes",
":=",
"uint64",
"(",
"1024",
")",
"\n",
"approxSec",
":=",
"float64",
"(",
"0",
")",
"\n\n",
"for",
"approxSec",
"<=",
"targetSec",
"/",
"4",
"&&",
"memoryReqtBytes",
"<",
"maxMem",
"{",
"memoryReqtBytes",
"*=",
"2",
"\n",
"before",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"_",
"=",
"keyOneIter",
"(",
"testKey",
",",
"params",
".",
"salt",
"[",
":",
"]",
",",
"memoryReqtBytes",
")",
"\n",
"approxSec",
"=",
"time",
".",
"Since",
"(",
"before",
")",
".",
"Seconds",
"(",
")",
"\n",
"}",
"\n\n",
"allItersSec",
":=",
"float64",
"(",
"0",
")",
"\n",
"nIter",
":=",
"uint32",
"(",
"1",
")",
"\n",
"for",
"allItersSec",
"<",
"0.02",
"{",
"// This is a magic number straight from armory's source.",
"nIter",
"*=",
"2",
"\n",
"before",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"for",
"i",
":=",
"uint32",
"(",
"0",
")",
";",
"i",
"<",
"nIter",
";",
"i",
"++",
"{",
"_",
"=",
"keyOneIter",
"(",
"testKey",
",",
"params",
".",
"salt",
"[",
":",
"]",
",",
"memoryReqtBytes",
")",
"\n",
"}",
"\n",
"allItersSec",
"=",
"time",
".",
"Since",
"(",
"before",
")",
".",
"Seconds",
"(",
")",
"\n",
"}",
"\n\n",
"params",
".",
"mem",
"=",
"memoryReqtBytes",
"\n",
"params",
".",
"nIter",
"=",
"nIter",
"\n\n",
"return",
"params",
",",
"nil",
"\n",
"}"
] | // computeKdfParameters returns best guess parameters to the
// memory-hard key derivation function to make the computation last
// targetSec seconds, while using no more than maxMem bytes of memory. | [
"computeKdfParameters",
"returns",
"best",
"guess",
"parameters",
"to",
"the",
"memory",
"-",
"hard",
"key",
"derivation",
"function",
"to",
"make",
"the",
"computation",
"last",
"targetSec",
"seconds",
"while",
"using",
"no",
"more",
"than",
"maxMem",
"bytes",
"of",
"memory",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L3053-L3086 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | WriteTo | func (e *scriptEntry) WriteTo(w io.Writer) (n int64, err error) {
var written int64
// Write header
if written, err = binaryWrite(w, binary.LittleEndian, scriptHeader); err != nil {
return n + written, err
}
n += written
// Write hash
if written, err = binaryWrite(w, binary.LittleEndian, &e.scriptHash160); err != nil {
return n + written, err
}
n += written
// Write btcAddress
written, err = e.script.WriteTo(w)
n += written
return n, err
} | go | func (e *scriptEntry) WriteTo(w io.Writer) (n int64, err error) {
var written int64
// Write header
if written, err = binaryWrite(w, binary.LittleEndian, scriptHeader); err != nil {
return n + written, err
}
n += written
// Write hash
if written, err = binaryWrite(w, binary.LittleEndian, &e.scriptHash160); err != nil {
return n + written, err
}
n += written
// Write btcAddress
written, err = e.script.WriteTo(w)
n += written
return n, err
} | [
"func",
"(",
"e",
"*",
"scriptEntry",
")",
"WriteTo",
"(",
"w",
"io",
".",
"Writer",
")",
"(",
"n",
"int64",
",",
"err",
"error",
")",
"{",
"var",
"written",
"int64",
"\n\n",
"// Write header",
"if",
"written",
",",
"err",
"=",
"binaryWrite",
"(",
"w",
",",
"binary",
".",
"LittleEndian",
",",
"scriptHeader",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"n",
"+",
"written",
",",
"err",
"\n",
"}",
"\n",
"n",
"+=",
"written",
"\n\n",
"// Write hash",
"if",
"written",
",",
"err",
"=",
"binaryWrite",
"(",
"w",
",",
"binary",
".",
"LittleEndian",
",",
"&",
"e",
".",
"scriptHash160",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"n",
"+",
"written",
",",
"err",
"\n",
"}",
"\n",
"n",
"+=",
"written",
"\n\n",
"// Write btcAddress",
"written",
",",
"err",
"=",
"e",
".",
"script",
".",
"WriteTo",
"(",
"w",
")",
"\n",
"n",
"+=",
"written",
"\n",
"return",
"n",
",",
"err",
"\n",
"}"
] | // WriteTo implements io.WriterTo by writing the entry to w. | [
"WriteTo",
"implements",
"io",
".",
"WriterTo",
"by",
"writing",
"the",
"entry",
"to",
"w",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L3201-L3220 | train |
btcsuite/btcwallet | internal/legacy/keystore/keystore.go | ReadFrom | func (e *scriptEntry) ReadFrom(r io.Reader) (n int64, err error) {
var read int64
if read, err = binaryRead(r, binary.LittleEndian, &e.scriptHash160); err != nil {
return n + read, err
}
n += read
read, err = e.script.ReadFrom(r)
return n + read, err
} | go | func (e *scriptEntry) ReadFrom(r io.Reader) (n int64, err error) {
var read int64
if read, err = binaryRead(r, binary.LittleEndian, &e.scriptHash160); err != nil {
return n + read, err
}
n += read
read, err = e.script.ReadFrom(r)
return n + read, err
} | [
"func",
"(",
"e",
"*",
"scriptEntry",
")",
"ReadFrom",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"n",
"int64",
",",
"err",
"error",
")",
"{",
"var",
"read",
"int64",
"\n\n",
"if",
"read",
",",
"err",
"=",
"binaryRead",
"(",
"r",
",",
"binary",
".",
"LittleEndian",
",",
"&",
"e",
".",
"scriptHash160",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"n",
"+",
"read",
",",
"err",
"\n",
"}",
"\n",
"n",
"+=",
"read",
"\n\n",
"read",
",",
"err",
"=",
"e",
".",
"script",
".",
"ReadFrom",
"(",
"r",
")",
"\n",
"return",
"n",
"+",
"read",
",",
"err",
"\n",
"}"
] | // ReadFrom implements io.ReaderFrom by reading the entry from e. | [
"ReadFrom",
"implements",
"io",
".",
"ReaderFrom",
"by",
"reading",
"the",
"entry",
"from",
"e",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/legacy/keystore/keystore.go#L3223-L3233 | train |
btcsuite/btcwallet | chain/block_filterer.go | NewBlockFilterer | func NewBlockFilterer(params *chaincfg.Params,
req *FilterBlocksRequest) *BlockFilterer {
// Construct a reverse index by address string for the requested
// external addresses.
nExAddrs := len(req.ExternalAddrs)
exReverseFilter := make(map[string]waddrmgr.ScopedIndex, nExAddrs)
for scopedIndex, addr := range req.ExternalAddrs {
exReverseFilter[addr.EncodeAddress()] = scopedIndex
}
// Construct a reverse index by address string for the requested
// internal addresses.
nInAddrs := len(req.InternalAddrs)
inReverseFilter := make(map[string]waddrmgr.ScopedIndex, nInAddrs)
for scopedIndex, addr := range req.InternalAddrs {
inReverseFilter[addr.EncodeAddress()] = scopedIndex
}
foundExternal := make(map[waddrmgr.KeyScope]map[uint32]struct{})
foundInternal := make(map[waddrmgr.KeyScope]map[uint32]struct{})
foundOutPoints := make(map[wire.OutPoint]btcutil.Address)
return &BlockFilterer{
Params: params,
ExReverseFilter: exReverseFilter,
InReverseFilter: inReverseFilter,
WatchedOutPoints: req.WatchedOutPoints,
FoundExternal: foundExternal,
FoundInternal: foundInternal,
FoundOutPoints: foundOutPoints,
}
} | go | func NewBlockFilterer(params *chaincfg.Params,
req *FilterBlocksRequest) *BlockFilterer {
// Construct a reverse index by address string for the requested
// external addresses.
nExAddrs := len(req.ExternalAddrs)
exReverseFilter := make(map[string]waddrmgr.ScopedIndex, nExAddrs)
for scopedIndex, addr := range req.ExternalAddrs {
exReverseFilter[addr.EncodeAddress()] = scopedIndex
}
// Construct a reverse index by address string for the requested
// internal addresses.
nInAddrs := len(req.InternalAddrs)
inReverseFilter := make(map[string]waddrmgr.ScopedIndex, nInAddrs)
for scopedIndex, addr := range req.InternalAddrs {
inReverseFilter[addr.EncodeAddress()] = scopedIndex
}
foundExternal := make(map[waddrmgr.KeyScope]map[uint32]struct{})
foundInternal := make(map[waddrmgr.KeyScope]map[uint32]struct{})
foundOutPoints := make(map[wire.OutPoint]btcutil.Address)
return &BlockFilterer{
Params: params,
ExReverseFilter: exReverseFilter,
InReverseFilter: inReverseFilter,
WatchedOutPoints: req.WatchedOutPoints,
FoundExternal: foundExternal,
FoundInternal: foundInternal,
FoundOutPoints: foundOutPoints,
}
} | [
"func",
"NewBlockFilterer",
"(",
"params",
"*",
"chaincfg",
".",
"Params",
",",
"req",
"*",
"FilterBlocksRequest",
")",
"*",
"BlockFilterer",
"{",
"// Construct a reverse index by address string for the requested",
"// external addresses.",
"nExAddrs",
":=",
"len",
"(",
"req",
".",
"ExternalAddrs",
")",
"\n",
"exReverseFilter",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"waddrmgr",
".",
"ScopedIndex",
",",
"nExAddrs",
")",
"\n",
"for",
"scopedIndex",
",",
"addr",
":=",
"range",
"req",
".",
"ExternalAddrs",
"{",
"exReverseFilter",
"[",
"addr",
".",
"EncodeAddress",
"(",
")",
"]",
"=",
"scopedIndex",
"\n",
"}",
"\n\n",
"// Construct a reverse index by address string for the requested",
"// internal addresses.",
"nInAddrs",
":=",
"len",
"(",
"req",
".",
"InternalAddrs",
")",
"\n",
"inReverseFilter",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"waddrmgr",
".",
"ScopedIndex",
",",
"nInAddrs",
")",
"\n",
"for",
"scopedIndex",
",",
"addr",
":=",
"range",
"req",
".",
"InternalAddrs",
"{",
"inReverseFilter",
"[",
"addr",
".",
"EncodeAddress",
"(",
")",
"]",
"=",
"scopedIndex",
"\n",
"}",
"\n\n",
"foundExternal",
":=",
"make",
"(",
"map",
"[",
"waddrmgr",
".",
"KeyScope",
"]",
"map",
"[",
"uint32",
"]",
"struct",
"{",
"}",
")",
"\n",
"foundInternal",
":=",
"make",
"(",
"map",
"[",
"waddrmgr",
".",
"KeyScope",
"]",
"map",
"[",
"uint32",
"]",
"struct",
"{",
"}",
")",
"\n",
"foundOutPoints",
":=",
"make",
"(",
"map",
"[",
"wire",
".",
"OutPoint",
"]",
"btcutil",
".",
"Address",
")",
"\n\n",
"return",
"&",
"BlockFilterer",
"{",
"Params",
":",
"params",
",",
"ExReverseFilter",
":",
"exReverseFilter",
",",
"InReverseFilter",
":",
"inReverseFilter",
",",
"WatchedOutPoints",
":",
"req",
".",
"WatchedOutPoints",
",",
"FoundExternal",
":",
"foundExternal",
",",
"FoundInternal",
":",
"foundInternal",
",",
"FoundOutPoints",
":",
"foundOutPoints",
",",
"}",
"\n",
"}"
] | // NewBlockFilterer constructs the reverse indexes for the current set of
// external and internal addresses that we are searching for, and is used to
// scan successive blocks for addresses of interest. A particular block filter
// can be reused until the first call from `FitlerBlock` returns true. | [
"NewBlockFilterer",
"constructs",
"the",
"reverse",
"indexes",
"for",
"the",
"current",
"set",
"of",
"external",
"and",
"internal",
"addresses",
"that",
"we",
"are",
"searching",
"for",
"and",
"is",
"used",
"to",
"scan",
"successive",
"blocks",
"for",
"addresses",
"of",
"interest",
".",
"A",
"particular",
"block",
"filter",
"can",
"be",
"reused",
"until",
"the",
"first",
"call",
"from",
"FitlerBlock",
"returns",
"true",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/block_filterer.go#L69-L101 | train |
btcsuite/btcwallet | chain/block_filterer.go | FilterBlock | func (bf *BlockFilterer) FilterBlock(block *wire.MsgBlock) bool {
var hasRelevantTxns bool
for _, tx := range block.Transactions {
if bf.FilterTx(tx) {
bf.RelevantTxns = append(bf.RelevantTxns, tx)
hasRelevantTxns = true
}
}
return hasRelevantTxns
} | go | func (bf *BlockFilterer) FilterBlock(block *wire.MsgBlock) bool {
var hasRelevantTxns bool
for _, tx := range block.Transactions {
if bf.FilterTx(tx) {
bf.RelevantTxns = append(bf.RelevantTxns, tx)
hasRelevantTxns = true
}
}
return hasRelevantTxns
} | [
"func",
"(",
"bf",
"*",
"BlockFilterer",
")",
"FilterBlock",
"(",
"block",
"*",
"wire",
".",
"MsgBlock",
")",
"bool",
"{",
"var",
"hasRelevantTxns",
"bool",
"\n",
"for",
"_",
",",
"tx",
":=",
"range",
"block",
".",
"Transactions",
"{",
"if",
"bf",
".",
"FilterTx",
"(",
"tx",
")",
"{",
"bf",
".",
"RelevantTxns",
"=",
"append",
"(",
"bf",
".",
"RelevantTxns",
",",
"tx",
")",
"\n",
"hasRelevantTxns",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"hasRelevantTxns",
"\n",
"}"
] | // FilterBlock parses all txns in the provided block, searching for any that
// contain addresses of interest in either the external or internal reverse
// filters. This method return true iff the block contains a non-zero number of
// addresses of interest, or a transaction in the block spends from outpoints
// controlled by the wallet. | [
"FilterBlock",
"parses",
"all",
"txns",
"in",
"the",
"provided",
"block",
"searching",
"for",
"any",
"that",
"contain",
"addresses",
"of",
"interest",
"in",
"either",
"the",
"external",
"or",
"internal",
"reverse",
"filters",
".",
"This",
"method",
"return",
"true",
"iff",
"the",
"block",
"contains",
"a",
"non",
"-",
"zero",
"number",
"of",
"addresses",
"of",
"interest",
"or",
"a",
"transaction",
"in",
"the",
"block",
"spends",
"from",
"outpoints",
"controlled",
"by",
"the",
"wallet",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/block_filterer.go#L108-L118 | train |
btcsuite/btcwallet | chain/block_filterer.go | FilterTx | func (bf *BlockFilterer) FilterTx(tx *wire.MsgTx) bool {
var isRelevant bool
// First, check the inputs to this transaction to see if they spend any
// inputs belonging to the wallet. In addition to checking
// WatchedOutPoints, we also check FoundOutPoints, in case a txn spends
// from an outpoint created in the same block.
for _, in := range tx.TxIn {
if _, ok := bf.WatchedOutPoints[in.PreviousOutPoint]; ok {
isRelevant = true
}
if _, ok := bf.FoundOutPoints[in.PreviousOutPoint]; ok {
isRelevant = true
}
}
// Now, parse all of the outputs created by this transactions, and see
// if they contain any addresses known the wallet using our reverse
// indexes for both external and internal addresses. If a new output is
// found, we will add the outpoint to our set of FoundOutPoints.
for i, out := range tx.TxOut {
_, addrs, _, err := txscript.ExtractPkScriptAddrs(
out.PkScript, bf.Params,
)
if err != nil {
log.Warnf("Could not parse output script in %s:%d: %v",
tx.TxHash(), i, err)
continue
}
if !bf.FilterOutputAddrs(addrs) {
continue
}
// If we've reached this point, then the output contains an
// address of interest.
isRelevant = true
// Record the outpoint that containing the address in our set of
// found outpoints, so that the caller can update its global
// set of watched outpoints.
outPoint := wire.OutPoint{
Hash: *btcutil.NewTx(tx).Hash(),
Index: uint32(i),
}
bf.FoundOutPoints[outPoint] = addrs[0]
}
return isRelevant
} | go | func (bf *BlockFilterer) FilterTx(tx *wire.MsgTx) bool {
var isRelevant bool
// First, check the inputs to this transaction to see if they spend any
// inputs belonging to the wallet. In addition to checking
// WatchedOutPoints, we also check FoundOutPoints, in case a txn spends
// from an outpoint created in the same block.
for _, in := range tx.TxIn {
if _, ok := bf.WatchedOutPoints[in.PreviousOutPoint]; ok {
isRelevant = true
}
if _, ok := bf.FoundOutPoints[in.PreviousOutPoint]; ok {
isRelevant = true
}
}
// Now, parse all of the outputs created by this transactions, and see
// if they contain any addresses known the wallet using our reverse
// indexes for both external and internal addresses. If a new output is
// found, we will add the outpoint to our set of FoundOutPoints.
for i, out := range tx.TxOut {
_, addrs, _, err := txscript.ExtractPkScriptAddrs(
out.PkScript, bf.Params,
)
if err != nil {
log.Warnf("Could not parse output script in %s:%d: %v",
tx.TxHash(), i, err)
continue
}
if !bf.FilterOutputAddrs(addrs) {
continue
}
// If we've reached this point, then the output contains an
// address of interest.
isRelevant = true
// Record the outpoint that containing the address in our set of
// found outpoints, so that the caller can update its global
// set of watched outpoints.
outPoint := wire.OutPoint{
Hash: *btcutil.NewTx(tx).Hash(),
Index: uint32(i),
}
bf.FoundOutPoints[outPoint] = addrs[0]
}
return isRelevant
} | [
"func",
"(",
"bf",
"*",
"BlockFilterer",
")",
"FilterTx",
"(",
"tx",
"*",
"wire",
".",
"MsgTx",
")",
"bool",
"{",
"var",
"isRelevant",
"bool",
"\n\n",
"// First, check the inputs to this transaction to see if they spend any",
"// inputs belonging to the wallet. In addition to checking",
"// WatchedOutPoints, we also check FoundOutPoints, in case a txn spends",
"// from an outpoint created in the same block.",
"for",
"_",
",",
"in",
":=",
"range",
"tx",
".",
"TxIn",
"{",
"if",
"_",
",",
"ok",
":=",
"bf",
".",
"WatchedOutPoints",
"[",
"in",
".",
"PreviousOutPoint",
"]",
";",
"ok",
"{",
"isRelevant",
"=",
"true",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"bf",
".",
"FoundOutPoints",
"[",
"in",
".",
"PreviousOutPoint",
"]",
";",
"ok",
"{",
"isRelevant",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Now, parse all of the outputs created by this transactions, and see",
"// if they contain any addresses known the wallet using our reverse",
"// indexes for both external and internal addresses. If a new output is",
"// found, we will add the outpoint to our set of FoundOutPoints.",
"for",
"i",
",",
"out",
":=",
"range",
"tx",
".",
"TxOut",
"{",
"_",
",",
"addrs",
",",
"_",
",",
"err",
":=",
"txscript",
".",
"ExtractPkScriptAddrs",
"(",
"out",
".",
"PkScript",
",",
"bf",
".",
"Params",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"tx",
".",
"TxHash",
"(",
")",
",",
"i",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"if",
"!",
"bf",
".",
"FilterOutputAddrs",
"(",
"addrs",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"// If we've reached this point, then the output contains an",
"// address of interest.",
"isRelevant",
"=",
"true",
"\n\n",
"// Record the outpoint that containing the address in our set of",
"// found outpoints, so that the caller can update its global",
"// set of watched outpoints.",
"outPoint",
":=",
"wire",
".",
"OutPoint",
"{",
"Hash",
":",
"*",
"btcutil",
".",
"NewTx",
"(",
"tx",
")",
".",
"Hash",
"(",
")",
",",
"Index",
":",
"uint32",
"(",
"i",
")",
",",
"}",
"\n\n",
"bf",
".",
"FoundOutPoints",
"[",
"outPoint",
"]",
"=",
"addrs",
"[",
"0",
"]",
"\n",
"}",
"\n\n",
"return",
"isRelevant",
"\n",
"}"
] | // FilterTx scans all txouts in the provided txn, testing to see if any found
// addresses match those contained within the external or internal reverse
// indexes. This method returns true iff the txn contains a non-zero number of
// addresses of interest, or the transaction spends from an outpoint that
// belongs to the wallet. | [
"FilterTx",
"scans",
"all",
"txouts",
"in",
"the",
"provided",
"txn",
"testing",
"to",
"see",
"if",
"any",
"found",
"addresses",
"match",
"those",
"contained",
"within",
"the",
"external",
"or",
"internal",
"reverse",
"indexes",
".",
"This",
"method",
"returns",
"true",
"iff",
"the",
"txn",
"contains",
"a",
"non",
"-",
"zero",
"number",
"of",
"addresses",
"of",
"interest",
"or",
"the",
"transaction",
"spends",
"from",
"an",
"outpoint",
"that",
"belongs",
"to",
"the",
"wallet",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/block_filterer.go#L125-L175 | train |
btcsuite/btcwallet | chain/block_filterer.go | FilterOutputAddrs | func (bf *BlockFilterer) FilterOutputAddrs(addrs []btcutil.Address) bool {
var isRelevant bool
for _, addr := range addrs {
addrStr := addr.EncodeAddress()
if scopedIndex, ok := bf.ExReverseFilter[addrStr]; ok {
bf.foundExternal(scopedIndex)
isRelevant = true
}
if scopedIndex, ok := bf.InReverseFilter[addrStr]; ok {
bf.foundInternal(scopedIndex)
isRelevant = true
}
}
return isRelevant
} | go | func (bf *BlockFilterer) FilterOutputAddrs(addrs []btcutil.Address) bool {
var isRelevant bool
for _, addr := range addrs {
addrStr := addr.EncodeAddress()
if scopedIndex, ok := bf.ExReverseFilter[addrStr]; ok {
bf.foundExternal(scopedIndex)
isRelevant = true
}
if scopedIndex, ok := bf.InReverseFilter[addrStr]; ok {
bf.foundInternal(scopedIndex)
isRelevant = true
}
}
return isRelevant
} | [
"func",
"(",
"bf",
"*",
"BlockFilterer",
")",
"FilterOutputAddrs",
"(",
"addrs",
"[",
"]",
"btcutil",
".",
"Address",
")",
"bool",
"{",
"var",
"isRelevant",
"bool",
"\n",
"for",
"_",
",",
"addr",
":=",
"range",
"addrs",
"{",
"addrStr",
":=",
"addr",
".",
"EncodeAddress",
"(",
")",
"\n",
"if",
"scopedIndex",
",",
"ok",
":=",
"bf",
".",
"ExReverseFilter",
"[",
"addrStr",
"]",
";",
"ok",
"{",
"bf",
".",
"foundExternal",
"(",
"scopedIndex",
")",
"\n",
"isRelevant",
"=",
"true",
"\n",
"}",
"\n",
"if",
"scopedIndex",
",",
"ok",
":=",
"bf",
".",
"InReverseFilter",
"[",
"addrStr",
"]",
";",
"ok",
"{",
"bf",
".",
"foundInternal",
"(",
"scopedIndex",
")",
"\n",
"isRelevant",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"isRelevant",
"\n",
"}"
] | // FilterOutputAddrs tests the set of addresses against the block filterer's
// external and internal reverse address indexes. If any are found, they are
// added to set of external and internal found addresses, respectively. This
// method returns true iff a non-zero number of the provided addresses are of
// interest. | [
"FilterOutputAddrs",
"tests",
"the",
"set",
"of",
"addresses",
"against",
"the",
"block",
"filterer",
"s",
"external",
"and",
"internal",
"reverse",
"address",
"indexes",
".",
"If",
"any",
"are",
"found",
"they",
"are",
"added",
"to",
"set",
"of",
"external",
"and",
"internal",
"found",
"addresses",
"respectively",
".",
"This",
"method",
"returns",
"true",
"iff",
"a",
"non",
"-",
"zero",
"number",
"of",
"the",
"provided",
"addresses",
"are",
"of",
"interest",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/block_filterer.go#L182-L197 | train |
btcsuite/btcwallet | chain/block_filterer.go | foundExternal | func (bf *BlockFilterer) foundExternal(scopedIndex waddrmgr.ScopedIndex) {
if _, ok := bf.FoundExternal[scopedIndex.Scope]; !ok {
bf.FoundExternal[scopedIndex.Scope] = make(map[uint32]struct{})
}
bf.FoundExternal[scopedIndex.Scope][scopedIndex.Index] = struct{}{}
} | go | func (bf *BlockFilterer) foundExternal(scopedIndex waddrmgr.ScopedIndex) {
if _, ok := bf.FoundExternal[scopedIndex.Scope]; !ok {
bf.FoundExternal[scopedIndex.Scope] = make(map[uint32]struct{})
}
bf.FoundExternal[scopedIndex.Scope][scopedIndex.Index] = struct{}{}
} | [
"func",
"(",
"bf",
"*",
"BlockFilterer",
")",
"foundExternal",
"(",
"scopedIndex",
"waddrmgr",
".",
"ScopedIndex",
")",
"{",
"if",
"_",
",",
"ok",
":=",
"bf",
".",
"FoundExternal",
"[",
"scopedIndex",
".",
"Scope",
"]",
";",
"!",
"ok",
"{",
"bf",
".",
"FoundExternal",
"[",
"scopedIndex",
".",
"Scope",
"]",
"=",
"make",
"(",
"map",
"[",
"uint32",
"]",
"struct",
"{",
"}",
")",
"\n",
"}",
"\n",
"bf",
".",
"FoundExternal",
"[",
"scopedIndex",
".",
"Scope",
"]",
"[",
"scopedIndex",
".",
"Index",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}"
] | // foundExternal marks the scoped index as found within the block filterer's
// FoundExternal map. If this the first index found for a particular scope, the
// scope's second layer map will be initialized before marking the index. | [
"foundExternal",
"marks",
"the",
"scoped",
"index",
"as",
"found",
"within",
"the",
"block",
"filterer",
"s",
"FoundExternal",
"map",
".",
"If",
"this",
"the",
"first",
"index",
"found",
"for",
"a",
"particular",
"scope",
"the",
"scope",
"s",
"second",
"layer",
"map",
"will",
"be",
"initialized",
"before",
"marking",
"the",
"index",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/block_filterer.go#L202-L207 | train |
btcsuite/btcwallet | chain/block_filterer.go | foundInternal | func (bf *BlockFilterer) foundInternal(scopedIndex waddrmgr.ScopedIndex) {
if _, ok := bf.FoundInternal[scopedIndex.Scope]; !ok {
bf.FoundInternal[scopedIndex.Scope] = make(map[uint32]struct{})
}
bf.FoundInternal[scopedIndex.Scope][scopedIndex.Index] = struct{}{}
} | go | func (bf *BlockFilterer) foundInternal(scopedIndex waddrmgr.ScopedIndex) {
if _, ok := bf.FoundInternal[scopedIndex.Scope]; !ok {
bf.FoundInternal[scopedIndex.Scope] = make(map[uint32]struct{})
}
bf.FoundInternal[scopedIndex.Scope][scopedIndex.Index] = struct{}{}
} | [
"func",
"(",
"bf",
"*",
"BlockFilterer",
")",
"foundInternal",
"(",
"scopedIndex",
"waddrmgr",
".",
"ScopedIndex",
")",
"{",
"if",
"_",
",",
"ok",
":=",
"bf",
".",
"FoundInternal",
"[",
"scopedIndex",
".",
"Scope",
"]",
";",
"!",
"ok",
"{",
"bf",
".",
"FoundInternal",
"[",
"scopedIndex",
".",
"Scope",
"]",
"=",
"make",
"(",
"map",
"[",
"uint32",
"]",
"struct",
"{",
"}",
")",
"\n",
"}",
"\n",
"bf",
".",
"FoundInternal",
"[",
"scopedIndex",
".",
"Scope",
"]",
"[",
"scopedIndex",
".",
"Index",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}"
] | // foundInternal marks the scoped index as found within the block filterer's
// FoundInternal map. If this the first index found for a particular scope, the
// scope's second layer map will be initialized before marking the index. | [
"foundInternal",
"marks",
"the",
"scoped",
"index",
"as",
"found",
"within",
"the",
"block",
"filterer",
"s",
"FoundInternal",
"map",
".",
"If",
"this",
"the",
"first",
"index",
"found",
"for",
"a",
"particular",
"scope",
"the",
"scope",
"s",
"second",
"layer",
"map",
"will",
"be",
"initialized",
"before",
"marking",
"the",
"index",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/block_filterer.go#L212-L217 | train |
btcsuite/btcwallet | rpc/rpcserver/server.go | StartWalletService | func StartWalletService(server *grpc.Server, wallet *wallet.Wallet) {
service := &walletServer{wallet}
pb.RegisterWalletServiceServer(server, service)
} | go | func StartWalletService(server *grpc.Server, wallet *wallet.Wallet) {
service := &walletServer{wallet}
pb.RegisterWalletServiceServer(server, service)
} | [
"func",
"StartWalletService",
"(",
"server",
"*",
"grpc",
".",
"Server",
",",
"wallet",
"*",
"wallet",
".",
"Wallet",
")",
"{",
"service",
":=",
"&",
"walletServer",
"{",
"wallet",
"}",
"\n",
"pb",
".",
"RegisterWalletServiceServer",
"(",
"server",
",",
"service",
")",
"\n",
"}"
] | // StartWalletService creates an implementation of the WalletService and
// registers it with the gRPC server. | [
"StartWalletService",
"creates",
"an",
"implementation",
"of",
"the",
"WalletService",
"and",
"registers",
"it",
"with",
"the",
"gRPC",
"server",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/rpcserver/server.go#L136-L139 | train |
btcsuite/btcwallet | rpc/rpcserver/server.go | StartWalletLoaderService | func StartWalletLoaderService(server *grpc.Server, loader *wallet.Loader,
activeNet *netparams.Params) {
service := &loaderServer{loader: loader, activeNet: activeNet}
pb.RegisterWalletLoaderServiceServer(server, service)
} | go | func StartWalletLoaderService(server *grpc.Server, loader *wallet.Loader,
activeNet *netparams.Params) {
service := &loaderServer{loader: loader, activeNet: activeNet}
pb.RegisterWalletLoaderServiceServer(server, service)
} | [
"func",
"StartWalletLoaderService",
"(",
"server",
"*",
"grpc",
".",
"Server",
",",
"loader",
"*",
"wallet",
".",
"Loader",
",",
"activeNet",
"*",
"netparams",
".",
"Params",
")",
"{",
"service",
":=",
"&",
"loaderServer",
"{",
"loader",
":",
"loader",
",",
"activeNet",
":",
"activeNet",
"}",
"\n",
"pb",
".",
"RegisterWalletLoaderServiceServer",
"(",
"server",
",",
"service",
")",
"\n",
"}"
] | // StartWalletLoaderService creates an implementation of the WalletLoaderService
// and registers it with the gRPC server. | [
"StartWalletLoaderService",
"creates",
"an",
"implementation",
"of",
"the",
"WalletLoaderService",
"and",
"registers",
"it",
"with",
"the",
"gRPC",
"server",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/rpcserver/server.go#L704-L709 | train |
btcsuite/btcwallet | rpc/legacyrpc/server.go | jsonAuthFail | func jsonAuthFail(w http.ResponseWriter) {
w.Header().Add("WWW-Authenticate", `Basic realm="btcwallet RPC"`)
http.Error(w, "401 Unauthorized.", http.StatusUnauthorized)
} | go | func jsonAuthFail(w http.ResponseWriter) {
w.Header().Add("WWW-Authenticate", `Basic realm="btcwallet RPC"`)
http.Error(w, "401 Unauthorized.", http.StatusUnauthorized)
} | [
"func",
"jsonAuthFail",
"(",
"w",
"http",
".",
"ResponseWriter",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"",
"\"",
",",
"`Basic realm=\"btcwallet RPC\"`",
")",
"\n",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusUnauthorized",
")",
"\n",
"}"
] | // jsonAuthFail sends a message back to the client if the http auth is rejected. | [
"jsonAuthFail",
"sends",
"a",
"message",
"back",
"to",
"the",
"client",
"if",
"the",
"http",
"auth",
"is",
"rejected",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/server.go#L83-L86 | train |
btcsuite/btcwallet | rpc/legacyrpc/server.go | NewServer | func NewServer(opts *Options, walletLoader *wallet.Loader, listeners []net.Listener) *Server {
serveMux := http.NewServeMux()
const rpcAuthTimeoutSeconds = 10
server := &Server{
httpServer: http.Server{
Handler: serveMux,
// Timeout connections which don't complete the initial
// handshake within the allowed timeframe.
ReadTimeout: time.Second * rpcAuthTimeoutSeconds,
},
walletLoader: walletLoader,
maxPostClients: opts.MaxPOSTClients,
maxWebsocketClients: opts.MaxWebsocketClients,
listeners: listeners,
// A hash of the HTTP basic auth string is used for a constant
// time comparison.
authsha: sha256.Sum256(httpBasicAuth(opts.Username, opts.Password)),
upgrader: websocket.Upgrader{
// Allow all origins.
CheckOrigin: func(r *http.Request) bool { return true },
},
quit: make(chan struct{}),
requestShutdownChan: make(chan struct{}, 1),
}
serveMux.Handle("/", throttledFn(opts.MaxPOSTClients,
func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Connection", "close")
w.Header().Set("Content-Type", "application/json")
r.Close = true
if err := server.checkAuthHeader(r); err != nil {
log.Warnf("Unauthorized client connection attempt")
jsonAuthFail(w)
return
}
server.wg.Add(1)
server.postClientRPC(w, r)
server.wg.Done()
}))
serveMux.Handle("/ws", throttledFn(opts.MaxWebsocketClients,
func(w http.ResponseWriter, r *http.Request) {
authenticated := false
switch server.checkAuthHeader(r) {
case nil:
authenticated = true
case ErrNoAuth:
// nothing
default:
// If auth was supplied but incorrect, rather than simply
// being missing, immediately terminate the connection.
log.Warnf("Disconnecting improperly authorized " +
"websocket client")
jsonAuthFail(w)
return
}
conn, err := server.upgrader.Upgrade(w, r, nil)
if err != nil {
log.Warnf("Cannot websocket upgrade client %s: %v",
r.RemoteAddr, err)
return
}
wsc := newWebsocketClient(conn, authenticated, r.RemoteAddr)
server.websocketClientRPC(wsc)
}))
for _, lis := range listeners {
server.serve(lis)
}
return server
} | go | func NewServer(opts *Options, walletLoader *wallet.Loader, listeners []net.Listener) *Server {
serveMux := http.NewServeMux()
const rpcAuthTimeoutSeconds = 10
server := &Server{
httpServer: http.Server{
Handler: serveMux,
// Timeout connections which don't complete the initial
// handshake within the allowed timeframe.
ReadTimeout: time.Second * rpcAuthTimeoutSeconds,
},
walletLoader: walletLoader,
maxPostClients: opts.MaxPOSTClients,
maxWebsocketClients: opts.MaxWebsocketClients,
listeners: listeners,
// A hash of the HTTP basic auth string is used for a constant
// time comparison.
authsha: sha256.Sum256(httpBasicAuth(opts.Username, opts.Password)),
upgrader: websocket.Upgrader{
// Allow all origins.
CheckOrigin: func(r *http.Request) bool { return true },
},
quit: make(chan struct{}),
requestShutdownChan: make(chan struct{}, 1),
}
serveMux.Handle("/", throttledFn(opts.MaxPOSTClients,
func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Connection", "close")
w.Header().Set("Content-Type", "application/json")
r.Close = true
if err := server.checkAuthHeader(r); err != nil {
log.Warnf("Unauthorized client connection attempt")
jsonAuthFail(w)
return
}
server.wg.Add(1)
server.postClientRPC(w, r)
server.wg.Done()
}))
serveMux.Handle("/ws", throttledFn(opts.MaxWebsocketClients,
func(w http.ResponseWriter, r *http.Request) {
authenticated := false
switch server.checkAuthHeader(r) {
case nil:
authenticated = true
case ErrNoAuth:
// nothing
default:
// If auth was supplied but incorrect, rather than simply
// being missing, immediately terminate the connection.
log.Warnf("Disconnecting improperly authorized " +
"websocket client")
jsonAuthFail(w)
return
}
conn, err := server.upgrader.Upgrade(w, r, nil)
if err != nil {
log.Warnf("Cannot websocket upgrade client %s: %v",
r.RemoteAddr, err)
return
}
wsc := newWebsocketClient(conn, authenticated, r.RemoteAddr)
server.websocketClientRPC(wsc)
}))
for _, lis := range listeners {
server.serve(lis)
}
return server
} | [
"func",
"NewServer",
"(",
"opts",
"*",
"Options",
",",
"walletLoader",
"*",
"wallet",
".",
"Loader",
",",
"listeners",
"[",
"]",
"net",
".",
"Listener",
")",
"*",
"Server",
"{",
"serveMux",
":=",
"http",
".",
"NewServeMux",
"(",
")",
"\n",
"const",
"rpcAuthTimeoutSeconds",
"=",
"10",
"\n\n",
"server",
":=",
"&",
"Server",
"{",
"httpServer",
":",
"http",
".",
"Server",
"{",
"Handler",
":",
"serveMux",
",",
"// Timeout connections which don't complete the initial",
"// handshake within the allowed timeframe.",
"ReadTimeout",
":",
"time",
".",
"Second",
"*",
"rpcAuthTimeoutSeconds",
",",
"}",
",",
"walletLoader",
":",
"walletLoader",
",",
"maxPostClients",
":",
"opts",
".",
"MaxPOSTClients",
",",
"maxWebsocketClients",
":",
"opts",
".",
"MaxWebsocketClients",
",",
"listeners",
":",
"listeners",
",",
"// A hash of the HTTP basic auth string is used for a constant",
"// time comparison.",
"authsha",
":",
"sha256",
".",
"Sum256",
"(",
"httpBasicAuth",
"(",
"opts",
".",
"Username",
",",
"opts",
".",
"Password",
")",
")",
",",
"upgrader",
":",
"websocket",
".",
"Upgrader",
"{",
"// Allow all origins.",
"CheckOrigin",
":",
"func",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"bool",
"{",
"return",
"true",
"}",
",",
"}",
",",
"quit",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"requestShutdownChan",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"1",
")",
",",
"}",
"\n\n",
"serveMux",
".",
"Handle",
"(",
"\"",
"\"",
",",
"throttledFn",
"(",
"opts",
".",
"MaxPOSTClients",
",",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"r",
".",
"Close",
"=",
"true",
"\n\n",
"if",
"err",
":=",
"server",
".",
"checkAuthHeader",
"(",
"r",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
")",
"\n",
"jsonAuthFail",
"(",
"w",
")",
"\n",
"return",
"\n",
"}",
"\n",
"server",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"server",
".",
"postClientRPC",
"(",
"w",
",",
"r",
")",
"\n",
"server",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"}",
")",
")",
"\n\n",
"serveMux",
".",
"Handle",
"(",
"\"",
"\"",
",",
"throttledFn",
"(",
"opts",
".",
"MaxWebsocketClients",
",",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"authenticated",
":=",
"false",
"\n",
"switch",
"server",
".",
"checkAuthHeader",
"(",
"r",
")",
"{",
"case",
"nil",
":",
"authenticated",
"=",
"true",
"\n",
"case",
"ErrNoAuth",
":",
"// nothing",
"default",
":",
"// If auth was supplied but incorrect, rather than simply",
"// being missing, immediately terminate the connection.",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
")",
"\n",
"jsonAuthFail",
"(",
"w",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"conn",
",",
"err",
":=",
"server",
".",
"upgrader",
".",
"Upgrade",
"(",
"w",
",",
"r",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"r",
".",
"RemoteAddr",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"wsc",
":=",
"newWebsocketClient",
"(",
"conn",
",",
"authenticated",
",",
"r",
".",
"RemoteAddr",
")",
"\n",
"server",
".",
"websocketClientRPC",
"(",
"wsc",
")",
"\n",
"}",
")",
")",
"\n\n",
"for",
"_",
",",
"lis",
":=",
"range",
"listeners",
"{",
"server",
".",
"serve",
"(",
"lis",
")",
"\n",
"}",
"\n\n",
"return",
"server",
"\n",
"}"
] | // NewServer creates a new server for serving legacy RPC client connections,
// both HTTP POST and websocket. | [
"NewServer",
"creates",
"a",
"new",
"server",
"for",
"serving",
"legacy",
"RPC",
"client",
"connections",
"both",
"HTTP",
"POST",
"and",
"websocket",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/server.go#L90-L165 | train |
btcsuite/btcwallet | rpc/legacyrpc/server.go | serve | func (s *Server) serve(lis net.Listener) {
s.wg.Add(1)
go func() {
log.Infof("Listening on %s", lis.Addr())
err := s.httpServer.Serve(lis)
log.Tracef("Finished serving RPC: %v", err)
s.wg.Done()
}()
} | go | func (s *Server) serve(lis net.Listener) {
s.wg.Add(1)
go func() {
log.Infof("Listening on %s", lis.Addr())
err := s.httpServer.Serve(lis)
log.Tracef("Finished serving RPC: %v", err)
s.wg.Done()
}()
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"serve",
"(",
"lis",
"net",
".",
"Listener",
")",
"{",
"s",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"lis",
".",
"Addr",
"(",
")",
")",
"\n",
"err",
":=",
"s",
".",
"httpServer",
".",
"Serve",
"(",
"lis",
")",
"\n",
"log",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"s",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"}"
] | // serve serves HTTP POST and websocket RPC for the legacy JSON-RPC RPC server.
// This function does not block on lis.Accept. | [
"serve",
"serves",
"HTTP",
"POST",
"and",
"websocket",
"RPC",
"for",
"the",
"legacy",
"JSON",
"-",
"RPC",
"RPC",
"server",
".",
"This",
"function",
"does",
"not",
"block",
"on",
"lis",
".",
"Accept",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/server.go#L189-L197 | train |
btcsuite/btcwallet | rpc/legacyrpc/server.go | RegisterWallet | func (s *Server) RegisterWallet(w *wallet.Wallet) {
s.handlerMu.Lock()
s.wallet = w
s.handlerMu.Unlock()
} | go | func (s *Server) RegisterWallet(w *wallet.Wallet) {
s.handlerMu.Lock()
s.wallet = w
s.handlerMu.Unlock()
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"RegisterWallet",
"(",
"w",
"*",
"wallet",
".",
"Wallet",
")",
"{",
"s",
".",
"handlerMu",
".",
"Lock",
"(",
")",
"\n",
"s",
".",
"wallet",
"=",
"w",
"\n",
"s",
".",
"handlerMu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // RegisterWallet associates the legacy RPC server with the wallet. This
// function must be called before any wallet RPCs can be called by clients. | [
"RegisterWallet",
"associates",
"the",
"legacy",
"RPC",
"server",
"with",
"the",
"wallet",
".",
"This",
"function",
"must",
"be",
"called",
"before",
"any",
"wallet",
"RPCs",
"can",
"be",
"called",
"by",
"clients",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/server.go#L201-L205 | train |
btcsuite/btcwallet | rpc/legacyrpc/server.go | Stop | func (s *Server) Stop() {
s.quitMtx.Lock()
select {
case <-s.quit:
s.quitMtx.Unlock()
return
default:
}
// Stop the connected wallet and chain server, if any.
s.handlerMu.Lock()
wallet := s.wallet
chainClient := s.chainClient
s.handlerMu.Unlock()
if wallet != nil {
wallet.Stop()
}
if chainClient != nil {
chainClient.Stop()
}
// Stop all the listeners.
for _, listener := range s.listeners {
err := listener.Close()
if err != nil {
log.Errorf("Cannot close listener `%s`: %v",
listener.Addr(), err)
}
}
// Signal the remaining goroutines to stop.
close(s.quit)
s.quitMtx.Unlock()
// First wait for the wallet and chain server to stop, if they
// were ever set.
if wallet != nil {
wallet.WaitForShutdown()
}
if chainClient != nil {
chainClient.WaitForShutdown()
}
// Wait for all remaining goroutines to exit.
s.wg.Wait()
} | go | func (s *Server) Stop() {
s.quitMtx.Lock()
select {
case <-s.quit:
s.quitMtx.Unlock()
return
default:
}
// Stop the connected wallet and chain server, if any.
s.handlerMu.Lock()
wallet := s.wallet
chainClient := s.chainClient
s.handlerMu.Unlock()
if wallet != nil {
wallet.Stop()
}
if chainClient != nil {
chainClient.Stop()
}
// Stop all the listeners.
for _, listener := range s.listeners {
err := listener.Close()
if err != nil {
log.Errorf("Cannot close listener `%s`: %v",
listener.Addr(), err)
}
}
// Signal the remaining goroutines to stop.
close(s.quit)
s.quitMtx.Unlock()
// First wait for the wallet and chain server to stop, if they
// were ever set.
if wallet != nil {
wallet.WaitForShutdown()
}
if chainClient != nil {
chainClient.WaitForShutdown()
}
// Wait for all remaining goroutines to exit.
s.wg.Wait()
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"Stop",
"(",
")",
"{",
"s",
".",
"quitMtx",
".",
"Lock",
"(",
")",
"\n",
"select",
"{",
"case",
"<-",
"s",
".",
"quit",
":",
"s",
".",
"quitMtx",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"default",
":",
"}",
"\n\n",
"// Stop the connected wallet and chain server, if any.",
"s",
".",
"handlerMu",
".",
"Lock",
"(",
")",
"\n",
"wallet",
":=",
"s",
".",
"wallet",
"\n",
"chainClient",
":=",
"s",
".",
"chainClient",
"\n",
"s",
".",
"handlerMu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"wallet",
"!=",
"nil",
"{",
"wallet",
".",
"Stop",
"(",
")",
"\n",
"}",
"\n",
"if",
"chainClient",
"!=",
"nil",
"{",
"chainClient",
".",
"Stop",
"(",
")",
"\n",
"}",
"\n\n",
"// Stop all the listeners.",
"for",
"_",
",",
"listener",
":=",
"range",
"s",
".",
"listeners",
"{",
"err",
":=",
"listener",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"listener",
".",
"Addr",
"(",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Signal the remaining goroutines to stop.",
"close",
"(",
"s",
".",
"quit",
")",
"\n",
"s",
".",
"quitMtx",
".",
"Unlock",
"(",
")",
"\n\n",
"// First wait for the wallet and chain server to stop, if they",
"// were ever set.",
"if",
"wallet",
"!=",
"nil",
"{",
"wallet",
".",
"WaitForShutdown",
"(",
")",
"\n",
"}",
"\n",
"if",
"chainClient",
"!=",
"nil",
"{",
"chainClient",
".",
"WaitForShutdown",
"(",
")",
"\n",
"}",
"\n\n",
"// Wait for all remaining goroutines to exit.",
"s",
".",
"wg",
".",
"Wait",
"(",
")",
"\n",
"}"
] | // Stop gracefully shuts down the rpc server by stopping and disconnecting all
// clients, disconnecting the chain server connection, and closing the wallet's
// account files. This blocks until shutdown completes. | [
"Stop",
"gracefully",
"shuts",
"down",
"the",
"rpc",
"server",
"by",
"stopping",
"and",
"disconnecting",
"all",
"clients",
"disconnecting",
"the",
"chain",
"server",
"connection",
"and",
"closing",
"the",
"wallet",
"s",
"account",
"files",
".",
"This",
"blocks",
"until",
"shutdown",
"completes",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/server.go#L210-L255 | train |
btcsuite/btcwallet | rpc/legacyrpc/server.go | SetChainServer | func (s *Server) SetChainServer(chainClient chain.Interface) {
s.handlerMu.Lock()
s.chainClient = chainClient
s.handlerMu.Unlock()
} | go | func (s *Server) SetChainServer(chainClient chain.Interface) {
s.handlerMu.Lock()
s.chainClient = chainClient
s.handlerMu.Unlock()
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"SetChainServer",
"(",
"chainClient",
"chain",
".",
"Interface",
")",
"{",
"s",
".",
"handlerMu",
".",
"Lock",
"(",
")",
"\n",
"s",
".",
"chainClient",
"=",
"chainClient",
"\n",
"s",
".",
"handlerMu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // SetChainServer sets the chain server client component needed to run a fully
// functional bitcoin wallet RPC server. This can be called to enable RPC
// passthrough even before a loaded wallet is set, but the wallet's RPC client
// is preferred. | [
"SetChainServer",
"sets",
"the",
"chain",
"server",
"client",
"component",
"needed",
"to",
"run",
"a",
"fully",
"functional",
"bitcoin",
"wallet",
"RPC",
"server",
".",
"This",
"can",
"be",
"called",
"to",
"enable",
"RPC",
"passthrough",
"even",
"before",
"a",
"loaded",
"wallet",
"is",
"set",
"but",
"the",
"wallet",
"s",
"RPC",
"client",
"is",
"preferred",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/server.go#L261-L265 | train |
btcsuite/btcwallet | rpc/legacyrpc/server.go | checkAuthHeader | func (s *Server) checkAuthHeader(r *http.Request) error {
authhdr := r.Header["Authorization"]
if len(authhdr) == 0 {
return ErrNoAuth
}
authsha := sha256.Sum256([]byte(authhdr[0]))
cmp := subtle.ConstantTimeCompare(authsha[:], s.authsha[:])
if cmp != 1 {
return errors.New("bad auth")
}
return nil
} | go | func (s *Server) checkAuthHeader(r *http.Request) error {
authhdr := r.Header["Authorization"]
if len(authhdr) == 0 {
return ErrNoAuth
}
authsha := sha256.Sum256([]byte(authhdr[0]))
cmp := subtle.ConstantTimeCompare(authsha[:], s.authsha[:])
if cmp != 1 {
return errors.New("bad auth")
}
return nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"checkAuthHeader",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"authhdr",
":=",
"r",
".",
"Header",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"len",
"(",
"authhdr",
")",
"==",
"0",
"{",
"return",
"ErrNoAuth",
"\n",
"}",
"\n\n",
"authsha",
":=",
"sha256",
".",
"Sum256",
"(",
"[",
"]",
"byte",
"(",
"authhdr",
"[",
"0",
"]",
")",
")",
"\n",
"cmp",
":=",
"subtle",
".",
"ConstantTimeCompare",
"(",
"authsha",
"[",
":",
"]",
",",
"s",
".",
"authsha",
"[",
":",
"]",
")",
"\n",
"if",
"cmp",
"!=",
"1",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // checkAuthHeader checks the HTTP Basic authentication supplied by a client
// in the HTTP request r. It errors with ErrNoAuth if the request does not
// contain the Authorization header, or another non-nil error if the
// authentication was provided but incorrect.
//
// This check is time-constant. | [
"checkAuthHeader",
"checks",
"the",
"HTTP",
"Basic",
"authentication",
"supplied",
"by",
"a",
"client",
"in",
"the",
"HTTP",
"request",
"r",
".",
"It",
"errors",
"with",
"ErrNoAuth",
"if",
"the",
"request",
"does",
"not",
"contain",
"the",
"Authorization",
"header",
"or",
"another",
"non",
"-",
"nil",
"error",
"if",
"the",
"authentication",
"was",
"provided",
"but",
"incorrect",
".",
"This",
"check",
"is",
"time",
"-",
"constant",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/server.go#L298-L310 | train |
btcsuite/btcwallet | rpc/legacyrpc/server.go | throttledFn | func throttledFn(threshold int64, f http.HandlerFunc) http.Handler {
return throttled(threshold, f)
} | go | func throttledFn(threshold int64, f http.HandlerFunc) http.Handler {
return throttled(threshold, f)
} | [
"func",
"throttledFn",
"(",
"threshold",
"int64",
",",
"f",
"http",
".",
"HandlerFunc",
")",
"http",
".",
"Handler",
"{",
"return",
"throttled",
"(",
"threshold",
",",
"f",
")",
"\n",
"}"
] | // throttledFn wraps an http.HandlerFunc with throttling of concurrent active
// clients by responding with an HTTP 429 when the threshold is crossed. | [
"throttledFn",
"wraps",
"an",
"http",
".",
"HandlerFunc",
"with",
"throttling",
"of",
"concurrent",
"active",
"clients",
"by",
"responding",
"with",
"an",
"HTTP",
"429",
"when",
"the",
"threshold",
"is",
"crossed",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/server.go#L314-L316 | train |
btcsuite/btcwallet | rpc/legacyrpc/server.go | throttled | func throttled(threshold int64, h http.Handler) http.Handler {
var active int64
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
current := atomic.AddInt64(&active, 1)
defer atomic.AddInt64(&active, -1)
if current-1 >= threshold {
log.Warnf("Reached threshold of %d concurrent active clients", threshold)
http.Error(w, "429 Too Many Requests", 429)
return
}
h.ServeHTTP(w, r)
})
} | go | func throttled(threshold int64, h http.Handler) http.Handler {
var active int64
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
current := atomic.AddInt64(&active, 1)
defer atomic.AddInt64(&active, -1)
if current-1 >= threshold {
log.Warnf("Reached threshold of %d concurrent active clients", threshold)
http.Error(w, "429 Too Many Requests", 429)
return
}
h.ServeHTTP(w, r)
})
} | [
"func",
"throttled",
"(",
"threshold",
"int64",
",",
"h",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"var",
"active",
"int64",
"\n\n",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"current",
":=",
"atomic",
".",
"AddInt64",
"(",
"&",
"active",
",",
"1",
")",
"\n",
"defer",
"atomic",
".",
"AddInt64",
"(",
"&",
"active",
",",
"-",
"1",
")",
"\n\n",
"if",
"current",
"-",
"1",
">=",
"threshold",
"{",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"threshold",
")",
"\n",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"429",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"h",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"}",
")",
"\n",
"}"
] | // throttled wraps an http.Handler with throttling of concurrent active
// clients by responding with an HTTP 429 when the threshold is crossed. | [
"throttled",
"wraps",
"an",
"http",
".",
"Handler",
"with",
"throttling",
"of",
"concurrent",
"active",
"clients",
"by",
"responding",
"with",
"an",
"HTTP",
"429",
"when",
"the",
"threshold",
"is",
"crossed",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/server.go#L320-L335 | train |
btcsuite/btcwallet | rpc/legacyrpc/server.go | sanitizeRequest | func sanitizeRequest(r *btcjson.Request) string {
// These are considered unsafe to log, so sanitize parameters.
switch r.Method {
case "encryptwallet", "importprivkey", "importwallet",
"signrawtransaction", "walletpassphrase",
"walletpassphrasechange":
return fmt.Sprintf(`{"id":%v,"method":"%s","params":SANITIZED %d parameters}`,
r.ID, r.Method, len(r.Params))
}
return fmt.Sprintf(`{"id":%v,"method":"%s","params":%v}`, r.ID,
r.Method, r.Params)
} | go | func sanitizeRequest(r *btcjson.Request) string {
// These are considered unsafe to log, so sanitize parameters.
switch r.Method {
case "encryptwallet", "importprivkey", "importwallet",
"signrawtransaction", "walletpassphrase",
"walletpassphrasechange":
return fmt.Sprintf(`{"id":%v,"method":"%s","params":SANITIZED %d parameters}`,
r.ID, r.Method, len(r.Params))
}
return fmt.Sprintf(`{"id":%v,"method":"%s","params":%v}`, r.ID,
r.Method, r.Params)
} | [
"func",
"sanitizeRequest",
"(",
"r",
"*",
"btcjson",
".",
"Request",
")",
"string",
"{",
"// These are considered unsafe to log, so sanitize parameters.",
"switch",
"r",
".",
"Method",
"{",
"case",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"`{\"id\":%v,\"method\":\"%s\",\"params\":SANITIZED %d parameters}`",
",",
"r",
".",
"ID",
",",
"r",
".",
"Method",
",",
"len",
"(",
"r",
".",
"Params",
")",
")",
"\n",
"}",
"\n\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"`{\"id\":%v,\"method\":\"%s\",\"params\":%v}`",
",",
"r",
".",
"ID",
",",
"r",
".",
"Method",
",",
"r",
".",
"Params",
")",
"\n",
"}"
] | // sanitizeRequest returns a sanitized string for the request which may be
// safely logged. It is intended to strip private keys, passphrases, and any
// other secrets from request parameters before they may be saved to a log file. | [
"sanitizeRequest",
"returns",
"a",
"sanitized",
"string",
"for",
"the",
"request",
"which",
"may",
"be",
"safely",
"logged",
".",
"It",
"is",
"intended",
"to",
"strip",
"private",
"keys",
"passphrases",
"and",
"any",
"other",
"secrets",
"from",
"request",
"parameters",
"before",
"they",
"may",
"be",
"saved",
"to",
"a",
"log",
"file",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/server.go#L340-L353 | train |
btcsuite/btcwallet | rpc/legacyrpc/server.go | websocketClientRPC | func (s *Server) websocketClientRPC(wsc *websocketClient) {
log.Infof("New websocket client %s", wsc.remoteAddr)
// Clear the read deadline set before the websocket hijacked
// the connection.
if err := wsc.conn.SetReadDeadline(time.Time{}); err != nil {
log.Warnf("Cannot remove read deadline: %v", err)
}
// WebsocketClientRead is intentionally not run with the waitgroup
// so it is ignored during shutdown. This is to prevent a hang during
// shutdown where the goroutine is blocked on a read of the
// websocket connection if the client is still connected.
go s.websocketClientRead(wsc)
s.wg.Add(2)
go s.websocketClientRespond(wsc)
go s.websocketClientSend(wsc)
<-wsc.quit
} | go | func (s *Server) websocketClientRPC(wsc *websocketClient) {
log.Infof("New websocket client %s", wsc.remoteAddr)
// Clear the read deadline set before the websocket hijacked
// the connection.
if err := wsc.conn.SetReadDeadline(time.Time{}); err != nil {
log.Warnf("Cannot remove read deadline: %v", err)
}
// WebsocketClientRead is intentionally not run with the waitgroup
// so it is ignored during shutdown. This is to prevent a hang during
// shutdown where the goroutine is blocked on a read of the
// websocket connection if the client is still connected.
go s.websocketClientRead(wsc)
s.wg.Add(2)
go s.websocketClientRespond(wsc)
go s.websocketClientSend(wsc)
<-wsc.quit
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"websocketClientRPC",
"(",
"wsc",
"*",
"websocketClient",
")",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"wsc",
".",
"remoteAddr",
")",
"\n\n",
"// Clear the read deadline set before the websocket hijacked",
"// the connection.",
"if",
"err",
":=",
"wsc",
".",
"conn",
".",
"SetReadDeadline",
"(",
"time",
".",
"Time",
"{",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// WebsocketClientRead is intentionally not run with the waitgroup",
"// so it is ignored during shutdown. This is to prevent a hang during",
"// shutdown where the goroutine is blocked on a read of the",
"// websocket connection if the client is still connected.",
"go",
"s",
".",
"websocketClientRead",
"(",
"wsc",
")",
"\n\n",
"s",
".",
"wg",
".",
"Add",
"(",
"2",
")",
"\n",
"go",
"s",
".",
"websocketClientRespond",
"(",
"wsc",
")",
"\n",
"go",
"s",
".",
"websocketClientSend",
"(",
"wsc",
")",
"\n\n",
"<-",
"wsc",
".",
"quit",
"\n",
"}"
] | // websocketClientRPC starts the goroutines to serve JSON-RPC requests over a
// websocket connection for a single client. | [
"websocketClientRPC",
"starts",
"the",
"goroutines",
"to",
"serve",
"JSON",
"-",
"RPC",
"requests",
"over",
"a",
"websocket",
"connection",
"for",
"a",
"single",
"client",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/server.go#L539-L559 | train |
btcsuite/btcwallet | rpc/legacyrpc/server.go | postClientRPC | func (s *Server) postClientRPC(w http.ResponseWriter, r *http.Request) {
body := http.MaxBytesReader(w, r.Body, maxRequestSize)
rpcRequest, err := ioutil.ReadAll(body)
if err != nil {
// TODO: what if the underlying reader errored?
http.Error(w, "413 Request Too Large.",
http.StatusRequestEntityTooLarge)
return
}
// First check whether wallet has a handler for this request's method.
// If unfound, the request is sent to the chain server for further
// processing. While checking the methods, disallow authenticate
// requests, as they are invalid for HTTP POST clients.
var req btcjson.Request
err = json.Unmarshal(rpcRequest, &req)
if err != nil {
resp, err := btcjson.MarshalResponse(req.ID, nil, btcjson.ErrRPCInvalidRequest)
if err != nil {
log.Errorf("Unable to marshal response: %v", err)
http.Error(w, "500 Internal Server Error",
http.StatusInternalServerError)
return
}
_, err = w.Write(resp)
if err != nil {
log.Warnf("Cannot write invalid request request to "+
"client: %v", err)
}
return
}
// Create the response and error from the request. Two special cases
// are handled for the authenticate and stop request methods.
var res interface{}
var jsonErr *btcjson.RPCError
var stop bool
switch req.Method {
case "authenticate":
// Drop it.
return
case "stop":
stop = true
res = "btcwallet stopping"
default:
res, jsonErr = s.handlerClosure(&req)()
}
// Marshal and send.
mresp, err := btcjson.MarshalResponse(req.ID, res, jsonErr)
if err != nil {
log.Errorf("Unable to marshal response: %v", err)
http.Error(w, "500 Internal Server Error", http.StatusInternalServerError)
return
}
_, err = w.Write(mresp)
if err != nil {
log.Warnf("Unable to respond to client: %v", err)
}
if stop {
s.requestProcessShutdown()
}
} | go | func (s *Server) postClientRPC(w http.ResponseWriter, r *http.Request) {
body := http.MaxBytesReader(w, r.Body, maxRequestSize)
rpcRequest, err := ioutil.ReadAll(body)
if err != nil {
// TODO: what if the underlying reader errored?
http.Error(w, "413 Request Too Large.",
http.StatusRequestEntityTooLarge)
return
}
// First check whether wallet has a handler for this request's method.
// If unfound, the request is sent to the chain server for further
// processing. While checking the methods, disallow authenticate
// requests, as they are invalid for HTTP POST clients.
var req btcjson.Request
err = json.Unmarshal(rpcRequest, &req)
if err != nil {
resp, err := btcjson.MarshalResponse(req.ID, nil, btcjson.ErrRPCInvalidRequest)
if err != nil {
log.Errorf("Unable to marshal response: %v", err)
http.Error(w, "500 Internal Server Error",
http.StatusInternalServerError)
return
}
_, err = w.Write(resp)
if err != nil {
log.Warnf("Cannot write invalid request request to "+
"client: %v", err)
}
return
}
// Create the response and error from the request. Two special cases
// are handled for the authenticate and stop request methods.
var res interface{}
var jsonErr *btcjson.RPCError
var stop bool
switch req.Method {
case "authenticate":
// Drop it.
return
case "stop":
stop = true
res = "btcwallet stopping"
default:
res, jsonErr = s.handlerClosure(&req)()
}
// Marshal and send.
mresp, err := btcjson.MarshalResponse(req.ID, res, jsonErr)
if err != nil {
log.Errorf("Unable to marshal response: %v", err)
http.Error(w, "500 Internal Server Error", http.StatusInternalServerError)
return
}
_, err = w.Write(mresp)
if err != nil {
log.Warnf("Unable to respond to client: %v", err)
}
if stop {
s.requestProcessShutdown()
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"postClientRPC",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"body",
":=",
"http",
".",
"MaxBytesReader",
"(",
"w",
",",
"r",
".",
"Body",
",",
"maxRequestSize",
")",
"\n",
"rpcRequest",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// TODO: what if the underlying reader errored?",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusRequestEntityTooLarge",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// First check whether wallet has a handler for this request's method.",
"// If unfound, the request is sent to the chain server for further",
"// processing. While checking the methods, disallow authenticate",
"// requests, as they are invalid for HTTP POST clients.",
"var",
"req",
"btcjson",
".",
"Request",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"rpcRequest",
",",
"&",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"resp",
",",
"err",
":=",
"btcjson",
".",
"MarshalResponse",
"(",
"req",
".",
"ID",
",",
"nil",
",",
"btcjson",
".",
"ErrRPCInvalidRequest",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"w",
".",
"Write",
"(",
"resp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Create the response and error from the request. Two special cases",
"// are handled for the authenticate and stop request methods.",
"var",
"res",
"interface",
"{",
"}",
"\n",
"var",
"jsonErr",
"*",
"btcjson",
".",
"RPCError",
"\n",
"var",
"stop",
"bool",
"\n",
"switch",
"req",
".",
"Method",
"{",
"case",
"\"",
"\"",
":",
"// Drop it.",
"return",
"\n",
"case",
"\"",
"\"",
":",
"stop",
"=",
"true",
"\n",
"res",
"=",
"\"",
"\"",
"\n",
"default",
":",
"res",
",",
"jsonErr",
"=",
"s",
".",
"handlerClosure",
"(",
"&",
"req",
")",
"(",
")",
"\n",
"}",
"\n\n",
"// Marshal and send.",
"mresp",
",",
"err",
":=",
"btcjson",
".",
"MarshalResponse",
"(",
"req",
".",
"ID",
",",
"res",
",",
"jsonErr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"w",
".",
"Write",
"(",
"mresp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"stop",
"{",
"s",
".",
"requestProcessShutdown",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // postClientRPC processes and replies to a JSON-RPC client request. | [
"postClientRPC",
"processes",
"and",
"replies",
"to",
"a",
"JSON",
"-",
"RPC",
"client",
"request",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/rpc/legacyrpc/server.go#L566-L629 | train |
btcsuite/btcwallet | wallet/multisig.go | MakeMultiSigScript | func (w *Wallet) MakeMultiSigScript(addrs []btcutil.Address, nRequired int) ([]byte, error) {
pubKeys := make([]*btcutil.AddressPubKey, len(addrs))
var dbtx walletdb.ReadTx
var addrmgrNs walletdb.ReadBucket
defer func() {
if dbtx != nil {
dbtx.Rollback()
}
}()
// The address list will made up either of addreseses (pubkey hash), for
// which we need to look up the keys in wallet, straight pubkeys, or a
// mixture of the two.
for i, addr := range addrs {
switch addr := addr.(type) {
default:
return nil, errors.New("cannot make multisig script for " +
"a non-secp256k1 public key or P2PKH address")
case *btcutil.AddressPubKey:
pubKeys[i] = addr
case *btcutil.AddressPubKeyHash:
if dbtx == nil {
var err error
dbtx, err = w.db.BeginReadTx()
if err != nil {
return nil, err
}
addrmgrNs = dbtx.ReadBucket(waddrmgrNamespaceKey)
}
addrInfo, err := w.Manager.Address(addrmgrNs, addr)
if err != nil {
return nil, err
}
serializedPubKey := addrInfo.(waddrmgr.ManagedPubKeyAddress).
PubKey().SerializeCompressed()
pubKeyAddr, err := btcutil.NewAddressPubKey(
serializedPubKey, w.chainParams)
if err != nil {
return nil, err
}
pubKeys[i] = pubKeyAddr
}
}
return txscript.MultiSigScript(pubKeys, nRequired)
} | go | func (w *Wallet) MakeMultiSigScript(addrs []btcutil.Address, nRequired int) ([]byte, error) {
pubKeys := make([]*btcutil.AddressPubKey, len(addrs))
var dbtx walletdb.ReadTx
var addrmgrNs walletdb.ReadBucket
defer func() {
if dbtx != nil {
dbtx.Rollback()
}
}()
// The address list will made up either of addreseses (pubkey hash), for
// which we need to look up the keys in wallet, straight pubkeys, or a
// mixture of the two.
for i, addr := range addrs {
switch addr := addr.(type) {
default:
return nil, errors.New("cannot make multisig script for " +
"a non-secp256k1 public key or P2PKH address")
case *btcutil.AddressPubKey:
pubKeys[i] = addr
case *btcutil.AddressPubKeyHash:
if dbtx == nil {
var err error
dbtx, err = w.db.BeginReadTx()
if err != nil {
return nil, err
}
addrmgrNs = dbtx.ReadBucket(waddrmgrNamespaceKey)
}
addrInfo, err := w.Manager.Address(addrmgrNs, addr)
if err != nil {
return nil, err
}
serializedPubKey := addrInfo.(waddrmgr.ManagedPubKeyAddress).
PubKey().SerializeCompressed()
pubKeyAddr, err := btcutil.NewAddressPubKey(
serializedPubKey, w.chainParams)
if err != nil {
return nil, err
}
pubKeys[i] = pubKeyAddr
}
}
return txscript.MultiSigScript(pubKeys, nRequired)
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"MakeMultiSigScript",
"(",
"addrs",
"[",
"]",
"btcutil",
".",
"Address",
",",
"nRequired",
"int",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"pubKeys",
":=",
"make",
"(",
"[",
"]",
"*",
"btcutil",
".",
"AddressPubKey",
",",
"len",
"(",
"addrs",
")",
")",
"\n\n",
"var",
"dbtx",
"walletdb",
".",
"ReadTx",
"\n",
"var",
"addrmgrNs",
"walletdb",
".",
"ReadBucket",
"\n",
"defer",
"func",
"(",
")",
"{",
"if",
"dbtx",
"!=",
"nil",
"{",
"dbtx",
".",
"Rollback",
"(",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"// The address list will made up either of addreseses (pubkey hash), for",
"// which we need to look up the keys in wallet, straight pubkeys, or a",
"// mixture of the two.",
"for",
"i",
",",
"addr",
":=",
"range",
"addrs",
"{",
"switch",
"addr",
":=",
"addr",
".",
"(",
"type",
")",
"{",
"default",
":",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
")",
"\n\n",
"case",
"*",
"btcutil",
".",
"AddressPubKey",
":",
"pubKeys",
"[",
"i",
"]",
"=",
"addr",
"\n\n",
"case",
"*",
"btcutil",
".",
"AddressPubKeyHash",
":",
"if",
"dbtx",
"==",
"nil",
"{",
"var",
"err",
"error",
"\n",
"dbtx",
",",
"err",
"=",
"w",
".",
"db",
".",
"BeginReadTx",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"addrmgrNs",
"=",
"dbtx",
".",
"ReadBucket",
"(",
"waddrmgrNamespaceKey",
")",
"\n",
"}",
"\n",
"addrInfo",
",",
"err",
":=",
"w",
".",
"Manager",
".",
"Address",
"(",
"addrmgrNs",
",",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"serializedPubKey",
":=",
"addrInfo",
".",
"(",
"waddrmgr",
".",
"ManagedPubKeyAddress",
")",
".",
"PubKey",
"(",
")",
".",
"SerializeCompressed",
"(",
")",
"\n\n",
"pubKeyAddr",
",",
"err",
":=",
"btcutil",
".",
"NewAddressPubKey",
"(",
"serializedPubKey",
",",
"w",
".",
"chainParams",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"pubKeys",
"[",
"i",
"]",
"=",
"pubKeyAddr",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"txscript",
".",
"MultiSigScript",
"(",
"pubKeys",
",",
"nRequired",
")",
"\n",
"}"
] | // MakeMultiSigScript creates a multi-signature script that can be redeemed with
// nRequired signatures of the passed keys and addresses. If the address is a
// P2PKH address, the associated pubkey is looked up by the wallet if possible,
// otherwise an error is returned for a missing pubkey.
//
// This function only works with pubkeys and P2PKH addresses derived from them. | [
"MakeMultiSigScript",
"creates",
"a",
"multi",
"-",
"signature",
"script",
"that",
"can",
"be",
"redeemed",
"with",
"nRequired",
"signatures",
"of",
"the",
"passed",
"keys",
"and",
"addresses",
".",
"If",
"the",
"address",
"is",
"a",
"P2PKH",
"address",
"the",
"associated",
"pubkey",
"is",
"looked",
"up",
"by",
"the",
"wallet",
"if",
"possible",
"otherwise",
"an",
"error",
"is",
"returned",
"for",
"a",
"missing",
"pubkey",
".",
"This",
"function",
"only",
"works",
"with",
"pubkeys",
"and",
"P2PKH",
"addresses",
"derived",
"from",
"them",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/multisig.go#L23-L72 | train |
btcsuite/btcwallet | wallet/multisig.go | ImportP2SHRedeemScript | func (w *Wallet) ImportP2SHRedeemScript(script []byte) (*btcutil.AddressScriptHash, error) {
var p2shAddr *btcutil.AddressScriptHash
err := walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
// TODO(oga) blockstamp current block?
bs := &waddrmgr.BlockStamp{
Hash: *w.ChainParams().GenesisHash,
Height: 0,
}
// As this is a regular P2SH script, we'll import this into the
// BIP0044 scope.
bip44Mgr, err := w.Manager.FetchScopedKeyManager(
waddrmgr.KeyScopeBIP0084,
)
if err != nil {
return err
}
addrInfo, err := bip44Mgr.ImportScript(addrmgrNs, script, bs)
if err != nil {
// Don't care if it's already there, but still have to
// set the p2shAddr since the address manager didn't
// return anything useful.
if waddrmgr.IsError(err, waddrmgr.ErrDuplicateAddress) {
// This function will never error as it always
// hashes the script to the correct length.
p2shAddr, _ = btcutil.NewAddressScriptHash(script,
w.chainParams)
return nil
}
return err
}
p2shAddr = addrInfo.Address().(*btcutil.AddressScriptHash)
return nil
})
return p2shAddr, err
} | go | func (w *Wallet) ImportP2SHRedeemScript(script []byte) (*btcutil.AddressScriptHash, error) {
var p2shAddr *btcutil.AddressScriptHash
err := walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
// TODO(oga) blockstamp current block?
bs := &waddrmgr.BlockStamp{
Hash: *w.ChainParams().GenesisHash,
Height: 0,
}
// As this is a regular P2SH script, we'll import this into the
// BIP0044 scope.
bip44Mgr, err := w.Manager.FetchScopedKeyManager(
waddrmgr.KeyScopeBIP0084,
)
if err != nil {
return err
}
addrInfo, err := bip44Mgr.ImportScript(addrmgrNs, script, bs)
if err != nil {
// Don't care if it's already there, but still have to
// set the p2shAddr since the address manager didn't
// return anything useful.
if waddrmgr.IsError(err, waddrmgr.ErrDuplicateAddress) {
// This function will never error as it always
// hashes the script to the correct length.
p2shAddr, _ = btcutil.NewAddressScriptHash(script,
w.chainParams)
return nil
}
return err
}
p2shAddr = addrInfo.Address().(*btcutil.AddressScriptHash)
return nil
})
return p2shAddr, err
} | [
"func",
"(",
"w",
"*",
"Wallet",
")",
"ImportP2SHRedeemScript",
"(",
"script",
"[",
"]",
"byte",
")",
"(",
"*",
"btcutil",
".",
"AddressScriptHash",
",",
"error",
")",
"{",
"var",
"p2shAddr",
"*",
"btcutil",
".",
"AddressScriptHash",
"\n",
"err",
":=",
"walletdb",
".",
"Update",
"(",
"w",
".",
"db",
",",
"func",
"(",
"tx",
"walletdb",
".",
"ReadWriteTx",
")",
"error",
"{",
"addrmgrNs",
":=",
"tx",
".",
"ReadWriteBucket",
"(",
"waddrmgrNamespaceKey",
")",
"\n\n",
"// TODO(oga) blockstamp current block?",
"bs",
":=",
"&",
"waddrmgr",
".",
"BlockStamp",
"{",
"Hash",
":",
"*",
"w",
".",
"ChainParams",
"(",
")",
".",
"GenesisHash",
",",
"Height",
":",
"0",
",",
"}",
"\n\n",
"// As this is a regular P2SH script, we'll import this into the",
"// BIP0044 scope.",
"bip44Mgr",
",",
"err",
":=",
"w",
".",
"Manager",
".",
"FetchScopedKeyManager",
"(",
"waddrmgr",
".",
"KeyScopeBIP0084",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"addrInfo",
",",
"err",
":=",
"bip44Mgr",
".",
"ImportScript",
"(",
"addrmgrNs",
",",
"script",
",",
"bs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Don't care if it's already there, but still have to",
"// set the p2shAddr since the address manager didn't",
"// return anything useful.",
"if",
"waddrmgr",
".",
"IsError",
"(",
"err",
",",
"waddrmgr",
".",
"ErrDuplicateAddress",
")",
"{",
"// This function will never error as it always",
"// hashes the script to the correct length.",
"p2shAddr",
",",
"_",
"=",
"btcutil",
".",
"NewAddressScriptHash",
"(",
"script",
",",
"w",
".",
"chainParams",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"p2shAddr",
"=",
"addrInfo",
".",
"Address",
"(",
")",
".",
"(",
"*",
"btcutil",
".",
"AddressScriptHash",
")",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"return",
"p2shAddr",
",",
"err",
"\n",
"}"
] | // ImportP2SHRedeemScript adds a P2SH redeem script to the wallet. | [
"ImportP2SHRedeemScript",
"adds",
"a",
"P2SH",
"redeem",
"script",
"to",
"the",
"wallet",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/multisig.go#L75-L114 | train |
btcsuite/btcwallet | walletdb/migration/manager.go | VersionsToApply | func VersionsToApply(currentVersion uint32, versions []Version) []Version {
// Assuming the migration versions are in increasing order, we'll apply
// any migrations that have a version number lower than our current one.
var upgradeVersions []Version
for _, version := range versions {
if version.Number > currentVersion {
upgradeVersions = append(upgradeVersions, version)
}
}
// Before returning, we'll sort the slice by its version number to
// ensure the migrations are applied in their intended order.
sort.Slice(upgradeVersions, func(i, j int) bool {
return upgradeVersions[i].Number < upgradeVersions[j].Number
})
return upgradeVersions
} | go | func VersionsToApply(currentVersion uint32, versions []Version) []Version {
// Assuming the migration versions are in increasing order, we'll apply
// any migrations that have a version number lower than our current one.
var upgradeVersions []Version
for _, version := range versions {
if version.Number > currentVersion {
upgradeVersions = append(upgradeVersions, version)
}
}
// Before returning, we'll sort the slice by its version number to
// ensure the migrations are applied in their intended order.
sort.Slice(upgradeVersions, func(i, j int) bool {
return upgradeVersions[i].Number < upgradeVersions[j].Number
})
return upgradeVersions
} | [
"func",
"VersionsToApply",
"(",
"currentVersion",
"uint32",
",",
"versions",
"[",
"]",
"Version",
")",
"[",
"]",
"Version",
"{",
"// Assuming the migration versions are in increasing order, we'll apply",
"// any migrations that have a version number lower than our current one.",
"var",
"upgradeVersions",
"[",
"]",
"Version",
"\n",
"for",
"_",
",",
"version",
":=",
"range",
"versions",
"{",
"if",
"version",
".",
"Number",
">",
"currentVersion",
"{",
"upgradeVersions",
"=",
"append",
"(",
"upgradeVersions",
",",
"version",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Before returning, we'll sort the slice by its version number to",
"// ensure the migrations are applied in their intended order.",
"sort",
".",
"Slice",
"(",
"upgradeVersions",
",",
"func",
"(",
"i",
",",
"j",
"int",
")",
"bool",
"{",
"return",
"upgradeVersions",
"[",
"i",
"]",
".",
"Number",
"<",
"upgradeVersions",
"[",
"j",
"]",
".",
"Number",
"\n",
"}",
")",
"\n\n",
"return",
"upgradeVersions",
"\n",
"}"
] | // VersionsToApply determines which versions should be applied as migrations
// based on the current version. | [
"VersionsToApply",
"determines",
"which",
"versions",
"should",
"be",
"applied",
"as",
"migrations",
"based",
"on",
"the",
"current",
"version",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/walletdb/migration/manager.go#L69-L86 | train |
btcsuite/btcwallet | walletdb/migration/manager.go | upgrade | func upgrade(mgr Manager) error {
// We'll start by fetching the service's current and latest version.
ns := mgr.Namespace()
currentVersion, err := mgr.CurrentVersion(ns)
if err != nil {
return err
}
versions := mgr.Versions()
latestVersion := GetLatestVersion(versions)
switch {
// If the current version is greater than the latest, then the service
// is attempting to revert to a previous version that's possibly
// backwards-incompatible. To prevent this, we'll return an error
// indicating so.
case currentVersion > latestVersion:
return ErrReversion
// If the current version is behind the latest version, we'll need to
// apply all of the newer versions in order to catch up to the latest.
case currentVersion < latestVersion:
versions := VersionsToApply(currentVersion, versions)
mgrName := mgr.Name()
ns := mgr.Namespace()
for _, version := range versions {
log.Infof("Applying %v migration #%d", mgrName,
version.Number)
// We'll only run a migration if there is one available
// for this version.
if version.Migration != nil {
err := version.Migration(ns)
if err != nil {
log.Errorf("Unable to apply %v "+
"migration #%d: %v", mgrName,
version.Number, err)
return err
}
}
}
// With all of the versions applied, we can now reflect the
// latest version upon the service.
if err := mgr.SetVersion(ns, latestVersion); err != nil {
return err
}
// If the current version matches the latest one, there's no upgrade
// needed and we can safely exit.
case currentVersion == latestVersion:
}
return nil
} | go | func upgrade(mgr Manager) error {
// We'll start by fetching the service's current and latest version.
ns := mgr.Namespace()
currentVersion, err := mgr.CurrentVersion(ns)
if err != nil {
return err
}
versions := mgr.Versions()
latestVersion := GetLatestVersion(versions)
switch {
// If the current version is greater than the latest, then the service
// is attempting to revert to a previous version that's possibly
// backwards-incompatible. To prevent this, we'll return an error
// indicating so.
case currentVersion > latestVersion:
return ErrReversion
// If the current version is behind the latest version, we'll need to
// apply all of the newer versions in order to catch up to the latest.
case currentVersion < latestVersion:
versions := VersionsToApply(currentVersion, versions)
mgrName := mgr.Name()
ns := mgr.Namespace()
for _, version := range versions {
log.Infof("Applying %v migration #%d", mgrName,
version.Number)
// We'll only run a migration if there is one available
// for this version.
if version.Migration != nil {
err := version.Migration(ns)
if err != nil {
log.Errorf("Unable to apply %v "+
"migration #%d: %v", mgrName,
version.Number, err)
return err
}
}
}
// With all of the versions applied, we can now reflect the
// latest version upon the service.
if err := mgr.SetVersion(ns, latestVersion); err != nil {
return err
}
// If the current version matches the latest one, there's no upgrade
// needed and we can safely exit.
case currentVersion == latestVersion:
}
return nil
} | [
"func",
"upgrade",
"(",
"mgr",
"Manager",
")",
"error",
"{",
"// We'll start by fetching the service's current and latest version.",
"ns",
":=",
"mgr",
".",
"Namespace",
"(",
")",
"\n",
"currentVersion",
",",
"err",
":=",
"mgr",
".",
"CurrentVersion",
"(",
"ns",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"versions",
":=",
"mgr",
".",
"Versions",
"(",
")",
"\n",
"latestVersion",
":=",
"GetLatestVersion",
"(",
"versions",
")",
"\n\n",
"switch",
"{",
"// If the current version is greater than the latest, then the service",
"// is attempting to revert to a previous version that's possibly",
"// backwards-incompatible. To prevent this, we'll return an error",
"// indicating so.",
"case",
"currentVersion",
">",
"latestVersion",
":",
"return",
"ErrReversion",
"\n\n",
"// If the current version is behind the latest version, we'll need to",
"// apply all of the newer versions in order to catch up to the latest.",
"case",
"currentVersion",
"<",
"latestVersion",
":",
"versions",
":=",
"VersionsToApply",
"(",
"currentVersion",
",",
"versions",
")",
"\n",
"mgrName",
":=",
"mgr",
".",
"Name",
"(",
")",
"\n",
"ns",
":=",
"mgr",
".",
"Namespace",
"(",
")",
"\n\n",
"for",
"_",
",",
"version",
":=",
"range",
"versions",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"mgrName",
",",
"version",
".",
"Number",
")",
"\n\n",
"// We'll only run a migration if there is one available",
"// for this version.",
"if",
"version",
".",
"Migration",
"!=",
"nil",
"{",
"err",
":=",
"version",
".",
"Migration",
"(",
"ns",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"mgrName",
",",
"version",
".",
"Number",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// With all of the versions applied, we can now reflect the",
"// latest version upon the service.",
"if",
"err",
":=",
"mgr",
".",
"SetVersion",
"(",
"ns",
",",
"latestVersion",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// If the current version matches the latest one, there's no upgrade",
"// needed and we can safely exit.",
"case",
"currentVersion",
"==",
"latestVersion",
":",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // upgrade attempts to upgrade a service expose through its implementation of
// the Manager interface. This function will determine whether any new versions
// need to be applied based on the service's current version and latest
// available one. | [
"upgrade",
"attempts",
"to",
"upgrade",
"a",
"service",
"expose",
"through",
"its",
"implementation",
"of",
"the",
"Manager",
"interface",
".",
"This",
"function",
"will",
"determine",
"whether",
"any",
"new",
"versions",
"need",
"to",
"be",
"applied",
"based",
"on",
"the",
"service",
"s",
"current",
"version",
"and",
"latest",
"available",
"one",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/walletdb/migration/manager.go#L108-L162 | train |
btcsuite/btcwallet | wtxmgr/query.go | minedTxDetails | func (s *Store) minedTxDetails(ns walletdb.ReadBucket, txHash *chainhash.Hash, recKey, recVal []byte) (*TxDetails, error) {
var details TxDetails
// Parse transaction record k/v, lookup the full block record for the
// block time, and read all matching credits, debits.
err := readRawTxRecord(txHash, recVal, &details.TxRecord)
if err != nil {
return nil, err
}
err = readRawTxRecordBlock(recKey, &details.Block.Block)
if err != nil {
return nil, err
}
details.Block.Time, err = fetchBlockTime(ns, details.Block.Height)
if err != nil {
return nil, err
}
credIter := makeReadCreditIterator(ns, recKey)
for credIter.next() {
if int(credIter.elem.Index) >= len(details.MsgTx.TxOut) {
str := "saved credit index exceeds number of outputs"
return nil, storeError(ErrData, str, nil)
}
// The credit iterator does not record whether this credit was
// spent by an unmined transaction, so check that here.
if !credIter.elem.Spent {
k := canonicalOutPoint(txHash, credIter.elem.Index)
spent := existsRawUnminedInput(ns, k) != nil
credIter.elem.Spent = spent
}
details.Credits = append(details.Credits, credIter.elem)
}
if credIter.err != nil {
return nil, credIter.err
}
debIter := makeReadDebitIterator(ns, recKey)
for debIter.next() {
if int(debIter.elem.Index) >= len(details.MsgTx.TxIn) {
str := "saved debit index exceeds number of inputs"
return nil, storeError(ErrData, str, nil)
}
details.Debits = append(details.Debits, debIter.elem)
}
return &details, debIter.err
} | go | func (s *Store) minedTxDetails(ns walletdb.ReadBucket, txHash *chainhash.Hash, recKey, recVal []byte) (*TxDetails, error) {
var details TxDetails
// Parse transaction record k/v, lookup the full block record for the
// block time, and read all matching credits, debits.
err := readRawTxRecord(txHash, recVal, &details.TxRecord)
if err != nil {
return nil, err
}
err = readRawTxRecordBlock(recKey, &details.Block.Block)
if err != nil {
return nil, err
}
details.Block.Time, err = fetchBlockTime(ns, details.Block.Height)
if err != nil {
return nil, err
}
credIter := makeReadCreditIterator(ns, recKey)
for credIter.next() {
if int(credIter.elem.Index) >= len(details.MsgTx.TxOut) {
str := "saved credit index exceeds number of outputs"
return nil, storeError(ErrData, str, nil)
}
// The credit iterator does not record whether this credit was
// spent by an unmined transaction, so check that here.
if !credIter.elem.Spent {
k := canonicalOutPoint(txHash, credIter.elem.Index)
spent := existsRawUnminedInput(ns, k) != nil
credIter.elem.Spent = spent
}
details.Credits = append(details.Credits, credIter.elem)
}
if credIter.err != nil {
return nil, credIter.err
}
debIter := makeReadDebitIterator(ns, recKey)
for debIter.next() {
if int(debIter.elem.Index) >= len(details.MsgTx.TxIn) {
str := "saved debit index exceeds number of inputs"
return nil, storeError(ErrData, str, nil)
}
details.Debits = append(details.Debits, debIter.elem)
}
return &details, debIter.err
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"minedTxDetails",
"(",
"ns",
"walletdb",
".",
"ReadBucket",
",",
"txHash",
"*",
"chainhash",
".",
"Hash",
",",
"recKey",
",",
"recVal",
"[",
"]",
"byte",
")",
"(",
"*",
"TxDetails",
",",
"error",
")",
"{",
"var",
"details",
"TxDetails",
"\n\n",
"// Parse transaction record k/v, lookup the full block record for the",
"// block time, and read all matching credits, debits.",
"err",
":=",
"readRawTxRecord",
"(",
"txHash",
",",
"recVal",
",",
"&",
"details",
".",
"TxRecord",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"err",
"=",
"readRawTxRecordBlock",
"(",
"recKey",
",",
"&",
"details",
".",
"Block",
".",
"Block",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"details",
".",
"Block",
".",
"Time",
",",
"err",
"=",
"fetchBlockTime",
"(",
"ns",
",",
"details",
".",
"Block",
".",
"Height",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"credIter",
":=",
"makeReadCreditIterator",
"(",
"ns",
",",
"recKey",
")",
"\n",
"for",
"credIter",
".",
"next",
"(",
")",
"{",
"if",
"int",
"(",
"credIter",
".",
"elem",
".",
"Index",
")",
">=",
"len",
"(",
"details",
".",
"MsgTx",
".",
"TxOut",
")",
"{",
"str",
":=",
"\"",
"\"",
"\n",
"return",
"nil",
",",
"storeError",
"(",
"ErrData",
",",
"str",
",",
"nil",
")",
"\n",
"}",
"\n\n",
"// The credit iterator does not record whether this credit was",
"// spent by an unmined transaction, so check that here.",
"if",
"!",
"credIter",
".",
"elem",
".",
"Spent",
"{",
"k",
":=",
"canonicalOutPoint",
"(",
"txHash",
",",
"credIter",
".",
"elem",
".",
"Index",
")",
"\n",
"spent",
":=",
"existsRawUnminedInput",
"(",
"ns",
",",
"k",
")",
"!=",
"nil",
"\n",
"credIter",
".",
"elem",
".",
"Spent",
"=",
"spent",
"\n",
"}",
"\n",
"details",
".",
"Credits",
"=",
"append",
"(",
"details",
".",
"Credits",
",",
"credIter",
".",
"elem",
")",
"\n",
"}",
"\n",
"if",
"credIter",
".",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"credIter",
".",
"err",
"\n",
"}",
"\n\n",
"debIter",
":=",
"makeReadDebitIterator",
"(",
"ns",
",",
"recKey",
")",
"\n",
"for",
"debIter",
".",
"next",
"(",
")",
"{",
"if",
"int",
"(",
"debIter",
".",
"elem",
".",
"Index",
")",
">=",
"len",
"(",
"details",
".",
"MsgTx",
".",
"TxIn",
")",
"{",
"str",
":=",
"\"",
"\"",
"\n",
"return",
"nil",
",",
"storeError",
"(",
"ErrData",
",",
"str",
",",
"nil",
")",
"\n",
"}",
"\n\n",
"details",
".",
"Debits",
"=",
"append",
"(",
"details",
".",
"Debits",
",",
"debIter",
".",
"elem",
")",
"\n",
"}",
"\n",
"return",
"&",
"details",
",",
"debIter",
".",
"err",
"\n",
"}"
] | // minedTxDetails fetches the TxDetails for the mined transaction with hash
// txHash and the passed tx record key and value. | [
"minedTxDetails",
"fetches",
"the",
"TxDetails",
"for",
"the",
"mined",
"transaction",
"with",
"hash",
"txHash",
"and",
"the",
"passed",
"tx",
"record",
"key",
"and",
"value",
"."
] | 9d95f76e99a72ffaf73b8a6581d8781c52d756f5 | https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wtxmgr/query.go#L46-L94 | train |
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.