repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
btcsuite/btcwallet
waddrmgr/db.go
serializeChainedAddress
func serializeChainedAddress(branch, index uint32) []byte { // The serialized chain address raw data format is: // <branch><index> // // 4 bytes branch + 4 bytes address index rawData := make([]byte, 8) binary.LittleEndian.PutUint32(rawData[0:4], branch) binary.LittleEndian.PutUint32(rawData[4:8], index) return rawData }
go
func serializeChainedAddress(branch, index uint32) []byte { // The serialized chain address raw data format is: // <branch><index> // // 4 bytes branch + 4 bytes address index rawData := make([]byte, 8) binary.LittleEndian.PutUint32(rawData[0:4], branch) binary.LittleEndian.PutUint32(rawData[4:8], index) return rawData }
[ "func", "serializeChainedAddress", "(", "branch", ",", "index", "uint32", ")", "[", "]", "byte", "{", "rawData", ":=", "make", "(", "[", "]", "byte", ",", "8", ")", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "rawData", "[", "0", ":", ...
// serializeChainedAddress returns the serialization of the raw data field for // a chained address.
[ "serializeChainedAddress", "returns", "the", "serialization", "of", "the", "raw", "data", "field", "for", "a", "chained", "address", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1204-L1213
train
btcsuite/btcwallet
waddrmgr/db.go
deserializeImportedAddress
func deserializeImportedAddress(row *dbAddressRow) (*dbImportedAddressRow, error) { // The serialized imported address raw data format is: // <encpubkeylen><encpubkey><encprivkeylen><encprivkey> // // 4 bytes encrypted pubkey len + encrypted pubkey + 4 bytes encrypted // privkey len + encrypted privkey // Given the above, the length of the entry must be at a minimum // the constant value sizes. if len(row.rawData) < 8 { str := "malformed serialized imported address" return nil, managerError(ErrDatabase, str, nil) } retRow := dbImportedAddressRow{ dbAddressRow: *row, } pubLen := binary.LittleEndian.Uint32(row.rawData[0:4]) retRow.encryptedPubKey = make([]byte, pubLen) copy(retRow.encryptedPubKey, row.rawData[4:4+pubLen]) offset := 4 + pubLen privLen := binary.LittleEndian.Uint32(row.rawData[offset : offset+4]) offset += 4 retRow.encryptedPrivKey = make([]byte, privLen) copy(retRow.encryptedPrivKey, row.rawData[offset:offset+privLen]) return &retRow, nil }
go
func deserializeImportedAddress(row *dbAddressRow) (*dbImportedAddressRow, error) { // The serialized imported address raw data format is: // <encpubkeylen><encpubkey><encprivkeylen><encprivkey> // // 4 bytes encrypted pubkey len + encrypted pubkey + 4 bytes encrypted // privkey len + encrypted privkey // Given the above, the length of the entry must be at a minimum // the constant value sizes. if len(row.rawData) < 8 { str := "malformed serialized imported address" return nil, managerError(ErrDatabase, str, nil) } retRow := dbImportedAddressRow{ dbAddressRow: *row, } pubLen := binary.LittleEndian.Uint32(row.rawData[0:4]) retRow.encryptedPubKey = make([]byte, pubLen) copy(retRow.encryptedPubKey, row.rawData[4:4+pubLen]) offset := 4 + pubLen privLen := binary.LittleEndian.Uint32(row.rawData[offset : offset+4]) offset += 4 retRow.encryptedPrivKey = make([]byte, privLen) copy(retRow.encryptedPrivKey, row.rawData[offset:offset+privLen]) return &retRow, nil }
[ "func", "deserializeImportedAddress", "(", "row", "*", "dbAddressRow", ")", "(", "*", "dbImportedAddressRow", ",", "error", ")", "{", "if", "len", "(", "row", ".", "rawData", ")", "<", "8", "{", "str", ":=", "\"malformed serialized imported address\"", "\n", "...
// deserializeImportedAddress deserializes the raw data from the passed address // row as an imported address.
[ "deserializeImportedAddress", "deserializes", "the", "raw", "data", "from", "the", "passed", "address", "row", "as", "an", "imported", "address", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1217-L1245
train
btcsuite/btcwallet
waddrmgr/db.go
serializeImportedAddress
func serializeImportedAddress(encryptedPubKey, encryptedPrivKey []byte) []byte { // The serialized imported address raw data format is: // <encpubkeylen><encpubkey><encprivkeylen><encprivkey> // // 4 bytes encrypted pubkey len + encrypted pubkey + 4 bytes encrypted // privkey len + encrypted privkey pubLen := uint32(len(encryptedPubKey)) privLen := uint32(len(encryptedPrivKey)) rawData := make([]byte, 8+pubLen+privLen) binary.LittleEndian.PutUint32(rawData[0:4], pubLen) copy(rawData[4:4+pubLen], encryptedPubKey) offset := 4 + pubLen binary.LittleEndian.PutUint32(rawData[offset:offset+4], privLen) offset += 4 copy(rawData[offset:offset+privLen], encryptedPrivKey) return rawData }
go
func serializeImportedAddress(encryptedPubKey, encryptedPrivKey []byte) []byte { // The serialized imported address raw data format is: // <encpubkeylen><encpubkey><encprivkeylen><encprivkey> // // 4 bytes encrypted pubkey len + encrypted pubkey + 4 bytes encrypted // privkey len + encrypted privkey pubLen := uint32(len(encryptedPubKey)) privLen := uint32(len(encryptedPrivKey)) rawData := make([]byte, 8+pubLen+privLen) binary.LittleEndian.PutUint32(rawData[0:4], pubLen) copy(rawData[4:4+pubLen], encryptedPubKey) offset := 4 + pubLen binary.LittleEndian.PutUint32(rawData[offset:offset+4], privLen) offset += 4 copy(rawData[offset:offset+privLen], encryptedPrivKey) return rawData }
[ "func", "serializeImportedAddress", "(", "encryptedPubKey", ",", "encryptedPrivKey", "[", "]", "byte", ")", "[", "]", "byte", "{", "pubLen", ":=", "uint32", "(", "len", "(", "encryptedPubKey", ")", ")", "\n", "privLen", ":=", "uint32", "(", "len", "(", "en...
// serializeImportedAddress returns the serialization of the raw data field for // an imported address.
[ "serializeImportedAddress", "returns", "the", "serialization", "of", "the", "raw", "data", "field", "for", "an", "imported", "address", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1249-L1265
train
btcsuite/btcwallet
waddrmgr/db.go
deserializeScriptAddress
func deserializeScriptAddress(row *dbAddressRow) (*dbScriptAddressRow, error) { // The serialized script address raw data format is: // <encscripthashlen><encscripthash><encscriptlen><encscript> // // 4 bytes encrypted script hash len + encrypted script hash + 4 bytes // encrypted script len + encrypted script // Given the above, the length of the entry must be at a minimum // the constant value sizes. if len(row.rawData) < 8 { str := "malformed serialized script address" return nil, managerError(ErrDatabase, str, nil) } retRow := dbScriptAddressRow{ dbAddressRow: *row, } hashLen := binary.LittleEndian.Uint32(row.rawData[0:4]) retRow.encryptedHash = make([]byte, hashLen) copy(retRow.encryptedHash, row.rawData[4:4+hashLen]) offset := 4 + hashLen scriptLen := binary.LittleEndian.Uint32(row.rawData[offset : offset+4]) offset += 4 retRow.encryptedScript = make([]byte, scriptLen) copy(retRow.encryptedScript, row.rawData[offset:offset+scriptLen]) return &retRow, nil }
go
func deserializeScriptAddress(row *dbAddressRow) (*dbScriptAddressRow, error) { // The serialized script address raw data format is: // <encscripthashlen><encscripthash><encscriptlen><encscript> // // 4 bytes encrypted script hash len + encrypted script hash + 4 bytes // encrypted script len + encrypted script // Given the above, the length of the entry must be at a minimum // the constant value sizes. if len(row.rawData) < 8 { str := "malformed serialized script address" return nil, managerError(ErrDatabase, str, nil) } retRow := dbScriptAddressRow{ dbAddressRow: *row, } hashLen := binary.LittleEndian.Uint32(row.rawData[0:4]) retRow.encryptedHash = make([]byte, hashLen) copy(retRow.encryptedHash, row.rawData[4:4+hashLen]) offset := 4 + hashLen scriptLen := binary.LittleEndian.Uint32(row.rawData[offset : offset+4]) offset += 4 retRow.encryptedScript = make([]byte, scriptLen) copy(retRow.encryptedScript, row.rawData[offset:offset+scriptLen]) return &retRow, nil }
[ "func", "deserializeScriptAddress", "(", "row", "*", "dbAddressRow", ")", "(", "*", "dbScriptAddressRow", ",", "error", ")", "{", "if", "len", "(", "row", ".", "rawData", ")", "<", "8", "{", "str", ":=", "\"malformed serialized script address\"", "\n", "return...
// deserializeScriptAddress deserializes the raw data from the passed address // row as a script address.
[ "deserializeScriptAddress", "deserializes", "the", "raw", "data", "from", "the", "passed", "address", "row", "as", "a", "script", "address", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1269-L1297
train
btcsuite/btcwallet
waddrmgr/db.go
serializeScriptAddress
func serializeScriptAddress(encryptedHash, encryptedScript []byte) []byte { // The serialized script address raw data format is: // <encscripthashlen><encscripthash><encscriptlen><encscript> // // 4 bytes encrypted script hash len + encrypted script hash + 4 bytes // encrypted script len + encrypted script hashLen := uint32(len(encryptedHash)) scriptLen := uint32(len(encryptedScript)) rawData := make([]byte, 8+hashLen+scriptLen) binary.LittleEndian.PutUint32(rawData[0:4], hashLen) copy(rawData[4:4+hashLen], encryptedHash) offset := 4 + hashLen binary.LittleEndian.PutUint32(rawData[offset:offset+4], scriptLen) offset += 4 copy(rawData[offset:offset+scriptLen], encryptedScript) return rawData }
go
func serializeScriptAddress(encryptedHash, encryptedScript []byte) []byte { // The serialized script address raw data format is: // <encscripthashlen><encscripthash><encscriptlen><encscript> // // 4 bytes encrypted script hash len + encrypted script hash + 4 bytes // encrypted script len + encrypted script hashLen := uint32(len(encryptedHash)) scriptLen := uint32(len(encryptedScript)) rawData := make([]byte, 8+hashLen+scriptLen) binary.LittleEndian.PutUint32(rawData[0:4], hashLen) copy(rawData[4:4+hashLen], encryptedHash) offset := 4 + hashLen binary.LittleEndian.PutUint32(rawData[offset:offset+4], scriptLen) offset += 4 copy(rawData[offset:offset+scriptLen], encryptedScript) return rawData }
[ "func", "serializeScriptAddress", "(", "encryptedHash", ",", "encryptedScript", "[", "]", "byte", ")", "[", "]", "byte", "{", "hashLen", ":=", "uint32", "(", "len", "(", "encryptedHash", ")", ")", "\n", "scriptLen", ":=", "uint32", "(", "len", "(", "encryp...
// serializeScriptAddress returns the serialization of the raw data field for // a script address.
[ "serializeScriptAddress", "returns", "the", "serialization", "of", "the", "raw", "data", "field", "for", "a", "script", "address", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1301-L1318
train
btcsuite/btcwallet
waddrmgr/db.go
fetchAddressByHash
func fetchAddressByHash(ns walletdb.ReadBucket, scope *KeyScope, addrHash []byte) (interface{}, error) { scopedBucket, err := fetchReadScopeBucket(ns, scope) if err != nil { return nil, err } bucket := scopedBucket.NestedReadBucket(addrBucketName) serializedRow := bucket.Get(addrHash[:]) if serializedRow == nil { str := "address not found" return nil, managerError(ErrAddressNotFound, str, nil) } row, err := deserializeAddressRow(serializedRow) if err != nil { return nil, err } switch row.addrType { case adtChain: return deserializeChainedAddress(row) case adtImport: return deserializeImportedAddress(row) case adtScript: return deserializeScriptAddress(row) } str := fmt.Sprintf("unsupported address type '%d'", row.addrType) return nil, managerError(ErrDatabase, str, nil) }
go
func fetchAddressByHash(ns walletdb.ReadBucket, scope *KeyScope, addrHash []byte) (interface{}, error) { scopedBucket, err := fetchReadScopeBucket(ns, scope) if err != nil { return nil, err } bucket := scopedBucket.NestedReadBucket(addrBucketName) serializedRow := bucket.Get(addrHash[:]) if serializedRow == nil { str := "address not found" return nil, managerError(ErrAddressNotFound, str, nil) } row, err := deserializeAddressRow(serializedRow) if err != nil { return nil, err } switch row.addrType { case adtChain: return deserializeChainedAddress(row) case adtImport: return deserializeImportedAddress(row) case adtScript: return deserializeScriptAddress(row) } str := fmt.Sprintf("unsupported address type '%d'", row.addrType) return nil, managerError(ErrDatabase, str, nil) }
[ "func", "fetchAddressByHash", "(", "ns", "walletdb", ".", "ReadBucket", ",", "scope", "*", "KeyScope", ",", "addrHash", "[", "]", "byte", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "scopedBucket", ",", "err", ":=", "fetchReadScopeBucket", "("...
// fetchAddressByHash loads address information for the provided address hash // from the database. The returned value is one of the address rows for the // specific address type. The caller should use type assertions to ascertain // the type. The caller should prefix the error message with the address hash // which caused the failure.
[ "fetchAddressByHash", "loads", "address", "information", "for", "the", "provided", "address", "hash", "from", "the", "database", ".", "The", "returned", "value", "is", "one", "of", "the", "address", "rows", "for", "the", "specific", "address", "type", ".", "Th...
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1325-L1357
train
btcsuite/btcwallet
waddrmgr/db.go
fetchAddressUsed
func fetchAddressUsed(ns walletdb.ReadBucket, scope *KeyScope, addressID []byte) bool { scopedBucket, err := fetchReadScopeBucket(ns, scope) if err != nil { return false } bucket := scopedBucket.NestedReadBucket(usedAddrBucketName) addrHash := sha256.Sum256(addressID) return bucket.Get(addrHash[:]) != nil }
go
func fetchAddressUsed(ns walletdb.ReadBucket, scope *KeyScope, addressID []byte) bool { scopedBucket, err := fetchReadScopeBucket(ns, scope) if err != nil { return false } bucket := scopedBucket.NestedReadBucket(usedAddrBucketName) addrHash := sha256.Sum256(addressID) return bucket.Get(addrHash[:]) != nil }
[ "func", "fetchAddressUsed", "(", "ns", "walletdb", ".", "ReadBucket", ",", "scope", "*", "KeyScope", ",", "addressID", "[", "]", "byte", ")", "bool", "{", "scopedBucket", ",", "err", ":=", "fetchReadScopeBucket", "(", "ns", ",", "scope", ")", "\n", "if", ...
// fetchAddressUsed returns true if the provided address id was flagged as used.
[ "fetchAddressUsed", "returns", "true", "if", "the", "provided", "address", "id", "was", "flagged", "as", "used", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1360-L1372
train
btcsuite/btcwallet
waddrmgr/db.go
markAddressUsed
func markAddressUsed(ns walletdb.ReadWriteBucket, scope *KeyScope, addressID []byte) error { scopedBucket, err := fetchWriteScopeBucket(ns, scope) if err != nil { return err } bucket := scopedBucket.NestedReadWriteBucket(usedAddrBucketName) addrHash := sha256.Sum256(addressID) val := bucket.Get(addrHash[:]) if val != nil { return nil } err = bucket.Put(addrHash[:], []byte{0}) if err != nil { str := fmt.Sprintf("failed to mark address used %x", addressID) return managerError(ErrDatabase, str, err) } return nil }
go
func markAddressUsed(ns walletdb.ReadWriteBucket, scope *KeyScope, addressID []byte) error { scopedBucket, err := fetchWriteScopeBucket(ns, scope) if err != nil { return err } bucket := scopedBucket.NestedReadWriteBucket(usedAddrBucketName) addrHash := sha256.Sum256(addressID) val := bucket.Get(addrHash[:]) if val != nil { return nil } err = bucket.Put(addrHash[:], []byte{0}) if err != nil { str := fmt.Sprintf("failed to mark address used %x", addressID) return managerError(ErrDatabase, str, err) } return nil }
[ "func", "markAddressUsed", "(", "ns", "walletdb", ".", "ReadWriteBucket", ",", "scope", "*", "KeyScope", ",", "addressID", "[", "]", "byte", ")", "error", "{", "scopedBucket", ",", "err", ":=", "fetchWriteScopeBucket", "(", "ns", ",", "scope", ")", "\n", "...
// markAddressUsed flags the provided address id as used in the database.
[ "markAddressUsed", "flags", "the", "provided", "address", "id", "as", "used", "in", "the", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1375-L1398
train
btcsuite/btcwallet
waddrmgr/db.go
fetchAddress
func fetchAddress(ns walletdb.ReadBucket, scope *KeyScope, addressID []byte) (interface{}, error) { addrHash := sha256.Sum256(addressID) return fetchAddressByHash(ns, scope, addrHash[:]) }
go
func fetchAddress(ns walletdb.ReadBucket, scope *KeyScope, addressID []byte) (interface{}, error) { addrHash := sha256.Sum256(addressID) return fetchAddressByHash(ns, scope, addrHash[:]) }
[ "func", "fetchAddress", "(", "ns", "walletdb", ".", "ReadBucket", ",", "scope", "*", "KeyScope", ",", "addressID", "[", "]", "byte", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "addrHash", ":=", "sha256", ".", "Sum256", "(", "addressID", "...
// fetchAddress loads address information for the provided address id from the // database. The returned value is one of the address rows for the specific // address type. The caller should use type assertions to ascertain the type. // The caller should prefix the error message with the address which caused the // failure.
[ "fetchAddress", "loads", "address", "information", "for", "the", "provided", "address", "id", "from", "the", "database", ".", "The", "returned", "value", "is", "one", "of", "the", "address", "rows", "for", "the", "specific", "address", "type", ".", "The", "c...
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1405-L1410
train
btcsuite/btcwallet
waddrmgr/db.go
putAddress
func putAddress(ns walletdb.ReadWriteBucket, scope *KeyScope, addressID []byte, row *dbAddressRow) error { scopedBucket, err := fetchWriteScopeBucket(ns, scope) if err != nil { return err } bucket := scopedBucket.NestedReadWriteBucket(addrBucketName) // Write the serialized value keyed by the hash of the address. The // additional hash is used to conceal the actual address while still // allowed keyed lookups. addrHash := sha256.Sum256(addressID) err = bucket.Put(addrHash[:], serializeAddressRow(row)) if err != nil { str := fmt.Sprintf("failed to store address %x", addressID) return managerError(ErrDatabase, str, err) } // Update address account index return putAddrAccountIndex(ns, scope, row.account, addrHash[:]) }
go
func putAddress(ns walletdb.ReadWriteBucket, scope *KeyScope, addressID []byte, row *dbAddressRow) error { scopedBucket, err := fetchWriteScopeBucket(ns, scope) if err != nil { return err } bucket := scopedBucket.NestedReadWriteBucket(addrBucketName) // Write the serialized value keyed by the hash of the address. The // additional hash is used to conceal the actual address while still // allowed keyed lookups. addrHash := sha256.Sum256(addressID) err = bucket.Put(addrHash[:], serializeAddressRow(row)) if err != nil { str := fmt.Sprintf("failed to store address %x", addressID) return managerError(ErrDatabase, str, err) } // Update address account index return putAddrAccountIndex(ns, scope, row.account, addrHash[:]) }
[ "func", "putAddress", "(", "ns", "walletdb", ".", "ReadWriteBucket", ",", "scope", "*", "KeyScope", ",", "addressID", "[", "]", "byte", ",", "row", "*", "dbAddressRow", ")", "error", "{", "scopedBucket", ",", "err", ":=", "fetchWriteScopeBucket", "(", "ns", ...
// putAddress stores the provided address information to the database. This is // used a common base for storing the various address types.
[ "putAddress", "stores", "the", "provided", "address", "information", "to", "the", "database", ".", "This", "is", "used", "a", "common", "base", "for", "storing", "the", "various", "address", "types", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1414-L1436
train
btcsuite/btcwallet
waddrmgr/db.go
putChainedAddress
func putChainedAddress(ns walletdb.ReadWriteBucket, scope *KeyScope, addressID []byte, account uint32, status syncStatus, branch, index uint32, addrType addressType) error { scopedBucket, err := fetchWriteScopeBucket(ns, scope) if err != nil { return err } addrRow := dbAddressRow{ addrType: addrType, account: account, addTime: uint64(time.Now().Unix()), syncStatus: status, rawData: serializeChainedAddress(branch, index), } if err := putAddress(ns, scope, addressID, &addrRow); err != nil { return err } // Update the next index for the appropriate internal or external // branch. accountID := uint32ToBytes(account) bucket := scopedBucket.NestedReadWriteBucket(acctBucketName) serializedAccount := bucket.Get(accountID) // Deserialize the account row. row, err := deserializeAccountRow(accountID, serializedAccount) if err != nil { return err } arow, err := deserializeDefaultAccountRow(accountID, row) if err != nil { return err } // Increment the appropriate next index depending on whether the branch // is internal or external. nextExternalIndex := arow.nextExternalIndex nextInternalIndex := arow.nextInternalIndex if branch == InternalBranch { nextInternalIndex = index + 1 } else { nextExternalIndex = index + 1 } // Reserialize the account with the updated index and store it. row.rawData = serializeDefaultAccountRow( arow.pubKeyEncrypted, arow.privKeyEncrypted, nextExternalIndex, nextInternalIndex, arow.name, ) err = bucket.Put(accountID, serializeAccountRow(row)) if err != nil { str := fmt.Sprintf("failed to update next index for "+ "address %x, account %d", addressID, account) return managerError(ErrDatabase, str, err) } return nil }
go
func putChainedAddress(ns walletdb.ReadWriteBucket, scope *KeyScope, addressID []byte, account uint32, status syncStatus, branch, index uint32, addrType addressType) error { scopedBucket, err := fetchWriteScopeBucket(ns, scope) if err != nil { return err } addrRow := dbAddressRow{ addrType: addrType, account: account, addTime: uint64(time.Now().Unix()), syncStatus: status, rawData: serializeChainedAddress(branch, index), } if err := putAddress(ns, scope, addressID, &addrRow); err != nil { return err } // Update the next index for the appropriate internal or external // branch. accountID := uint32ToBytes(account) bucket := scopedBucket.NestedReadWriteBucket(acctBucketName) serializedAccount := bucket.Get(accountID) // Deserialize the account row. row, err := deserializeAccountRow(accountID, serializedAccount) if err != nil { return err } arow, err := deserializeDefaultAccountRow(accountID, row) if err != nil { return err } // Increment the appropriate next index depending on whether the branch // is internal or external. nextExternalIndex := arow.nextExternalIndex nextInternalIndex := arow.nextInternalIndex if branch == InternalBranch { nextInternalIndex = index + 1 } else { nextExternalIndex = index + 1 } // Reserialize the account with the updated index and store it. row.rawData = serializeDefaultAccountRow( arow.pubKeyEncrypted, arow.privKeyEncrypted, nextExternalIndex, nextInternalIndex, arow.name, ) err = bucket.Put(accountID, serializeAccountRow(row)) if err != nil { str := fmt.Sprintf("failed to update next index for "+ "address %x, account %d", addressID, account) return managerError(ErrDatabase, str, err) } return nil }
[ "func", "putChainedAddress", "(", "ns", "walletdb", ".", "ReadWriteBucket", ",", "scope", "*", "KeyScope", ",", "addressID", "[", "]", "byte", ",", "account", "uint32", ",", "status", "syncStatus", ",", "branch", ",", "index", "uint32", ",", "addrType", "add...
// putChainedAddress stores the provided chained address information to the // database.
[ "putChainedAddress", "stores", "the", "provided", "chained", "address", "information", "to", "the", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1440-L1498
train
btcsuite/btcwallet
waddrmgr/db.go
putImportedAddress
func putImportedAddress(ns walletdb.ReadWriteBucket, scope *KeyScope, addressID []byte, account uint32, status syncStatus, encryptedPubKey, encryptedPrivKey []byte) error { rawData := serializeImportedAddress(encryptedPubKey, encryptedPrivKey) addrRow := dbAddressRow{ addrType: adtImport, account: account, addTime: uint64(time.Now().Unix()), syncStatus: status, rawData: rawData, } return putAddress(ns, scope, addressID, &addrRow) }
go
func putImportedAddress(ns walletdb.ReadWriteBucket, scope *KeyScope, addressID []byte, account uint32, status syncStatus, encryptedPubKey, encryptedPrivKey []byte) error { rawData := serializeImportedAddress(encryptedPubKey, encryptedPrivKey) addrRow := dbAddressRow{ addrType: adtImport, account: account, addTime: uint64(time.Now().Unix()), syncStatus: status, rawData: rawData, } return putAddress(ns, scope, addressID, &addrRow) }
[ "func", "putImportedAddress", "(", "ns", "walletdb", ".", "ReadWriteBucket", ",", "scope", "*", "KeyScope", ",", "addressID", "[", "]", "byte", ",", "account", "uint32", ",", "status", "syncStatus", ",", "encryptedPubKey", ",", "encryptedPrivKey", "[", "]", "b...
// putImportedAddress stores the provided imported address information to the // database.
[ "putImportedAddress", "stores", "the", "provided", "imported", "address", "information", "to", "the", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1502-L1515
train
btcsuite/btcwallet
waddrmgr/db.go
putScriptAddress
func putScriptAddress(ns walletdb.ReadWriteBucket, scope *KeyScope, addressID []byte, account uint32, status syncStatus, encryptedHash, encryptedScript []byte) error { rawData := serializeScriptAddress(encryptedHash, encryptedScript) addrRow := dbAddressRow{ addrType: adtScript, account: account, addTime: uint64(time.Now().Unix()), syncStatus: status, rawData: rawData, } if err := putAddress(ns, scope, addressID, &addrRow); err != nil { return err } return nil }
go
func putScriptAddress(ns walletdb.ReadWriteBucket, scope *KeyScope, addressID []byte, account uint32, status syncStatus, encryptedHash, encryptedScript []byte) error { rawData := serializeScriptAddress(encryptedHash, encryptedScript) addrRow := dbAddressRow{ addrType: adtScript, account: account, addTime: uint64(time.Now().Unix()), syncStatus: status, rawData: rawData, } if err := putAddress(ns, scope, addressID, &addrRow); err != nil { return err } return nil }
[ "func", "putScriptAddress", "(", "ns", "walletdb", ".", "ReadWriteBucket", ",", "scope", "*", "KeyScope", ",", "addressID", "[", "]", "byte", ",", "account", "uint32", ",", "status", "syncStatus", ",", "encryptedHash", ",", "encryptedScript", "[", "]", "byte",...
// putScriptAddress stores the provided script address information to the // database.
[ "putScriptAddress", "stores", "the", "provided", "script", "address", "information", "to", "the", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1519-L1536
train
btcsuite/btcwallet
waddrmgr/db.go
fetchAddrAccount
func fetchAddrAccount(ns walletdb.ReadBucket, scope *KeyScope, addressID []byte) (uint32, error) { scopedBucket, err := fetchReadScopeBucket(ns, scope) if err != nil { return 0, err } bucket := scopedBucket.NestedReadBucket(addrAcctIdxBucketName) addrHash := sha256.Sum256(addressID) val := bucket.Get(addrHash[:]) if val == nil { str := "address not found" return 0, managerError(ErrAddressNotFound, str, nil) } return binary.LittleEndian.Uint32(val), nil }
go
func fetchAddrAccount(ns walletdb.ReadBucket, scope *KeyScope, addressID []byte) (uint32, error) { scopedBucket, err := fetchReadScopeBucket(ns, scope) if err != nil { return 0, err } bucket := scopedBucket.NestedReadBucket(addrAcctIdxBucketName) addrHash := sha256.Sum256(addressID) val := bucket.Get(addrHash[:]) if val == nil { str := "address not found" return 0, managerError(ErrAddressNotFound, str, nil) } return binary.LittleEndian.Uint32(val), nil }
[ "func", "fetchAddrAccount", "(", "ns", "walletdb", ".", "ReadBucket", ",", "scope", "*", "KeyScope", ",", "addressID", "[", "]", "byte", ")", "(", "uint32", ",", "error", ")", "{", "scopedBucket", ",", "err", ":=", "fetchReadScopeBucket", "(", "ns", ",", ...
// fetchAddrAccount returns the account to which the given address belongs to. // It looks up the account using the addracctidx index which maps the address // hash to its corresponding account id.
[ "fetchAddrAccount", "returns", "the", "account", "to", "which", "the", "given", "address", "belongs", "to", ".", "It", "looks", "up", "the", "account", "using", "the", "addracctidx", "index", "which", "maps", "the", "address", "hash", "to", "its", "correspondi...
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1554-L1571
train
btcsuite/btcwallet
waddrmgr/db.go
forEachAccountAddress
func forEachAccountAddress(ns walletdb.ReadBucket, scope *KeyScope, account uint32, fn func(rowInterface interface{}) error) error { scopedBucket, err := fetchReadScopeBucket(ns, scope) if err != nil { return err } bucket := scopedBucket.NestedReadBucket(addrAcctIdxBucketName). NestedReadBucket(uint32ToBytes(account)) // If index bucket is missing the account, there hasn't been any // address entries yet if bucket == nil { return nil } err = bucket.ForEach(func(k, v []byte) error { // Skip buckets. if v == nil { return nil } addrRow, err := fetchAddressByHash(ns, scope, k) if err != nil { if merr, ok := err.(*ManagerError); ok { desc := fmt.Sprintf("failed to fetch address hash '%s': %v", k, merr.Description) merr.Description = desc return merr } return err } return fn(addrRow) }) if err != nil { return maybeConvertDbError(err) } return nil }
go
func forEachAccountAddress(ns walletdb.ReadBucket, scope *KeyScope, account uint32, fn func(rowInterface interface{}) error) error { scopedBucket, err := fetchReadScopeBucket(ns, scope) if err != nil { return err } bucket := scopedBucket.NestedReadBucket(addrAcctIdxBucketName). NestedReadBucket(uint32ToBytes(account)) // If index bucket is missing the account, there hasn't been any // address entries yet if bucket == nil { return nil } err = bucket.ForEach(func(k, v []byte) error { // Skip buckets. if v == nil { return nil } addrRow, err := fetchAddressByHash(ns, scope, k) if err != nil { if merr, ok := err.(*ManagerError); ok { desc := fmt.Sprintf("failed to fetch address hash '%s': %v", k, merr.Description) merr.Description = desc return merr } return err } return fn(addrRow) }) if err != nil { return maybeConvertDbError(err) } return nil }
[ "func", "forEachAccountAddress", "(", "ns", "walletdb", ".", "ReadBucket", ",", "scope", "*", "KeyScope", ",", "account", "uint32", ",", "fn", "func", "(", "rowInterface", "interface", "{", "}", ")", "error", ")", "error", "{", "scopedBucket", ",", "err", ...
// forEachAccountAddress calls the given function with each address of the // given account stored in the manager, breaking early on error.
[ "forEachAccountAddress", "calls", "the", "given", "function", "with", "each", "address", "of", "the", "given", "account", "stored", "in", "the", "manager", "breaking", "early", "on", "error", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1575-L1615
train
btcsuite/btcwallet
waddrmgr/db.go
fetchSyncedTo
func fetchSyncedTo(ns walletdb.ReadBucket) (*BlockStamp, error) { bucket := ns.NestedReadBucket(syncBucketName) // The serialized synced to format is: // <blockheight><blockhash><timestamp> // // 4 bytes block height + 32 bytes hash length buf := bucket.Get(syncedToName) if len(buf) < 36 { str := "malformed sync information stored in database" return nil, managerError(ErrDatabase, str, nil) } var bs BlockStamp bs.Height = int32(binary.LittleEndian.Uint32(buf[0:4])) copy(bs.Hash[:], buf[4:36]) if len(buf) == 40 { bs.Timestamp = time.Unix( int64(binary.LittleEndian.Uint32(buf[36:])), 0, ) } return &bs, nil }
go
func fetchSyncedTo(ns walletdb.ReadBucket) (*BlockStamp, error) { bucket := ns.NestedReadBucket(syncBucketName) // The serialized synced to format is: // <blockheight><blockhash><timestamp> // // 4 bytes block height + 32 bytes hash length buf := bucket.Get(syncedToName) if len(buf) < 36 { str := "malformed sync information stored in database" return nil, managerError(ErrDatabase, str, nil) } var bs BlockStamp bs.Height = int32(binary.LittleEndian.Uint32(buf[0:4])) copy(bs.Hash[:], buf[4:36]) if len(buf) == 40 { bs.Timestamp = time.Unix( int64(binary.LittleEndian.Uint32(buf[36:])), 0, ) } return &bs, nil }
[ "func", "fetchSyncedTo", "(", "ns", "walletdb", ".", "ReadBucket", ")", "(", "*", "BlockStamp", ",", "error", ")", "{", "bucket", ":=", "ns", ".", "NestedReadBucket", "(", "syncBucketName", ")", "\n", "buf", ":=", "bucket", ".", "Get", "(", "syncedToName",...
// fetchSyncedTo loads the block stamp the manager is synced to from the // database.
[ "fetchSyncedTo", "loads", "the", "block", "stamp", "the", "manager", "is", "synced", "to", "from", "the", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1807-L1831
train
btcsuite/btcwallet
waddrmgr/db.go
PutSyncedTo
func PutSyncedTo(ns walletdb.ReadWriteBucket, bs *BlockStamp) error { bucket := ns.NestedReadWriteBucket(syncBucketName) errStr := fmt.Sprintf("failed to store sync information %v", bs.Hash) // If the block height is greater than zero, check that the previous // block height exists. This prevents reorg issues in the future. // We use BigEndian so that keys/values are added to the bucket in // order, making writes more efficient for some database backends. if bs.Height > 0 { if _, err := fetchBlockHash(ns, bs.Height-1); err != nil { return managerError(ErrDatabase, errStr, err) } } // Store the block hash by block height. height := make([]byte, 4) binary.BigEndian.PutUint32(height, uint32(bs.Height)) err := bucket.Put(height, bs.Hash[0:32]) if err != nil { return managerError(ErrDatabase, errStr, err) } // The serialized synced to format is: // <blockheight><blockhash><timestamp> // // 4 bytes block height + 32 bytes hash length + 4 byte timestamp length buf := make([]byte, 40) binary.LittleEndian.PutUint32(buf[0:4], uint32(bs.Height)) copy(buf[4:36], bs.Hash[0:32]) binary.LittleEndian.PutUint32(buf[36:], uint32(bs.Timestamp.Unix())) err = bucket.Put(syncedToName, buf) if err != nil { return managerError(ErrDatabase, errStr, err) } return nil }
go
func PutSyncedTo(ns walletdb.ReadWriteBucket, bs *BlockStamp) error { bucket := ns.NestedReadWriteBucket(syncBucketName) errStr := fmt.Sprintf("failed to store sync information %v", bs.Hash) // If the block height is greater than zero, check that the previous // block height exists. This prevents reorg issues in the future. // We use BigEndian so that keys/values are added to the bucket in // order, making writes more efficient for some database backends. if bs.Height > 0 { if _, err := fetchBlockHash(ns, bs.Height-1); err != nil { return managerError(ErrDatabase, errStr, err) } } // Store the block hash by block height. height := make([]byte, 4) binary.BigEndian.PutUint32(height, uint32(bs.Height)) err := bucket.Put(height, bs.Hash[0:32]) if err != nil { return managerError(ErrDatabase, errStr, err) } // The serialized synced to format is: // <blockheight><blockhash><timestamp> // // 4 bytes block height + 32 bytes hash length + 4 byte timestamp length buf := make([]byte, 40) binary.LittleEndian.PutUint32(buf[0:4], uint32(bs.Height)) copy(buf[4:36], bs.Hash[0:32]) binary.LittleEndian.PutUint32(buf[36:], uint32(bs.Timestamp.Unix())) err = bucket.Put(syncedToName, buf) if err != nil { return managerError(ErrDatabase, errStr, err) } return nil }
[ "func", "PutSyncedTo", "(", "ns", "walletdb", ".", "ReadWriteBucket", ",", "bs", "*", "BlockStamp", ")", "error", "{", "bucket", ":=", "ns", ".", "NestedReadWriteBucket", "(", "syncBucketName", ")", "\n", "errStr", ":=", "fmt", ".", "Sprintf", "(", "\"failed...
// PutSyncedTo stores the provided synced to blockstamp to the database.
[ "PutSyncedTo", "stores", "the", "provided", "synced", "to", "blockstamp", "to", "the", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1834-L1870
train
btcsuite/btcwallet
waddrmgr/db.go
fetchBlockHash
func fetchBlockHash(ns walletdb.ReadBucket, height int32) (*chainhash.Hash, error) { bucket := ns.NestedReadBucket(syncBucketName) errStr := fmt.Sprintf("failed to fetch block hash for height %d", height) heightBytes := make([]byte, 4) binary.BigEndian.PutUint32(heightBytes, uint32(height)) hashBytes := bucket.Get(heightBytes) if hashBytes == nil { err := errors.New("block not found") return nil, managerError(ErrBlockNotFound, errStr, err) } if len(hashBytes) != 32 { err := fmt.Errorf("couldn't get hash from database") return nil, managerError(ErrDatabase, errStr, err) } var hash chainhash.Hash if err := hash.SetBytes(hashBytes); err != nil { return nil, managerError(ErrDatabase, errStr, err) } return &hash, nil }
go
func fetchBlockHash(ns walletdb.ReadBucket, height int32) (*chainhash.Hash, error) { bucket := ns.NestedReadBucket(syncBucketName) errStr := fmt.Sprintf("failed to fetch block hash for height %d", height) heightBytes := make([]byte, 4) binary.BigEndian.PutUint32(heightBytes, uint32(height)) hashBytes := bucket.Get(heightBytes) if hashBytes == nil { err := errors.New("block not found") return nil, managerError(ErrBlockNotFound, errStr, err) } if len(hashBytes) != 32 { err := fmt.Errorf("couldn't get hash from database") return nil, managerError(ErrDatabase, errStr, err) } var hash chainhash.Hash if err := hash.SetBytes(hashBytes); err != nil { return nil, managerError(ErrDatabase, errStr, err) } return &hash, nil }
[ "func", "fetchBlockHash", "(", "ns", "walletdb", ".", "ReadBucket", ",", "height", "int32", ")", "(", "*", "chainhash", ".", "Hash", ",", "error", ")", "{", "bucket", ":=", "ns", ".", "NestedReadBucket", "(", "syncBucketName", ")", "\n", "errStr", ":=", ...
// fetchBlockHash loads the block hash for the provided height from the // database.
[ "fetchBlockHash", "loads", "the", "block", "hash", "for", "the", "provided", "height", "from", "the", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1874-L1894
train
btcsuite/btcwallet
waddrmgr/db.go
FetchStartBlock
func FetchStartBlock(ns walletdb.ReadBucket) (*BlockStamp, error) { bucket := ns.NestedReadBucket(syncBucketName) // The serialized start block format is: // <blockheight><blockhash> // // 4 bytes block height + 32 bytes hash length buf := bucket.Get(startBlockName) if len(buf) != 36 { str := "malformed start block stored in database" return nil, managerError(ErrDatabase, str, nil) } var bs BlockStamp bs.Height = int32(binary.LittleEndian.Uint32(buf[0:4])) copy(bs.Hash[:], buf[4:36]) return &bs, nil }
go
func FetchStartBlock(ns walletdb.ReadBucket) (*BlockStamp, error) { bucket := ns.NestedReadBucket(syncBucketName) // The serialized start block format is: // <blockheight><blockhash> // // 4 bytes block height + 32 bytes hash length buf := bucket.Get(startBlockName) if len(buf) != 36 { str := "malformed start block stored in database" return nil, managerError(ErrDatabase, str, nil) } var bs BlockStamp bs.Height = int32(binary.LittleEndian.Uint32(buf[0:4])) copy(bs.Hash[:], buf[4:36]) return &bs, nil }
[ "func", "FetchStartBlock", "(", "ns", "walletdb", ".", "ReadBucket", ")", "(", "*", "BlockStamp", ",", "error", ")", "{", "bucket", ":=", "ns", ".", "NestedReadBucket", "(", "syncBucketName", ")", "\n", "buf", ":=", "bucket", ".", "Get", "(", "startBlockNa...
// FetchStartBlock loads the start block stamp for the manager from the // database.
[ "FetchStartBlock", "loads", "the", "start", "block", "stamp", "for", "the", "manager", "from", "the", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1898-L1915
train
btcsuite/btcwallet
waddrmgr/db.go
putStartBlock
func putStartBlock(ns walletdb.ReadWriteBucket, bs *BlockStamp) error { bucket := ns.NestedReadWriteBucket(syncBucketName) // The serialized start block format is: // <blockheight><blockhash> // // 4 bytes block height + 32 bytes hash length buf := make([]byte, 36) binary.LittleEndian.PutUint32(buf[0:4], uint32(bs.Height)) copy(buf[4:36], bs.Hash[0:32]) err := bucket.Put(startBlockName, buf) if err != nil { str := fmt.Sprintf("failed to store start block %v", bs.Hash) return managerError(ErrDatabase, str, err) } return nil }
go
func putStartBlock(ns walletdb.ReadWriteBucket, bs *BlockStamp) error { bucket := ns.NestedReadWriteBucket(syncBucketName) // The serialized start block format is: // <blockheight><blockhash> // // 4 bytes block height + 32 bytes hash length buf := make([]byte, 36) binary.LittleEndian.PutUint32(buf[0:4], uint32(bs.Height)) copy(buf[4:36], bs.Hash[0:32]) err := bucket.Put(startBlockName, buf) if err != nil { str := fmt.Sprintf("failed to store start block %v", bs.Hash) return managerError(ErrDatabase, str, err) } return nil }
[ "func", "putStartBlock", "(", "ns", "walletdb", ".", "ReadWriteBucket", ",", "bs", "*", "BlockStamp", ")", "error", "{", "bucket", ":=", "ns", ".", "NestedReadWriteBucket", "(", "syncBucketName", ")", "\n", "buf", ":=", "make", "(", "[", "]", "byte", ",", ...
// putStartBlock stores the provided start block stamp to the database.
[ "putStartBlock", "stores", "the", "provided", "start", "block", "stamp", "to", "the", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1918-L1935
train
btcsuite/btcwallet
waddrmgr/db.go
fetchBirthday
func fetchBirthday(ns walletdb.ReadBucket) (time.Time, error) { var t time.Time bucket := ns.NestedReadBucket(syncBucketName) birthdayTimestamp := bucket.Get(birthdayName) if len(birthdayTimestamp) != 8 { str := "malformed birthday stored in database" return t, managerError(ErrDatabase, str, nil) } t = time.Unix(int64(binary.BigEndian.Uint64(birthdayTimestamp)), 0) return t, nil }
go
func fetchBirthday(ns walletdb.ReadBucket) (time.Time, error) { var t time.Time bucket := ns.NestedReadBucket(syncBucketName) birthdayTimestamp := bucket.Get(birthdayName) if len(birthdayTimestamp) != 8 { str := "malformed birthday stored in database" return t, managerError(ErrDatabase, str, nil) } t = time.Unix(int64(binary.BigEndian.Uint64(birthdayTimestamp)), 0) return t, nil }
[ "func", "fetchBirthday", "(", "ns", "walletdb", ".", "ReadBucket", ")", "(", "time", ".", "Time", ",", "error", ")", "{", "var", "t", "time", ".", "Time", "\n", "bucket", ":=", "ns", ".", "NestedReadBucket", "(", "syncBucketName", ")", "\n", "birthdayTim...
// fetchBirthday loads the manager's bithday timestamp from the database.
[ "fetchBirthday", "loads", "the", "manager", "s", "bithday", "timestamp", "from", "the", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1938-L1951
train
btcsuite/btcwallet
waddrmgr/db.go
putBirthday
func putBirthday(ns walletdb.ReadWriteBucket, t time.Time) error { var birthdayTimestamp [8]byte binary.BigEndian.PutUint64(birthdayTimestamp[:], uint64(t.Unix())) bucket := ns.NestedReadWriteBucket(syncBucketName) if err := bucket.Put(birthdayName, birthdayTimestamp[:]); err != nil { str := "failed to store birthday" return managerError(ErrDatabase, str, err) } return nil }
go
func putBirthday(ns walletdb.ReadWriteBucket, t time.Time) error { var birthdayTimestamp [8]byte binary.BigEndian.PutUint64(birthdayTimestamp[:], uint64(t.Unix())) bucket := ns.NestedReadWriteBucket(syncBucketName) if err := bucket.Put(birthdayName, birthdayTimestamp[:]); err != nil { str := "failed to store birthday" return managerError(ErrDatabase, str, err) } return nil }
[ "func", "putBirthday", "(", "ns", "walletdb", ".", "ReadWriteBucket", ",", "t", "time", ".", "Time", ")", "error", "{", "var", "birthdayTimestamp", "[", "8", "]", "byte", "\n", "binary", ".", "BigEndian", ".", "PutUint64", "(", "birthdayTimestamp", "[", ":...
// putBirthday stores the provided birthday timestamp to the database.
[ "putBirthday", "stores", "the", "provided", "birthday", "timestamp", "to", "the", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1954-L1965
train
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", ")...
// 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", "{", "verifiedValue", ":=", "uint16", "(", "0", ")", "\n", "if", "verified", "{", "verifiedValue", "=", "1", "\n", "}", "\n", "var",...
// 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", "mainBucke...
// 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", "{", "scopeKey", ":=", "scopeToBytes", "(", "scope", ")", "\n", "scopeBucket", ",", "err", ":=", "ns", ".", "CreateBucket", "(", "sco...
// 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", "perfor...
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", "{", "mainBucket", ",", "err", ":=", "ns", ".", "CreateBucket", "(", "mainBucketName", ")", "\n", "if"...
// 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", "cr...
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", ")", "{", "_", ",", "e", ":=", "os", ".", "Stat", "(", "cfg", ".", "RPCKey", ".", "Value", ")", "\n", "keyExists", ":=", "!", "os", ".", "IsNotExist", "(", "e", ")"...
// 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", "(", "\"Generating TLS certificates...\"", ")", "\n", "certDir", ",", "_", ":=", "filepath", ".", "Split", "(", "cfg", ...
// 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", ...
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", ")",...
// 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", "...
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", ")", "{", "a", ".", "privKeyMutex", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "privKeyMutex", ".", "Unlock", "("...
// 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"...
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", "switch", "n", ":=", "a", ".", "address", ".", "(", "type", ")", "{", "case", "*", "btcutil", ".", "AddressPubKeyHash"...
// 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", ".", ...
// 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", ")", "{", "if", "a", ".", "manager", ".", "rootManager", ".", "WatchOnly", "(", ")", "{", "return", "nil", ",", "managerError", "("...
// 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",...
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", "if", "a", ".", "imported", "{", ...
// 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"...
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", ",", "...
// 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", ")...
// 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"...
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", ")", "{", "var", ...
// 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", ...
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", ")", "{", "a", ".", "scriptMutex", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "scriptMutex", ".", "Unlock", "(", ...
// 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", "...
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", ")", "{", "if", "a", ".", "manager", ".", "rootManager", ".", "WatchOnly", "(", ")", "{", "return", "nil", ",", "managerError", "(", "ErrWatchingOnl...
// 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", ".", "NewA...
// 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", "{", "case", "bbolt", ".", "ErrDatabaseNotOpen", ":", "return", "walletdb", ".", "ErrDbNotOpen", "\n", "case", "bbolt", ".", "ErrInvalid", ":", "return", "walletdb", ".", "ErrInva...
// 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",...
// 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", "interfa...
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 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", "ErrIncom...
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", "doe...
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", "-", ...
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",...
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", ")", ...
// 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", "...
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"...
// 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", "...
// 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", "...
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", "(",...
// 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", ...
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", "(", "\"Attempting RPC client connection to %v\"", ",", "cfg", ".", "RPCConnect", ")", "\n", "rpcc", ",", "err",...
// 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", "...
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", "(", "[", "...
// 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", ...
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", ")", ...
// 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", "(", "...
// 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", "o...
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", ".", ...
// 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", "case", "v", ".", "minor", "<", "v2", ".", "minor", ":", "return", "...
// 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", ")", "{", "if", "len", "(", "des...
// 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",...
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", "...
// 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", "if", "s", ".", "flags", ".", "watch...
// 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", "...
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", "if", "s", ".", "flags", ".", "watchingOnly", "{", ...
// 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", "if", "s", ".", "flags", ".", "wa...
// 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", "(", ")",...
// 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", "...
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", "(", ")", "\...
// 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", "return", "s", ".", "chainIdxMap", "[", ...
// 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", "{", "a", ":=", "s", ".", "chainIdxMap", "[", "s", ".", "lastChainIdx", "]", "\n", "waddr", ",", "ok", ":=", "s", ".", "addrMap", "[", "getAddressKey",...
// 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", "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", "wa", ...
// 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", "uns...
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", "if", "bs", "==", "nil", "{", "s", ".", "rece...
// 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",...
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", "return", "s", ".", "recent", ".", "iter", ...
// 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"...
// 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", "Comp...
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", ".", "m...
// 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", "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", "...
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", "addrs", ":=", "make", "(", "[", "]",...
// 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"...
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", "addrs", ...
// 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", "u...
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", ")", ...
// 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", "(", "\"private key unavailable\"", ")", "\n", "}", "\n", "privKey", ":="...
// 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", "fa...
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", "var", "chkPubKeyHash", "uint32", "\n", "var", "chkChaincode", "uint32", "\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", ")", "!...
// 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...
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", "(", "\"unable to lock unencrypted address\"", ")", "\n", "}", "\n", "zero", "(", "a", ".", ...
// 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", ".", ...
// 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", "p...
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", "{", "if", "!", "a", ".", "flags", ".", "hasPrivKey", "{", "return", "errors", ".", "New", "(", "\"no 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.
[ "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", "th...
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", ...
// 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", ...
// 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...
// 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...
// 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", "[", ...
// 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", "<<", ...
// 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", "var", "chkScriptHash", "uint32", "\n", "var", "chkScript", "uint32", "\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", "hash", ":=", "sa", ".", "address", ".", "ScriptAddress", "(", ")", "\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", ".", "firstBlo...
// 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", ".", ...
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", ".", "addre...
// 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", "(", "...
// 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", ...
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", "if", "written", ",", "err", "=", "binaryWrite", "(", "w", ",", "binary", ...
// 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", "if", "read", ",", "err", "=", "binaryRead", "(", "r", ",", "binary", ".", ...
// 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", "{", "nExAddrs", ":=", "len", "(", "req", ".", "ExternalAddrs", ")", "\n", "exReverseFilter", ":=", "make", "(", "ma...
// 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...
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", ".",...
// 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", "...
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", "for", "_", ",", "in", ":=", "range", "tx", ".", "TxIn", "{", "if", "_", ",", "ok", ":=", "bf", ...
// 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...
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/chain/block_filterer.go#L125-L175
train