repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
btcsuite/btcwallet
wallet/wallet.go
PublishTransaction
func (w *Wallet) PublishTransaction(tx *wire.MsgTx) error { _, err := w.reliablyPublishTransaction(tx) return err }
go
func (w *Wallet) PublishTransaction(tx *wire.MsgTx) error { _, err := w.reliablyPublishTransaction(tx) return err }
[ "func", "(", "w", "*", "Wallet", ")", "PublishTransaction", "(", "tx", "*", "wire", ".", "MsgTx", ")", "error", "{", "_", ",", "err", ":=", "w", ".", "reliablyPublishTransaction", "(", "tx", ")", "\n", "return", "err", "\n", "}" ]
// PublishTransaction sends the transaction to the consensus RPC server so it // can be propagated to other nodes and eventually mined. // // This function is unstable and will be removed once syncing code is moved out // of the wallet.
[ "PublishTransaction", "sends", "the", "transaction", "to", "the", "consensus", "RPC", "server", "so", "it", "can", "be", "propagated", "to", "other", "nodes", "and", "eventually", "mined", ".", "This", "function", "is", "unstable", "and", "will", "be", "removed", "once", "syncing", "code", "is", "moved", "out", "of", "the", "wallet", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L3346-L3349
train
btcsuite/btcwallet
wallet/wallet.go
publishTransaction
func (w *Wallet) publishTransaction(tx *wire.MsgTx) (*chainhash.Hash, error) { chainClient, err := w.requireChainClient() if err != nil { return nil, err } txid, err := chainClient.SendRawTransaction(tx, false) switch { case err == nil: return txid, nil // Since we have different backends that can be used with the wallet, // we'll need to check specific errors for each one. // // If the transaction is already in the mempool, we can just return now. // // This error is returned when broadcasting/sending a transaction to a // btcd node that already has it in their mempool. case strings.Contains(err.Error(), "already have transaction"): fallthrough // This error is returned when broadcasting a transaction to a bitcoind // node that already has it in their mempool. case strings.Contains(err.Error(), "txn-already-in-mempool"): return txid, nil // If the transaction has already confirmed, we can safely remove it // from the unconfirmed store as it should already exist within the // confirmed store. We'll avoid returning an error as the broadcast was // in a sense successful. // // This error is returned when broadcasting/sending a transaction that // has already confirmed to a btcd node. case strings.Contains(err.Error(), "transaction already exists"): fallthrough // This error is returned when broadcasting a transaction that has // already confirmed to a bitcoind node. case strings.Contains(err.Error(), "txn-already-known"): fallthrough // This error is returned when sending a transaction that has already // confirmed to a bitcoind node over RPC. case strings.Contains(err.Error(), "transaction already in block chain"): dbErr := walletdb.Update(w.db, func(dbTx walletdb.ReadWriteTx) error { txmgrNs := dbTx.ReadWriteBucket(wtxmgrNamespaceKey) txRec, err := wtxmgr.NewTxRecordFromMsgTx(tx, time.Now()) if err != nil { return err } return w.TxStore.RemoveUnminedTx(txmgrNs, txRec) }) if dbErr != nil { log.Warnf("Unable to remove confirmed transaction %v "+ "from unconfirmed store: %v", tx.TxHash(), dbErr) } return txid, nil // If the transaction was rejected for whatever other reason, then we'll // remove it from the transaction store, as otherwise, we'll attempt to // continually re-broadcast it, and the UTXO state of the wallet won't // be accurate. default: dbErr := walletdb.Update(w.db, func(dbTx walletdb.ReadWriteTx) error { txmgrNs := dbTx.ReadWriteBucket(wtxmgrNamespaceKey) txRec, err := wtxmgr.NewTxRecordFromMsgTx(tx, time.Now()) if err != nil { return err } return w.TxStore.RemoveUnminedTx(txmgrNs, txRec) }) if dbErr != nil { log.Warnf("Unable to remove invalid transaction %v: %v", tx.TxHash(), dbErr) } else { log.Infof("Removed invalid transaction: %v", spew.Sdump(tx)) } return nil, err } }
go
func (w *Wallet) publishTransaction(tx *wire.MsgTx) (*chainhash.Hash, error) { chainClient, err := w.requireChainClient() if err != nil { return nil, err } txid, err := chainClient.SendRawTransaction(tx, false) switch { case err == nil: return txid, nil // Since we have different backends that can be used with the wallet, // we'll need to check specific errors for each one. // // If the transaction is already in the mempool, we can just return now. // // This error is returned when broadcasting/sending a transaction to a // btcd node that already has it in their mempool. case strings.Contains(err.Error(), "already have transaction"): fallthrough // This error is returned when broadcasting a transaction to a bitcoind // node that already has it in their mempool. case strings.Contains(err.Error(), "txn-already-in-mempool"): return txid, nil // If the transaction has already confirmed, we can safely remove it // from the unconfirmed store as it should already exist within the // confirmed store. We'll avoid returning an error as the broadcast was // in a sense successful. // // This error is returned when broadcasting/sending a transaction that // has already confirmed to a btcd node. case strings.Contains(err.Error(), "transaction already exists"): fallthrough // This error is returned when broadcasting a transaction that has // already confirmed to a bitcoind node. case strings.Contains(err.Error(), "txn-already-known"): fallthrough // This error is returned when sending a transaction that has already // confirmed to a bitcoind node over RPC. case strings.Contains(err.Error(), "transaction already in block chain"): dbErr := walletdb.Update(w.db, func(dbTx walletdb.ReadWriteTx) error { txmgrNs := dbTx.ReadWriteBucket(wtxmgrNamespaceKey) txRec, err := wtxmgr.NewTxRecordFromMsgTx(tx, time.Now()) if err != nil { return err } return w.TxStore.RemoveUnminedTx(txmgrNs, txRec) }) if dbErr != nil { log.Warnf("Unable to remove confirmed transaction %v "+ "from unconfirmed store: %v", tx.TxHash(), dbErr) } return txid, nil // If the transaction was rejected for whatever other reason, then we'll // remove it from the transaction store, as otherwise, we'll attempt to // continually re-broadcast it, and the UTXO state of the wallet won't // be accurate. default: dbErr := walletdb.Update(w.db, func(dbTx walletdb.ReadWriteTx) error { txmgrNs := dbTx.ReadWriteBucket(wtxmgrNamespaceKey) txRec, err := wtxmgr.NewTxRecordFromMsgTx(tx, time.Now()) if err != nil { return err } return w.TxStore.RemoveUnminedTx(txmgrNs, txRec) }) if dbErr != nil { log.Warnf("Unable to remove invalid transaction %v: %v", tx.TxHash(), dbErr) } else { log.Infof("Removed invalid transaction: %v", spew.Sdump(tx)) } return nil, err } }
[ "func", "(", "w", "*", "Wallet", ")", "publishTransaction", "(", "tx", "*", "wire", ".", "MsgTx", ")", "(", "*", "chainhash", ".", "Hash", ",", "error", ")", "{", "chainClient", ",", "err", ":=", "w", ".", "requireChainClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "txid", ",", "err", ":=", "chainClient", ".", "SendRawTransaction", "(", "tx", ",", "false", ")", "\n", "switch", "{", "case", "err", "==", "nil", ":", "return", "txid", ",", "nil", "\n\n", "// Since we have different backends that can be used with the wallet,", "// we'll need to check specific errors for each one.", "//", "// If the transaction is already in the mempool, we can just return now.", "//", "// This error is returned when broadcasting/sending a transaction to a", "// btcd node that already has it in their mempool.", "case", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", ":", "fallthrough", "\n\n", "// This error is returned when broadcasting a transaction to a bitcoind", "// node that already has it in their mempool.", "case", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", ":", "return", "txid", ",", "nil", "\n\n", "// If the transaction has already confirmed, we can safely remove it", "// from the unconfirmed store as it should already exist within the", "// confirmed store. We'll avoid returning an error as the broadcast was", "// in a sense successful.", "//", "// This error is returned when broadcasting/sending a transaction that", "// has already confirmed to a btcd node.", "case", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", ":", "fallthrough", "\n\n", "// This error is returned when broadcasting a transaction that has", "// already confirmed to a bitcoind node.", "case", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", ":", "fallthrough", "\n\n", "// This error is returned when sending a transaction that has already", "// confirmed to a bitcoind node over RPC.", "case", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", ":", "dbErr", ":=", "walletdb", ".", "Update", "(", "w", ".", "db", ",", "func", "(", "dbTx", "walletdb", ".", "ReadWriteTx", ")", "error", "{", "txmgrNs", ":=", "dbTx", ".", "ReadWriteBucket", "(", "wtxmgrNamespaceKey", ")", "\n", "txRec", ",", "err", ":=", "wtxmgr", ".", "NewTxRecordFromMsgTx", "(", "tx", ",", "time", ".", "Now", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "w", ".", "TxStore", ".", "RemoveUnminedTx", "(", "txmgrNs", ",", "txRec", ")", "\n", "}", ")", "\n", "if", "dbErr", "!=", "nil", "{", "log", ".", "Warnf", "(", "\"", "\"", "+", "\"", "\"", ",", "tx", ".", "TxHash", "(", ")", ",", "dbErr", ")", "\n", "}", "\n\n", "return", "txid", ",", "nil", "\n\n", "// If the transaction was rejected for whatever other reason, then we'll", "// remove it from the transaction store, as otherwise, we'll attempt to", "// continually re-broadcast it, and the UTXO state of the wallet won't", "// be accurate.", "default", ":", "dbErr", ":=", "walletdb", ".", "Update", "(", "w", ".", "db", ",", "func", "(", "dbTx", "walletdb", ".", "ReadWriteTx", ")", "error", "{", "txmgrNs", ":=", "dbTx", ".", "ReadWriteBucket", "(", "wtxmgrNamespaceKey", ")", "\n", "txRec", ",", "err", ":=", "wtxmgr", ".", "NewTxRecordFromMsgTx", "(", "tx", ",", "time", ".", "Now", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "w", ".", "TxStore", ".", "RemoveUnminedTx", "(", "txmgrNs", ",", "txRec", ")", "\n", "}", ")", "\n", "if", "dbErr", "!=", "nil", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "tx", ".", "TxHash", "(", ")", ",", "dbErr", ")", "\n", "}", "else", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "spew", ".", "Sdump", "(", "tx", ")", ")", "\n", "}", "\n\n", "return", "nil", ",", "err", "\n", "}", "\n", "}" ]
// publishTransaction attempts to send an unconfirmed transaction to the // wallet's current backend. In the event that sending the transaction fails for // whatever reason, it will be removed from the wallet's unconfirmed transaction // store.
[ "publishTransaction", "attempts", "to", "send", "an", "unconfirmed", "transaction", "to", "the", "wallet", "s", "current", "backend", ".", "In", "the", "event", "that", "sending", "the", "transaction", "fails", "for", "whatever", "reason", "it", "will", "be", "removed", "from", "the", "wallet", "s", "unconfirmed", "transaction", "store", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L3410-L3492
train
btcsuite/btcwallet
wallet/wallet.go
Create
func Create(db walletdb.DB, pubPass, privPass, seed []byte, params *chaincfg.Params, birthday time.Time) error { // If a seed was provided, ensure that it is of valid length. Otherwise, // we generate a random seed for the wallet with the recommended seed // length. if seed == nil { hdSeed, err := hdkeychain.GenerateSeed( hdkeychain.RecommendedSeedLen) if err != nil { return err } seed = hdSeed } if len(seed) < hdkeychain.MinSeedBytes || len(seed) > hdkeychain.MaxSeedBytes { return hdkeychain.ErrInvalidSeedLen } return walletdb.Update(db, func(tx walletdb.ReadWriteTx) error { addrmgrNs, err := tx.CreateTopLevelBucket(waddrmgrNamespaceKey) if err != nil { return err } txmgrNs, err := tx.CreateTopLevelBucket(wtxmgrNamespaceKey) if err != nil { return err } err = waddrmgr.Create( addrmgrNs, seed, pubPass, privPass, params, nil, birthday, ) if err != nil { return err } return wtxmgr.Create(txmgrNs) }) }
go
func Create(db walletdb.DB, pubPass, privPass, seed []byte, params *chaincfg.Params, birthday time.Time) error { // If a seed was provided, ensure that it is of valid length. Otherwise, // we generate a random seed for the wallet with the recommended seed // length. if seed == nil { hdSeed, err := hdkeychain.GenerateSeed( hdkeychain.RecommendedSeedLen) if err != nil { return err } seed = hdSeed } if len(seed) < hdkeychain.MinSeedBytes || len(seed) > hdkeychain.MaxSeedBytes { return hdkeychain.ErrInvalidSeedLen } return walletdb.Update(db, func(tx walletdb.ReadWriteTx) error { addrmgrNs, err := tx.CreateTopLevelBucket(waddrmgrNamespaceKey) if err != nil { return err } txmgrNs, err := tx.CreateTopLevelBucket(wtxmgrNamespaceKey) if err != nil { return err } err = waddrmgr.Create( addrmgrNs, seed, pubPass, privPass, params, nil, birthday, ) if err != nil { return err } return wtxmgr.Create(txmgrNs) }) }
[ "func", "Create", "(", "db", "walletdb", ".", "DB", ",", "pubPass", ",", "privPass", ",", "seed", "[", "]", "byte", ",", "params", "*", "chaincfg", ".", "Params", ",", "birthday", "time", ".", "Time", ")", "error", "{", "// If a seed was provided, ensure that it is of valid length. Otherwise,", "// we generate a random seed for the wallet with the recommended seed", "// length.", "if", "seed", "==", "nil", "{", "hdSeed", ",", "err", ":=", "hdkeychain", ".", "GenerateSeed", "(", "hdkeychain", ".", "RecommendedSeedLen", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "seed", "=", "hdSeed", "\n", "}", "\n", "if", "len", "(", "seed", ")", "<", "hdkeychain", ".", "MinSeedBytes", "||", "len", "(", "seed", ")", ">", "hdkeychain", ".", "MaxSeedBytes", "{", "return", "hdkeychain", ".", "ErrInvalidSeedLen", "\n", "}", "\n\n", "return", "walletdb", ".", "Update", "(", "db", ",", "func", "(", "tx", "walletdb", ".", "ReadWriteTx", ")", "error", "{", "addrmgrNs", ",", "err", ":=", "tx", ".", "CreateTopLevelBucket", "(", "waddrmgrNamespaceKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "txmgrNs", ",", "err", ":=", "tx", ".", "CreateTopLevelBucket", "(", "wtxmgrNamespaceKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "err", "=", "waddrmgr", ".", "Create", "(", "addrmgrNs", ",", "seed", ",", "pubPass", ",", "privPass", ",", "params", ",", "nil", ",", "birthday", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "wtxmgr", ".", "Create", "(", "txmgrNs", ")", "\n", "}", ")", "\n", "}" ]
// Create creates an new wallet, writing it to an empty database. If the passed // seed is non-nil, it is used. Otherwise, a secure random seed of the // recommended length is generated.
[ "Create", "creates", "an", "new", "wallet", "writing", "it", "to", "an", "empty", "database", ".", "If", "the", "passed", "seed", "is", "non", "-", "nil", "it", "is", "used", ".", "Otherwise", "a", "secure", "random", "seed", "of", "the", "recommended", "length", "is", "generated", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L3510-L3548
train
btcsuite/btcwallet
wallet/wallet.go
Open
func Open(db walletdb.DB, pubPass []byte, cbs *waddrmgr.OpenCallbacks, params *chaincfg.Params, recoveryWindow uint32) (*Wallet, error) { var ( addrMgr *waddrmgr.Manager txMgr *wtxmgr.Store ) // Before attempting to open the wallet, we'll check if there are any // database upgrades for us to proceed. We'll also create our references // to the address and transaction managers, as they are backed by the // database. err := walletdb.Update(db, func(tx walletdb.ReadWriteTx) error { addrMgrBucket := tx.ReadWriteBucket(waddrmgrNamespaceKey) if addrMgrBucket == nil { return errors.New("missing address manager namespace") } txMgrBucket := tx.ReadWriteBucket(wtxmgrNamespaceKey) if txMgrBucket == nil { return errors.New("missing transaction manager namespace") } addrMgrUpgrader := waddrmgr.NewMigrationManager(addrMgrBucket) txMgrUpgrader := wtxmgr.NewMigrationManager(txMgrBucket) err := migration.Upgrade(txMgrUpgrader, addrMgrUpgrader) if err != nil { return err } addrMgr, err = waddrmgr.Open(addrMgrBucket, pubPass, params) if err != nil { return err } txMgr, err = wtxmgr.Open(txMgrBucket, params) if err != nil { return err } return nil }) if err != nil { return nil, err } log.Infof("Opened wallet") // TODO: log balance? last sync height? w := &Wallet{ publicPassphrase: pubPass, db: db, Manager: addrMgr, TxStore: txMgr, lockedOutpoints: map[wire.OutPoint]struct{}{}, recoveryWindow: recoveryWindow, rescanAddJob: make(chan *RescanJob), rescanBatch: make(chan *rescanBatch), rescanNotifications: make(chan interface{}), rescanProgress: make(chan *RescanProgressMsg), rescanFinished: make(chan *RescanFinishedMsg), createTxRequests: make(chan createTxRequest), unlockRequests: make(chan unlockRequest), lockRequests: make(chan struct{}), holdUnlockRequests: make(chan chan heldUnlock), lockState: make(chan bool), changePassphrase: make(chan changePassphraseRequest), changePassphrases: make(chan changePassphrasesRequest), chainParams: params, quit: make(chan struct{}), } w.NtfnServer = newNotificationServer(w) w.TxStore.NotifyUnspent = func(hash *chainhash.Hash, index uint32) { w.NtfnServer.notifyUnspentOutput(0, hash, index) } return w, nil }
go
func Open(db walletdb.DB, pubPass []byte, cbs *waddrmgr.OpenCallbacks, params *chaincfg.Params, recoveryWindow uint32) (*Wallet, error) { var ( addrMgr *waddrmgr.Manager txMgr *wtxmgr.Store ) // Before attempting to open the wallet, we'll check if there are any // database upgrades for us to proceed. We'll also create our references // to the address and transaction managers, as they are backed by the // database. err := walletdb.Update(db, func(tx walletdb.ReadWriteTx) error { addrMgrBucket := tx.ReadWriteBucket(waddrmgrNamespaceKey) if addrMgrBucket == nil { return errors.New("missing address manager namespace") } txMgrBucket := tx.ReadWriteBucket(wtxmgrNamespaceKey) if txMgrBucket == nil { return errors.New("missing transaction manager namespace") } addrMgrUpgrader := waddrmgr.NewMigrationManager(addrMgrBucket) txMgrUpgrader := wtxmgr.NewMigrationManager(txMgrBucket) err := migration.Upgrade(txMgrUpgrader, addrMgrUpgrader) if err != nil { return err } addrMgr, err = waddrmgr.Open(addrMgrBucket, pubPass, params) if err != nil { return err } txMgr, err = wtxmgr.Open(txMgrBucket, params) if err != nil { return err } return nil }) if err != nil { return nil, err } log.Infof("Opened wallet") // TODO: log balance? last sync height? w := &Wallet{ publicPassphrase: pubPass, db: db, Manager: addrMgr, TxStore: txMgr, lockedOutpoints: map[wire.OutPoint]struct{}{}, recoveryWindow: recoveryWindow, rescanAddJob: make(chan *RescanJob), rescanBatch: make(chan *rescanBatch), rescanNotifications: make(chan interface{}), rescanProgress: make(chan *RescanProgressMsg), rescanFinished: make(chan *RescanFinishedMsg), createTxRequests: make(chan createTxRequest), unlockRequests: make(chan unlockRequest), lockRequests: make(chan struct{}), holdUnlockRequests: make(chan chan heldUnlock), lockState: make(chan bool), changePassphrase: make(chan changePassphraseRequest), changePassphrases: make(chan changePassphrasesRequest), chainParams: params, quit: make(chan struct{}), } w.NtfnServer = newNotificationServer(w) w.TxStore.NotifyUnspent = func(hash *chainhash.Hash, index uint32) { w.NtfnServer.notifyUnspentOutput(0, hash, index) } return w, nil }
[ "func", "Open", "(", "db", "walletdb", ".", "DB", ",", "pubPass", "[", "]", "byte", ",", "cbs", "*", "waddrmgr", ".", "OpenCallbacks", ",", "params", "*", "chaincfg", ".", "Params", ",", "recoveryWindow", "uint32", ")", "(", "*", "Wallet", ",", "error", ")", "{", "var", "(", "addrMgr", "*", "waddrmgr", ".", "Manager", "\n", "txMgr", "*", "wtxmgr", ".", "Store", "\n", ")", "\n\n", "// Before attempting to open the wallet, we'll check if there are any", "// database upgrades for us to proceed. We'll also create our references", "// to the address and transaction managers, as they are backed by the", "// database.", "err", ":=", "walletdb", ".", "Update", "(", "db", ",", "func", "(", "tx", "walletdb", ".", "ReadWriteTx", ")", "error", "{", "addrMgrBucket", ":=", "tx", ".", "ReadWriteBucket", "(", "waddrmgrNamespaceKey", ")", "\n", "if", "addrMgrBucket", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "txMgrBucket", ":=", "tx", ".", "ReadWriteBucket", "(", "wtxmgrNamespaceKey", ")", "\n", "if", "txMgrBucket", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "addrMgrUpgrader", ":=", "waddrmgr", ".", "NewMigrationManager", "(", "addrMgrBucket", ")", "\n", "txMgrUpgrader", ":=", "wtxmgr", ".", "NewMigrationManager", "(", "txMgrBucket", ")", "\n", "err", ":=", "migration", ".", "Upgrade", "(", "txMgrUpgrader", ",", "addrMgrUpgrader", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "addrMgr", ",", "err", "=", "waddrmgr", ".", "Open", "(", "addrMgrBucket", ",", "pubPass", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "txMgr", ",", "err", "=", "wtxmgr", ".", "Open", "(", "txMgrBucket", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "log", ".", "Infof", "(", "\"", "\"", ")", "// TODO: log balance? last sync height?", "\n\n", "w", ":=", "&", "Wallet", "{", "publicPassphrase", ":", "pubPass", ",", "db", ":", "db", ",", "Manager", ":", "addrMgr", ",", "TxStore", ":", "txMgr", ",", "lockedOutpoints", ":", "map", "[", "wire", ".", "OutPoint", "]", "struct", "{", "}", "{", "}", ",", "recoveryWindow", ":", "recoveryWindow", ",", "rescanAddJob", ":", "make", "(", "chan", "*", "RescanJob", ")", ",", "rescanBatch", ":", "make", "(", "chan", "*", "rescanBatch", ")", ",", "rescanNotifications", ":", "make", "(", "chan", "interface", "{", "}", ")", ",", "rescanProgress", ":", "make", "(", "chan", "*", "RescanProgressMsg", ")", ",", "rescanFinished", ":", "make", "(", "chan", "*", "RescanFinishedMsg", ")", ",", "createTxRequests", ":", "make", "(", "chan", "createTxRequest", ")", ",", "unlockRequests", ":", "make", "(", "chan", "unlockRequest", ")", ",", "lockRequests", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "holdUnlockRequests", ":", "make", "(", "chan", "chan", "heldUnlock", ")", ",", "lockState", ":", "make", "(", "chan", "bool", ")", ",", "changePassphrase", ":", "make", "(", "chan", "changePassphraseRequest", ")", ",", "changePassphrases", ":", "make", "(", "chan", "changePassphrasesRequest", ")", ",", "chainParams", ":", "params", ",", "quit", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n\n", "w", ".", "NtfnServer", "=", "newNotificationServer", "(", "w", ")", "\n", "w", ".", "TxStore", ".", "NotifyUnspent", "=", "func", "(", "hash", "*", "chainhash", ".", "Hash", ",", "index", "uint32", ")", "{", "w", ".", "NtfnServer", ".", "notifyUnspentOutput", "(", "0", ",", "hash", ",", "index", ")", "\n", "}", "\n\n", "return", "w", ",", "nil", "\n", "}" ]
// Open loads an already-created wallet from the passed database and namespaces.
[ "Open", "loads", "an", "already", "-", "created", "wallet", "from", "the", "passed", "database", "and", "namespaces", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/wallet.go#L3551-L3626
train
btcsuite/btcwallet
internal/helpers/helpers.go
SumOutputValues
func SumOutputValues(outputs []*wire.TxOut) (totalOutput btcutil.Amount) { for _, txOut := range outputs { totalOutput += btcutil.Amount(txOut.Value) } return totalOutput }
go
func SumOutputValues(outputs []*wire.TxOut) (totalOutput btcutil.Amount) { for _, txOut := range outputs { totalOutput += btcutil.Amount(txOut.Value) } return totalOutput }
[ "func", "SumOutputValues", "(", "outputs", "[", "]", "*", "wire", ".", "TxOut", ")", "(", "totalOutput", "btcutil", ".", "Amount", ")", "{", "for", "_", ",", "txOut", ":=", "range", "outputs", "{", "totalOutput", "+=", "btcutil", ".", "Amount", "(", "txOut", ".", "Value", ")", "\n", "}", "\n", "return", "totalOutput", "\n", "}" ]
// SumOutputValues sums up the list of TxOuts and returns an Amount.
[ "SumOutputValues", "sums", "up", "the", "list", "of", "TxOuts", "and", "returns", "an", "Amount", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/helpers/helpers.go#L15-L20
train
btcsuite/btcwallet
internal/helpers/helpers.go
SumOutputSerializeSizes
func SumOutputSerializeSizes(outputs []*wire.TxOut) (serializeSize int) { for _, txOut := range outputs { serializeSize += txOut.SerializeSize() } return serializeSize }
go
func SumOutputSerializeSizes(outputs []*wire.TxOut) (serializeSize int) { for _, txOut := range outputs { serializeSize += txOut.SerializeSize() } return serializeSize }
[ "func", "SumOutputSerializeSizes", "(", "outputs", "[", "]", "*", "wire", ".", "TxOut", ")", "(", "serializeSize", "int", ")", "{", "for", "_", ",", "txOut", ":=", "range", "outputs", "{", "serializeSize", "+=", "txOut", ".", "SerializeSize", "(", ")", "\n", "}", "\n", "return", "serializeSize", "\n", "}" ]
// SumOutputSerializeSizes sums up the serialized size of the supplied outputs.
[ "SumOutputSerializeSizes", "sums", "up", "the", "serialized", "size", "of", "the", "supplied", "outputs", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/internal/helpers/helpers.go#L23-L28
train
btcsuite/btcwallet
wallet/unstable.go
TxDetails
func (u unstableAPI) TxDetails(txHash *chainhash.Hash) (*wtxmgr.TxDetails, error) { var details *wtxmgr.TxDetails err := walletdb.View(u.w.db, func(dbtx walletdb.ReadTx) error { txmgrNs := dbtx.ReadBucket(wtxmgrNamespaceKey) var err error details, err = u.w.TxStore.TxDetails(txmgrNs, txHash) return err }) return details, err }
go
func (u unstableAPI) TxDetails(txHash *chainhash.Hash) (*wtxmgr.TxDetails, error) { var details *wtxmgr.TxDetails err := walletdb.View(u.w.db, func(dbtx walletdb.ReadTx) error { txmgrNs := dbtx.ReadBucket(wtxmgrNamespaceKey) var err error details, err = u.w.TxStore.TxDetails(txmgrNs, txHash) return err }) return details, err }
[ "func", "(", "u", "unstableAPI", ")", "TxDetails", "(", "txHash", "*", "chainhash", ".", "Hash", ")", "(", "*", "wtxmgr", ".", "TxDetails", ",", "error", ")", "{", "var", "details", "*", "wtxmgr", ".", "TxDetails", "\n", "err", ":=", "walletdb", ".", "View", "(", "u", ".", "w", ".", "db", ",", "func", "(", "dbtx", "walletdb", ".", "ReadTx", ")", "error", "{", "txmgrNs", ":=", "dbtx", ".", "ReadBucket", "(", "wtxmgrNamespaceKey", ")", "\n", "var", "err", "error", "\n", "details", ",", "err", "=", "u", ".", "w", ".", "TxStore", ".", "TxDetails", "(", "txmgrNs", ",", "txHash", ")", "\n", "return", "err", "\n", "}", ")", "\n", "return", "details", ",", "err", "\n", "}" ]
// TxDetails calls wtxmgr.Store.TxDetails under a single database view transaction.
[ "TxDetails", "calls", "wtxmgr", ".", "Store", ".", "TxDetails", "under", "a", "single", "database", "view", "transaction", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/unstable.go#L26-L35
train
btcsuite/btcwallet
wallet/unstable.go
RangeTransactions
func (u unstableAPI) RangeTransactions(begin, end int32, f func([]wtxmgr.TxDetails) (bool, error)) error { return walletdb.View(u.w.db, func(dbtx walletdb.ReadTx) error { txmgrNs := dbtx.ReadBucket(wtxmgrNamespaceKey) return u.w.TxStore.RangeTransactions(txmgrNs, begin, end, f) }) }
go
func (u unstableAPI) RangeTransactions(begin, end int32, f func([]wtxmgr.TxDetails) (bool, error)) error { return walletdb.View(u.w.db, func(dbtx walletdb.ReadTx) error { txmgrNs := dbtx.ReadBucket(wtxmgrNamespaceKey) return u.w.TxStore.RangeTransactions(txmgrNs, begin, end, f) }) }
[ "func", "(", "u", "unstableAPI", ")", "RangeTransactions", "(", "begin", ",", "end", "int32", ",", "f", "func", "(", "[", "]", "wtxmgr", ".", "TxDetails", ")", "(", "bool", ",", "error", ")", ")", "error", "{", "return", "walletdb", ".", "View", "(", "u", ".", "w", ".", "db", ",", "func", "(", "dbtx", "walletdb", ".", "ReadTx", ")", "error", "{", "txmgrNs", ":=", "dbtx", ".", "ReadBucket", "(", "wtxmgrNamespaceKey", ")", "\n", "return", "u", ".", "w", ".", "TxStore", ".", "RangeTransactions", "(", "txmgrNs", ",", "begin", ",", "end", ",", "f", ")", "\n", "}", ")", "\n", "}" ]
// RangeTransactions calls wtxmgr.Store.RangeTransactions under a single // database view tranasction.
[ "RangeTransactions", "calls", "wtxmgr", ".", "Store", ".", "RangeTransactions", "under", "a", "single", "database", "view", "tranasction", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/unstable.go#L39-L44
train
btcsuite/btcwallet
cmd/sweepaccount/main.go
init
func init() { // Unset localhost defaults if certificate file can not be found. certFileExists, err := cfgutil.FileExists(opts.RPCCertificateFile) if err != nil { fatalf("%v", err) } if !certFileExists { opts.RPCConnect = "" opts.RPCCertificateFile = "" } _, err = flags.Parse(&opts) if err != nil { os.Exit(1) } if opts.TestNet3 && opts.SimNet { fatalf("Multiple bitcoin networks may not be used simultaneously") } var activeNet = &netparams.MainNetParams if opts.TestNet3 { activeNet = &netparams.TestNet3Params } else if opts.SimNet { activeNet = &netparams.SimNetParams } if opts.RPCConnect == "" { fatalf("RPC hostname[:port] is required") } rpcConnect, err := cfgutil.NormalizeAddress(opts.RPCConnect, activeNet.RPCServerPort) if err != nil { fatalf("Invalid RPC network address `%v`: %v", opts.RPCConnect, err) } opts.RPCConnect = rpcConnect if opts.RPCUsername == "" { fatalf("RPC username is required") } certFileExists, err = cfgutil.FileExists(opts.RPCCertificateFile) if err != nil { fatalf("%v", err) } if !certFileExists { fatalf("RPC certificate file `%s` not found", opts.RPCCertificateFile) } if opts.FeeRate.Amount > 1e6 { fatalf("Fee rate `%v/kB` is exceptionally high", opts.FeeRate.Amount) } if opts.FeeRate.Amount < 1e2 { fatalf("Fee rate `%v/kB` is exceptionally low", opts.FeeRate.Amount) } if opts.SourceAccount == opts.DestinationAccount { fatalf("Source and destination accounts should not be equal") } if opts.RequiredConfirmations < 0 { fatalf("Required confirmations must be non-negative") } }
go
func init() { // Unset localhost defaults if certificate file can not be found. certFileExists, err := cfgutil.FileExists(opts.RPCCertificateFile) if err != nil { fatalf("%v", err) } if !certFileExists { opts.RPCConnect = "" opts.RPCCertificateFile = "" } _, err = flags.Parse(&opts) if err != nil { os.Exit(1) } if opts.TestNet3 && opts.SimNet { fatalf("Multiple bitcoin networks may not be used simultaneously") } var activeNet = &netparams.MainNetParams if opts.TestNet3 { activeNet = &netparams.TestNet3Params } else if opts.SimNet { activeNet = &netparams.SimNetParams } if opts.RPCConnect == "" { fatalf("RPC hostname[:port] is required") } rpcConnect, err := cfgutil.NormalizeAddress(opts.RPCConnect, activeNet.RPCServerPort) if err != nil { fatalf("Invalid RPC network address `%v`: %v", opts.RPCConnect, err) } opts.RPCConnect = rpcConnect if opts.RPCUsername == "" { fatalf("RPC username is required") } certFileExists, err = cfgutil.FileExists(opts.RPCCertificateFile) if err != nil { fatalf("%v", err) } if !certFileExists { fatalf("RPC certificate file `%s` not found", opts.RPCCertificateFile) } if opts.FeeRate.Amount > 1e6 { fatalf("Fee rate `%v/kB` is exceptionally high", opts.FeeRate.Amount) } if opts.FeeRate.Amount < 1e2 { fatalf("Fee rate `%v/kB` is exceptionally low", opts.FeeRate.Amount) } if opts.SourceAccount == opts.DestinationAccount { fatalf("Source and destination accounts should not be equal") } if opts.RequiredConfirmations < 0 { fatalf("Required confirmations must be non-negative") } }
[ "func", "init", "(", ")", "{", "// Unset localhost defaults if certificate file can not be found.", "certFileExists", ",", "err", ":=", "cfgutil", ".", "FileExists", "(", "opts", ".", "RPCCertificateFile", ")", "\n", "if", "err", "!=", "nil", "{", "fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "!", "certFileExists", "{", "opts", ".", "RPCConnect", "=", "\"", "\"", "\n", "opts", ".", "RPCCertificateFile", "=", "\"", "\"", "\n", "}", "\n\n", "_", ",", "err", "=", "flags", ".", "Parse", "(", "&", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n\n", "if", "opts", ".", "TestNet3", "&&", "opts", ".", "SimNet", "{", "fatalf", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "activeNet", "=", "&", "netparams", ".", "MainNetParams", "\n", "if", "opts", ".", "TestNet3", "{", "activeNet", "=", "&", "netparams", ".", "TestNet3Params", "\n", "}", "else", "if", "opts", ".", "SimNet", "{", "activeNet", "=", "&", "netparams", ".", "SimNetParams", "\n", "}", "\n\n", "if", "opts", ".", "RPCConnect", "==", "\"", "\"", "{", "fatalf", "(", "\"", "\"", ")", "\n", "}", "\n", "rpcConnect", ",", "err", ":=", "cfgutil", ".", "NormalizeAddress", "(", "opts", ".", "RPCConnect", ",", "activeNet", ".", "RPCServerPort", ")", "\n", "if", "err", "!=", "nil", "{", "fatalf", "(", "\"", "\"", ",", "opts", ".", "RPCConnect", ",", "err", ")", "\n", "}", "\n", "opts", ".", "RPCConnect", "=", "rpcConnect", "\n\n", "if", "opts", ".", "RPCUsername", "==", "\"", "\"", "{", "fatalf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "certFileExists", ",", "err", "=", "cfgutil", ".", "FileExists", "(", "opts", ".", "RPCCertificateFile", ")", "\n", "if", "err", "!=", "nil", "{", "fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "!", "certFileExists", "{", "fatalf", "(", "\"", "\"", ",", "opts", ".", "RPCCertificateFile", ")", "\n", "}", "\n\n", "if", "opts", ".", "FeeRate", ".", "Amount", ">", "1e6", "{", "fatalf", "(", "\"", "\"", ",", "opts", ".", "FeeRate", ".", "Amount", ")", "\n", "}", "\n", "if", "opts", ".", "FeeRate", ".", "Amount", "<", "1e2", "{", "fatalf", "(", "\"", "\"", ",", "opts", ".", "FeeRate", ".", "Amount", ")", "\n", "}", "\n", "if", "opts", ".", "SourceAccount", "==", "opts", ".", "DestinationAccount", "{", "fatalf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "opts", ".", "RequiredConfirmations", "<", "0", "{", "fatalf", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// Parse and validate flags.
[ "Parse", "and", "validate", "flags", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/cmd/sweepaccount/main.go#L67-L126
train
btcsuite/btcwallet
cmd/sweepaccount/main.go
makeInputSource
func makeInputSource(outputs []btcjson.ListUnspentResult) txauthor.InputSource { var ( totalInputValue btcutil.Amount inputs = make([]*wire.TxIn, 0, len(outputs)) inputValues = make([]btcutil.Amount, 0, len(outputs)) sourceErr error ) for _, output := range outputs { outputAmount, err := btcutil.NewAmount(output.Amount) if err != nil { sourceErr = fmt.Errorf( "invalid amount `%v` in listunspent result", output.Amount) break } if outputAmount == 0 { continue } if !saneOutputValue(outputAmount) { sourceErr = fmt.Errorf( "impossible output amount `%v` in listunspent result", outputAmount) break } totalInputValue += outputAmount previousOutPoint, err := parseOutPoint(&output) if err != nil { sourceErr = fmt.Errorf( "invalid data in listunspent result: %v", err) break } inputs = append(inputs, wire.NewTxIn(&previousOutPoint, nil, nil)) inputValues = append(inputValues, outputAmount) } if sourceErr == nil && totalInputValue == 0 { sourceErr = noInputValue{} } return func(btcutil.Amount) (btcutil.Amount, []*wire.TxIn, []btcutil.Amount, [][]byte, error) { return totalInputValue, inputs, inputValues, nil, sourceErr } }
go
func makeInputSource(outputs []btcjson.ListUnspentResult) txauthor.InputSource { var ( totalInputValue btcutil.Amount inputs = make([]*wire.TxIn, 0, len(outputs)) inputValues = make([]btcutil.Amount, 0, len(outputs)) sourceErr error ) for _, output := range outputs { outputAmount, err := btcutil.NewAmount(output.Amount) if err != nil { sourceErr = fmt.Errorf( "invalid amount `%v` in listunspent result", output.Amount) break } if outputAmount == 0 { continue } if !saneOutputValue(outputAmount) { sourceErr = fmt.Errorf( "impossible output amount `%v` in listunspent result", outputAmount) break } totalInputValue += outputAmount previousOutPoint, err := parseOutPoint(&output) if err != nil { sourceErr = fmt.Errorf( "invalid data in listunspent result: %v", err) break } inputs = append(inputs, wire.NewTxIn(&previousOutPoint, nil, nil)) inputValues = append(inputValues, outputAmount) } if sourceErr == nil && totalInputValue == 0 { sourceErr = noInputValue{} } return func(btcutil.Amount) (btcutil.Amount, []*wire.TxIn, []btcutil.Amount, [][]byte, error) { return totalInputValue, inputs, inputValues, nil, sourceErr } }
[ "func", "makeInputSource", "(", "outputs", "[", "]", "btcjson", ".", "ListUnspentResult", ")", "txauthor", ".", "InputSource", "{", "var", "(", "totalInputValue", "btcutil", ".", "Amount", "\n", "inputs", "=", "make", "(", "[", "]", "*", "wire", ".", "TxIn", ",", "0", ",", "len", "(", "outputs", ")", ")", "\n", "inputValues", "=", "make", "(", "[", "]", "btcutil", ".", "Amount", ",", "0", ",", "len", "(", "outputs", ")", ")", "\n", "sourceErr", "error", "\n", ")", "\n", "for", "_", ",", "output", ":=", "range", "outputs", "{", "outputAmount", ",", "err", ":=", "btcutil", ".", "NewAmount", "(", "output", ".", "Amount", ")", "\n", "if", "err", "!=", "nil", "{", "sourceErr", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "output", ".", "Amount", ")", "\n", "break", "\n", "}", "\n", "if", "outputAmount", "==", "0", "{", "continue", "\n", "}", "\n", "if", "!", "saneOutputValue", "(", "outputAmount", ")", "{", "sourceErr", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "outputAmount", ")", "\n", "break", "\n", "}", "\n", "totalInputValue", "+=", "outputAmount", "\n\n", "previousOutPoint", ",", "err", ":=", "parseOutPoint", "(", "&", "output", ")", "\n", "if", "err", "!=", "nil", "{", "sourceErr", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "break", "\n", "}", "\n\n", "inputs", "=", "append", "(", "inputs", ",", "wire", ".", "NewTxIn", "(", "&", "previousOutPoint", ",", "nil", ",", "nil", ")", ")", "\n", "inputValues", "=", "append", "(", "inputValues", ",", "outputAmount", ")", "\n", "}", "\n\n", "if", "sourceErr", "==", "nil", "&&", "totalInputValue", "==", "0", "{", "sourceErr", "=", "noInputValue", "{", "}", "\n", "}", "\n\n", "return", "func", "(", "btcutil", ".", "Amount", ")", "(", "btcutil", ".", "Amount", ",", "[", "]", "*", "wire", ".", "TxIn", ",", "[", "]", "btcutil", ".", "Amount", ",", "[", "]", "[", "]", "byte", ",", "error", ")", "{", "return", "totalInputValue", ",", "inputs", ",", "inputValues", ",", "nil", ",", "sourceErr", "\n", "}", "\n", "}" ]
// makeInputSource creates an InputSource that creates inputs for every unspent // output with non-zero output values. The target amount is ignored since every // output is consumed. The InputSource does not return any previous output // scripts as they are not needed for creating the unsinged transaction and are // looked up again by the wallet during the call to signrawtransaction.
[ "makeInputSource", "creates", "an", "InputSource", "that", "creates", "inputs", "for", "every", "unspent", "output", "with", "non", "-", "zero", "output", "values", ".", "The", "target", "amount", "is", "ignored", "since", "every", "output", "is", "consumed", ".", "The", "InputSource", "does", "not", "return", "any", "previous", "output", "scripts", "as", "they", "are", "not", "needed", "for", "creating", "the", "unsinged", "transaction", "and", "are", "looked", "up", "again", "by", "the", "wallet", "during", "the", "call", "to", "signrawtransaction", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/cmd/sweepaccount/main.go#L141-L186
train
btcsuite/btcwallet
cmd/sweepaccount/main.go
makeDestinationScriptSource
func makeDestinationScriptSource(rpcClient *rpcclient.Client, accountName string) txauthor.ChangeSource { return func() ([]byte, error) { destinationAddress, err := rpcClient.GetNewAddress(accountName) if err != nil { return nil, err } return txscript.PayToAddrScript(destinationAddress) } }
go
func makeDestinationScriptSource(rpcClient *rpcclient.Client, accountName string) txauthor.ChangeSource { return func() ([]byte, error) { destinationAddress, err := rpcClient.GetNewAddress(accountName) if err != nil { return nil, err } return txscript.PayToAddrScript(destinationAddress) } }
[ "func", "makeDestinationScriptSource", "(", "rpcClient", "*", "rpcclient", ".", "Client", ",", "accountName", "string", ")", "txauthor", ".", "ChangeSource", "{", "return", "func", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "destinationAddress", ",", "err", ":=", "rpcClient", ".", "GetNewAddress", "(", "accountName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "txscript", ".", "PayToAddrScript", "(", "destinationAddress", ")", "\n", "}", "\n", "}" ]
// makeDestinationScriptSource creates a ChangeSource which is used to receive // all correlated previous input value. A non-change address is created by this // function.
[ "makeDestinationScriptSource", "creates", "a", "ChangeSource", "which", "is", "used", "to", "receive", "all", "correlated", "previous", "input", "value", ".", "A", "non", "-", "change", "address", "is", "created", "by", "this", "function", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/cmd/sweepaccount/main.go#L191-L199
train
btcsuite/btcwallet
wallet/txauthor/author.go
RandomizeOutputPosition
func RandomizeOutputPosition(outputs []*wire.TxOut, index int) int { r := cprng.Int31n(int32(len(outputs))) outputs[r], outputs[index] = outputs[index], outputs[r] return int(r) }
go
func RandomizeOutputPosition(outputs []*wire.TxOut, index int) int { r := cprng.Int31n(int32(len(outputs))) outputs[r], outputs[index] = outputs[index], outputs[r] return int(r) }
[ "func", "RandomizeOutputPosition", "(", "outputs", "[", "]", "*", "wire", ".", "TxOut", ",", "index", "int", ")", "int", "{", "r", ":=", "cprng", ".", "Int31n", "(", "int32", "(", "len", "(", "outputs", ")", ")", ")", "\n", "outputs", "[", "r", "]", ",", "outputs", "[", "index", "]", "=", "outputs", "[", "index", "]", ",", "outputs", "[", "r", "]", "\n", "return", "int", "(", "r", ")", "\n", "}" ]
// RandomizeOutputPosition randomizes the position of a transaction's output by // swapping it with a random output. The new index is returned. This should be // done before signing.
[ "RandomizeOutputPosition", "randomizes", "the", "position", "of", "a", "transaction", "s", "output", "by", "swapping", "it", "with", "a", "random", "output", ".", "The", "new", "index", "is", "returned", ".", "This", "should", "be", "done", "before", "signing", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/txauthor/author.go#L158-L162
train
btcsuite/btcwallet
wallet/txauthor/author.go
RandomizeChangePosition
func (tx *AuthoredTx) RandomizeChangePosition() { tx.ChangeIndex = RandomizeOutputPosition(tx.Tx.TxOut, tx.ChangeIndex) }
go
func (tx *AuthoredTx) RandomizeChangePosition() { tx.ChangeIndex = RandomizeOutputPosition(tx.Tx.TxOut, tx.ChangeIndex) }
[ "func", "(", "tx", "*", "AuthoredTx", ")", "RandomizeChangePosition", "(", ")", "{", "tx", ".", "ChangeIndex", "=", "RandomizeOutputPosition", "(", "tx", ".", "Tx", ".", "TxOut", ",", "tx", ".", "ChangeIndex", ")", "\n", "}" ]
// RandomizeChangePosition randomizes the position of an authored transaction's // change output. This should be done before signing.
[ "RandomizeChangePosition", "randomizes", "the", "position", "of", "an", "authored", "transaction", "s", "change", "output", ".", "This", "should", "be", "done", "before", "signing", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/txauthor/author.go#L166-L168
train
btcsuite/btcwallet
wallet/txauthor/author.go
AddAllInputScripts
func AddAllInputScripts(tx *wire.MsgTx, prevPkScripts [][]byte, inputValues []btcutil.Amount, secrets SecretsSource) error { inputs := tx.TxIn hashCache := txscript.NewTxSigHashes(tx) chainParams := secrets.ChainParams() if len(inputs) != len(prevPkScripts) { return errors.New("tx.TxIn and prevPkScripts slices must " + "have equal length") } for i := range inputs { pkScript := prevPkScripts[i] switch { // If this is a p2sh output, who's script hash pre-image is a // witness program, then we'll need to use a modified signing // function which generates both the sigScript, and the witness // script. case txscript.IsPayToScriptHash(pkScript): err := spendNestedWitnessPubKeyHash(inputs[i], pkScript, int64(inputValues[i]), chainParams, secrets, tx, hashCache, i) if err != nil { return err } case txscript.IsPayToWitnessPubKeyHash(pkScript): err := spendWitnessKeyHash(inputs[i], pkScript, int64(inputValues[i]), chainParams, secrets, tx, hashCache, i) if err != nil { return err } default: sigScript := inputs[i].SignatureScript script, err := txscript.SignTxOutput(chainParams, tx, i, pkScript, txscript.SigHashAll, secrets, secrets, sigScript) if err != nil { return err } inputs[i].SignatureScript = script } } return nil }
go
func AddAllInputScripts(tx *wire.MsgTx, prevPkScripts [][]byte, inputValues []btcutil.Amount, secrets SecretsSource) error { inputs := tx.TxIn hashCache := txscript.NewTxSigHashes(tx) chainParams := secrets.ChainParams() if len(inputs) != len(prevPkScripts) { return errors.New("tx.TxIn and prevPkScripts slices must " + "have equal length") } for i := range inputs { pkScript := prevPkScripts[i] switch { // If this is a p2sh output, who's script hash pre-image is a // witness program, then we'll need to use a modified signing // function which generates both the sigScript, and the witness // script. case txscript.IsPayToScriptHash(pkScript): err := spendNestedWitnessPubKeyHash(inputs[i], pkScript, int64(inputValues[i]), chainParams, secrets, tx, hashCache, i) if err != nil { return err } case txscript.IsPayToWitnessPubKeyHash(pkScript): err := spendWitnessKeyHash(inputs[i], pkScript, int64(inputValues[i]), chainParams, secrets, tx, hashCache, i) if err != nil { return err } default: sigScript := inputs[i].SignatureScript script, err := txscript.SignTxOutput(chainParams, tx, i, pkScript, txscript.SigHashAll, secrets, secrets, sigScript) if err != nil { return err } inputs[i].SignatureScript = script } } return nil }
[ "func", "AddAllInputScripts", "(", "tx", "*", "wire", ".", "MsgTx", ",", "prevPkScripts", "[", "]", "[", "]", "byte", ",", "inputValues", "[", "]", "btcutil", ".", "Amount", ",", "secrets", "SecretsSource", ")", "error", "{", "inputs", ":=", "tx", ".", "TxIn", "\n", "hashCache", ":=", "txscript", ".", "NewTxSigHashes", "(", "tx", ")", "\n", "chainParams", ":=", "secrets", ".", "ChainParams", "(", ")", "\n\n", "if", "len", "(", "inputs", ")", "!=", "len", "(", "prevPkScripts", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", "+", "\"", "\"", ")", "\n", "}", "\n\n", "for", "i", ":=", "range", "inputs", "{", "pkScript", ":=", "prevPkScripts", "[", "i", "]", "\n\n", "switch", "{", "// If this is a p2sh output, who's script hash pre-image is a", "// witness program, then we'll need to use a modified signing", "// function which generates both the sigScript, and the witness", "// script.", "case", "txscript", ".", "IsPayToScriptHash", "(", "pkScript", ")", ":", "err", ":=", "spendNestedWitnessPubKeyHash", "(", "inputs", "[", "i", "]", ",", "pkScript", ",", "int64", "(", "inputValues", "[", "i", "]", ")", ",", "chainParams", ",", "secrets", ",", "tx", ",", "hashCache", ",", "i", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "txscript", ".", "IsPayToWitnessPubKeyHash", "(", "pkScript", ")", ":", "err", ":=", "spendWitnessKeyHash", "(", "inputs", "[", "i", "]", ",", "pkScript", ",", "int64", "(", "inputValues", "[", "i", "]", ")", ",", "chainParams", ",", "secrets", ",", "tx", ",", "hashCache", ",", "i", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "default", ":", "sigScript", ":=", "inputs", "[", "i", "]", ".", "SignatureScript", "\n", "script", ",", "err", ":=", "txscript", ".", "SignTxOutput", "(", "chainParams", ",", "tx", ",", "i", ",", "pkScript", ",", "txscript", ".", "SigHashAll", ",", "secrets", ",", "secrets", ",", "sigScript", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "inputs", "[", "i", "]", ".", "SignatureScript", "=", "script", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// AddAllInputScripts modifies transaction a transaction by adding inputs // scripts for each input. Previous output scripts being redeemed by each input // are passed in prevPkScripts and the slice length must match the number of // inputs. Private keys and redeem scripts are looked up using a SecretsSource // based on the previous output script.
[ "AddAllInputScripts", "modifies", "transaction", "a", "transaction", "by", "adding", "inputs", "scripts", "for", "each", "input", ".", "Previous", "output", "scripts", "being", "redeemed", "by", "each", "input", "are", "passed", "in", "prevPkScripts", "and", "the", "slice", "length", "must", "match", "the", "number", "of", "inputs", ".", "Private", "keys", "and", "redeem", "scripts", "are", "looked", "up", "using", "a", "SecretsSource", "based", "on", "the", "previous", "output", "script", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/txauthor/author.go#L192-L239
train
btcsuite/btcwallet
wallet/txauthor/author.go
AddAllInputScripts
func (tx *AuthoredTx) AddAllInputScripts(secrets SecretsSource) error { return AddAllInputScripts(tx.Tx, tx.PrevScripts, tx.PrevInputValues, secrets) }
go
func (tx *AuthoredTx) AddAllInputScripts(secrets SecretsSource) error { return AddAllInputScripts(tx.Tx, tx.PrevScripts, tx.PrevInputValues, secrets) }
[ "func", "(", "tx", "*", "AuthoredTx", ")", "AddAllInputScripts", "(", "secrets", "SecretsSource", ")", "error", "{", "return", "AddAllInputScripts", "(", "tx", ".", "Tx", ",", "tx", ".", "PrevScripts", ",", "tx", ".", "PrevInputValues", ",", "secrets", ")", "\n", "}" ]
// AddAllInputScripts modifies an authored transaction by adding inputs scripts // for each input of an authored transaction. Private keys and redeem scripts // are looked up using a SecretsSource based on the previous output script.
[ "AddAllInputScripts", "modifies", "an", "authored", "transaction", "by", "adding", "inputs", "scripts", "for", "each", "input", "of", "an", "authored", "transaction", ".", "Private", "keys", "and", "redeem", "scripts", "are", "looked", "up", "using", "a", "SecretsSource", "based", "on", "the", "previous", "output", "script", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/txauthor/author.go#L359-L361
train
btcsuite/btcwallet
wallet/utxos.go
UnspentOutputs
func (w *Wallet) UnspentOutputs(policy OutputSelectionPolicy) ([]*TransactionOutput, error) { var outputResults []*TransactionOutput err := walletdb.View(w.db, func(tx walletdb.ReadTx) error { addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey) txmgrNs := tx.ReadBucket(wtxmgrNamespaceKey) syncBlock := w.Manager.SyncedTo() // TODO: actually stream outputs from the db instead of fetching // all of them at once. outputs, err := w.TxStore.UnspentOutputs(txmgrNs) if err != nil { return err } for _, output := range outputs { // Ignore outputs that haven't reached the required // number of confirmations. if !policy.meetsRequiredConfs(output.Height, syncBlock.Height) { continue } // Ignore outputs that are not controlled by the account. _, addrs, _, err := txscript.ExtractPkScriptAddrs(output.PkScript, w.chainParams) if err != nil || len(addrs) == 0 { // Cannot determine which account this belongs // to without a valid address. TODO: Fix this // by saving outputs per account, or accounts // per output. continue } _, outputAcct, err := w.Manager.AddrAccount(addrmgrNs, addrs[0]) if err != nil { return err } if outputAcct != policy.Account { continue } // Stakebase isn't exposed by wtxmgr so those will be // OutputKindNormal for now. outputSource := OutputKindNormal if output.FromCoinBase { outputSource = OutputKindCoinbase } result := &TransactionOutput{ OutPoint: output.OutPoint, Output: wire.TxOut{ Value: int64(output.Amount), PkScript: output.PkScript, }, OutputKind: outputSource, ContainingBlock: BlockIdentity(output.Block), ReceiveTime: output.Received, } outputResults = append(outputResults, result) } return nil }) return outputResults, err }
go
func (w *Wallet) UnspentOutputs(policy OutputSelectionPolicy) ([]*TransactionOutput, error) { var outputResults []*TransactionOutput err := walletdb.View(w.db, func(tx walletdb.ReadTx) error { addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey) txmgrNs := tx.ReadBucket(wtxmgrNamespaceKey) syncBlock := w.Manager.SyncedTo() // TODO: actually stream outputs from the db instead of fetching // all of them at once. outputs, err := w.TxStore.UnspentOutputs(txmgrNs) if err != nil { return err } for _, output := range outputs { // Ignore outputs that haven't reached the required // number of confirmations. if !policy.meetsRequiredConfs(output.Height, syncBlock.Height) { continue } // Ignore outputs that are not controlled by the account. _, addrs, _, err := txscript.ExtractPkScriptAddrs(output.PkScript, w.chainParams) if err != nil || len(addrs) == 0 { // Cannot determine which account this belongs // to without a valid address. TODO: Fix this // by saving outputs per account, or accounts // per output. continue } _, outputAcct, err := w.Manager.AddrAccount(addrmgrNs, addrs[0]) if err != nil { return err } if outputAcct != policy.Account { continue } // Stakebase isn't exposed by wtxmgr so those will be // OutputKindNormal for now. outputSource := OutputKindNormal if output.FromCoinBase { outputSource = OutputKindCoinbase } result := &TransactionOutput{ OutPoint: output.OutPoint, Output: wire.TxOut{ Value: int64(output.Amount), PkScript: output.PkScript, }, OutputKind: outputSource, ContainingBlock: BlockIdentity(output.Block), ReceiveTime: output.Received, } outputResults = append(outputResults, result) } return nil }) return outputResults, err }
[ "func", "(", "w", "*", "Wallet", ")", "UnspentOutputs", "(", "policy", "OutputSelectionPolicy", ")", "(", "[", "]", "*", "TransactionOutput", ",", "error", ")", "{", "var", "outputResults", "[", "]", "*", "TransactionOutput", "\n", "err", ":=", "walletdb", ".", "View", "(", "w", ".", "db", ",", "func", "(", "tx", "walletdb", ".", "ReadTx", ")", "error", "{", "addrmgrNs", ":=", "tx", ".", "ReadBucket", "(", "waddrmgrNamespaceKey", ")", "\n", "txmgrNs", ":=", "tx", ".", "ReadBucket", "(", "wtxmgrNamespaceKey", ")", "\n\n", "syncBlock", ":=", "w", ".", "Manager", ".", "SyncedTo", "(", ")", "\n\n", "// TODO: actually stream outputs from the db instead of fetching", "// all of them at once.", "outputs", ",", "err", ":=", "w", ".", "TxStore", ".", "UnspentOutputs", "(", "txmgrNs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "for", "_", ",", "output", ":=", "range", "outputs", "{", "// Ignore outputs that haven't reached the required", "// number of confirmations.", "if", "!", "policy", ".", "meetsRequiredConfs", "(", "output", ".", "Height", ",", "syncBlock", ".", "Height", ")", "{", "continue", "\n", "}", "\n\n", "// Ignore outputs that are not controlled by the account.", "_", ",", "addrs", ",", "_", ",", "err", ":=", "txscript", ".", "ExtractPkScriptAddrs", "(", "output", ".", "PkScript", ",", "w", ".", "chainParams", ")", "\n", "if", "err", "!=", "nil", "||", "len", "(", "addrs", ")", "==", "0", "{", "// Cannot determine which account this belongs", "// to without a valid address. TODO: Fix this", "// by saving outputs per account, or accounts", "// per output.", "continue", "\n", "}", "\n", "_", ",", "outputAcct", ",", "err", ":=", "w", ".", "Manager", ".", "AddrAccount", "(", "addrmgrNs", ",", "addrs", "[", "0", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "outputAcct", "!=", "policy", ".", "Account", "{", "continue", "\n", "}", "\n\n", "// Stakebase isn't exposed by wtxmgr so those will be", "// OutputKindNormal for now.", "outputSource", ":=", "OutputKindNormal", "\n", "if", "output", ".", "FromCoinBase", "{", "outputSource", "=", "OutputKindCoinbase", "\n", "}", "\n\n", "result", ":=", "&", "TransactionOutput", "{", "OutPoint", ":", "output", ".", "OutPoint", ",", "Output", ":", "wire", ".", "TxOut", "{", "Value", ":", "int64", "(", "output", ".", "Amount", ")", ",", "PkScript", ":", "output", ".", "PkScript", ",", "}", ",", "OutputKind", ":", "outputSource", ",", "ContainingBlock", ":", "BlockIdentity", "(", "output", ".", "Block", ")", ",", "ReceiveTime", ":", "output", ".", "Received", ",", "}", "\n", "outputResults", "=", "append", "(", "outputResults", ",", "result", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}", ")", "\n", "return", "outputResults", ",", "err", "\n", "}" ]
// UnspentOutputs fetches all unspent outputs from the wallet that match rules // described in the passed policy.
[ "UnspentOutputs", "fetches", "all", "unspent", "outputs", "from", "the", "wallet", "that", "match", "rules", "described", "in", "the", "passed", "policy", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/wallet/utxos.go#L27-L90
train
btcsuite/btcwallet
waddrmgr/manager.go
defaultNewSecretKey
func defaultNewSecretKey(passphrase *[]byte, config *ScryptOptions) (*snacl.SecretKey, error) { return snacl.NewSecretKey(passphrase, config.N, config.R, config.P) }
go
func defaultNewSecretKey(passphrase *[]byte, config *ScryptOptions) (*snacl.SecretKey, error) { return snacl.NewSecretKey(passphrase, config.N, config.R, config.P) }
[ "func", "defaultNewSecretKey", "(", "passphrase", "*", "[", "]", "byte", ",", "config", "*", "ScryptOptions", ")", "(", "*", "snacl", ".", "SecretKey", ",", "error", ")", "{", "return", "snacl", ".", "NewSecretKey", "(", "passphrase", ",", "config", ".", "N", ",", "config", ".", "R", ",", "config", ".", "P", ")", "\n", "}" ]
// defaultNewSecretKey returns a new secret key. See newSecretKey.
[ "defaultNewSecretKey", "returns", "a", "new", "secret", "key", ".", "See", "newSecretKey", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L183-L186
train
btcsuite/btcwallet
waddrmgr/manager.go
SetSecretKeyGen
func SetSecretKeyGen(keyGen SecretKeyGenerator) SecretKeyGenerator { secretKeyGenMtx.Lock() oldKeyGen := secretKeyGen secretKeyGen = keyGen secretKeyGenMtx.Unlock() return oldKeyGen }
go
func SetSecretKeyGen(keyGen SecretKeyGenerator) SecretKeyGenerator { secretKeyGenMtx.Lock() oldKeyGen := secretKeyGen secretKeyGen = keyGen secretKeyGenMtx.Unlock() return oldKeyGen }
[ "func", "SetSecretKeyGen", "(", "keyGen", "SecretKeyGenerator", ")", "SecretKeyGenerator", "{", "secretKeyGenMtx", ".", "Lock", "(", ")", "\n", "oldKeyGen", ":=", "secretKeyGen", "\n", "secretKeyGen", "=", "keyGen", "\n", "secretKeyGenMtx", ".", "Unlock", "(", ")", "\n\n", "return", "oldKeyGen", "\n", "}" ]
// SetSecretKeyGen replaces the existing secret key generator, and returns the // previous generator.
[ "SetSecretKeyGen", "replaces", "the", "existing", "secret", "key", "generator", "and", "returns", "the", "previous", "generator", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L200-L207
train
btcsuite/btcwallet
waddrmgr/manager.go
newSecretKey
func newSecretKey(passphrase *[]byte, config *ScryptOptions) (*snacl.SecretKey, error) { secretKeyGenMtx.RLock() defer secretKeyGenMtx.RUnlock() return secretKeyGen(passphrase, config) }
go
func newSecretKey(passphrase *[]byte, config *ScryptOptions) (*snacl.SecretKey, error) { secretKeyGenMtx.RLock() defer secretKeyGenMtx.RUnlock() return secretKeyGen(passphrase, config) }
[ "func", "newSecretKey", "(", "passphrase", "*", "[", "]", "byte", ",", "config", "*", "ScryptOptions", ")", "(", "*", "snacl", ".", "SecretKey", ",", "error", ")", "{", "secretKeyGenMtx", ".", "RLock", "(", ")", "\n", "defer", "secretKeyGenMtx", ".", "RUnlock", "(", ")", "\n", "return", "secretKeyGen", "(", "passphrase", ",", "config", ")", "\n", "}" ]
// newSecretKey generates a new secret key using the active secretKeyGen.
[ "newSecretKey", "generates", "a", "new", "secret", "key", "using", "the", "active", "secretKeyGen", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L210-L216
train
btcsuite/btcwallet
waddrmgr/manager.go
defaultNewCryptoKey
func defaultNewCryptoKey() (EncryptorDecryptor, error) { key, err := snacl.GenerateCryptoKey() if err != nil { return nil, err } return &cryptoKey{*key}, nil }
go
func defaultNewCryptoKey() (EncryptorDecryptor, error) { key, err := snacl.GenerateCryptoKey() if err != nil { return nil, err } return &cryptoKey{*key}, nil }
[ "func", "defaultNewCryptoKey", "(", ")", "(", "EncryptorDecryptor", ",", "error", ")", "{", "key", ",", "err", ":=", "snacl", ".", "GenerateCryptoKey", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "cryptoKey", "{", "*", "key", "}", ",", "nil", "\n", "}" ]
// defaultNewCryptoKey returns a new CryptoKey. See newCryptoKey.
[ "defaultNewCryptoKey", "returns", "a", "new", "CryptoKey", ".", "See", "newCryptoKey", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L244-L250
train
btcsuite/btcwallet
waddrmgr/manager.go
WatchOnly
func (m *Manager) WatchOnly() bool { m.mtx.RLock() defer m.mtx.RUnlock() return m.watchOnly() }
go
func (m *Manager) WatchOnly() bool { m.mtx.RLock() defer m.mtx.RUnlock() return m.watchOnly() }
[ "func", "(", "m", "*", "Manager", ")", "WatchOnly", "(", ")", "bool", "{", "m", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "m", ".", "mtx", ".", "RUnlock", "(", ")", "\n\n", "return", "m", ".", "watchOnly", "(", ")", "\n", "}" ]
// WatchOnly returns true if the root manager is in watch only mode, and false // otherwise.
[ "WatchOnly", "returns", "true", "if", "the", "root", "manager", "is", "in", "watch", "only", "mode", "and", "false", "otherwise", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L336-L341
train
btcsuite/btcwallet
waddrmgr/manager.go
lock
func (m *Manager) lock() { for _, manager := range m.scopedManagers { // Clear all of the account private keys. for _, acctInfo := range manager.acctInfo { if acctInfo.acctKeyPriv != nil { acctInfo.acctKeyPriv.Zero() } acctInfo.acctKeyPriv = nil } } // Remove clear text private keys and scripts from all address entries. for _, manager := range m.scopedManagers { for _, ma := range manager.addrs { switch addr := ma.(type) { case *managedAddress: addr.lock() case *scriptAddress: addr.lock() } } } // Remove clear text private master and crypto keys from memory. m.cryptoKeyScript.Zero() m.cryptoKeyPriv.Zero() m.masterKeyPriv.Zero() // Zero the hashed passphrase. zero.Bytea64(&m.hashedPrivPassphrase) // NOTE: m.cryptoKeyPub is intentionally not cleared here as the address // manager needs to be able to continue to read and decrypt public data // which uses a separate derived key from the database even when it is // locked. m.locked = true }
go
func (m *Manager) lock() { for _, manager := range m.scopedManagers { // Clear all of the account private keys. for _, acctInfo := range manager.acctInfo { if acctInfo.acctKeyPriv != nil { acctInfo.acctKeyPriv.Zero() } acctInfo.acctKeyPriv = nil } } // Remove clear text private keys and scripts from all address entries. for _, manager := range m.scopedManagers { for _, ma := range manager.addrs { switch addr := ma.(type) { case *managedAddress: addr.lock() case *scriptAddress: addr.lock() } } } // Remove clear text private master and crypto keys from memory. m.cryptoKeyScript.Zero() m.cryptoKeyPriv.Zero() m.masterKeyPriv.Zero() // Zero the hashed passphrase. zero.Bytea64(&m.hashedPrivPassphrase) // NOTE: m.cryptoKeyPub is intentionally not cleared here as the address // manager needs to be able to continue to read and decrypt public data // which uses a separate derived key from the database even when it is // locked. m.locked = true }
[ "func", "(", "m", "*", "Manager", ")", "lock", "(", ")", "{", "for", "_", ",", "manager", ":=", "range", "m", ".", "scopedManagers", "{", "// Clear all of the account private keys.", "for", "_", ",", "acctInfo", ":=", "range", "manager", ".", "acctInfo", "{", "if", "acctInfo", ".", "acctKeyPriv", "!=", "nil", "{", "acctInfo", ".", "acctKeyPriv", ".", "Zero", "(", ")", "\n", "}", "\n", "acctInfo", ".", "acctKeyPriv", "=", "nil", "\n", "}", "\n", "}", "\n\n", "// Remove clear text private keys and scripts from all address entries.", "for", "_", ",", "manager", ":=", "range", "m", ".", "scopedManagers", "{", "for", "_", ",", "ma", ":=", "range", "manager", ".", "addrs", "{", "switch", "addr", ":=", "ma", ".", "(", "type", ")", "{", "case", "*", "managedAddress", ":", "addr", ".", "lock", "(", ")", "\n", "case", "*", "scriptAddress", ":", "addr", ".", "lock", "(", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Remove clear text private master and crypto keys from memory.", "m", ".", "cryptoKeyScript", ".", "Zero", "(", ")", "\n", "m", ".", "cryptoKeyPriv", ".", "Zero", "(", ")", "\n", "m", ".", "masterKeyPriv", ".", "Zero", "(", ")", "\n\n", "// Zero the hashed passphrase.", "zero", ".", "Bytea64", "(", "&", "m", ".", "hashedPrivPassphrase", ")", "\n\n", "// NOTE: m.cryptoKeyPub is intentionally not cleared here as the address", "// manager needs to be able to continue to read and decrypt public data", "// which uses a separate derived key from the database even when it is", "// locked.", "m", ".", "locked", "=", "true", "\n", "}" ]
// lock performs a best try effort to remove and zero all secret keys associated // with the address manager. // // This function MUST be called with the manager lock held for writes.
[ "lock", "performs", "a", "best", "try", "effort", "to", "remove", "and", "zero", "all", "secret", "keys", "associated", "with", "the", "address", "manager", ".", "This", "function", "MUST", "be", "called", "with", "the", "manager", "lock", "held", "for", "writes", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L355-L392
train
btcsuite/btcwallet
waddrmgr/manager.go
FetchScopedKeyManager
func (m *Manager) FetchScopedKeyManager(scope KeyScope) (*ScopedKeyManager, error) { m.mtx.RLock() defer m.mtx.RUnlock() sm, ok := m.scopedManagers[scope] if !ok { str := fmt.Sprintf("scope %v not found", scope) return nil, managerError(ErrScopeNotFound, str, nil) } return sm, nil }
go
func (m *Manager) FetchScopedKeyManager(scope KeyScope) (*ScopedKeyManager, error) { m.mtx.RLock() defer m.mtx.RUnlock() sm, ok := m.scopedManagers[scope] if !ok { str := fmt.Sprintf("scope %v not found", scope) return nil, managerError(ErrScopeNotFound, str, nil) } return sm, nil }
[ "func", "(", "m", "*", "Manager", ")", "FetchScopedKeyManager", "(", "scope", "KeyScope", ")", "(", "*", "ScopedKeyManager", ",", "error", ")", "{", "m", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "m", ".", "mtx", ".", "RUnlock", "(", ")", "\n\n", "sm", ",", "ok", ":=", "m", ".", "scopedManagers", "[", "scope", "]", "\n", "if", "!", "ok", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "scope", ")", "\n", "return", "nil", ",", "managerError", "(", "ErrScopeNotFound", ",", "str", ",", "nil", ")", "\n", "}", "\n\n", "return", "sm", ",", "nil", "\n", "}" ]
// FetchScopedKeyManager attempts to fetch an active scoped manager according to // its registered scope. If the manger is found, then a nil error is returned // along with the active scoped manager. Otherwise, a nil manager and a non-nil // error will be returned.
[ "FetchScopedKeyManager", "attempts", "to", "fetch", "an", "active", "scoped", "manager", "according", "to", "its", "registered", "scope", ".", "If", "the", "manger", "is", "found", "then", "a", "nil", "error", "is", "returned", "along", "with", "the", "active", "scoped", "manager", ".", "Otherwise", "a", "nil", "manager", "and", "a", "non", "-", "nil", "error", "will", "be", "returned", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L539-L550
train
btcsuite/btcwallet
waddrmgr/manager.go
ActiveScopedKeyManagers
func (m *Manager) ActiveScopedKeyManagers() []*ScopedKeyManager { m.mtx.RLock() defer m.mtx.RUnlock() var scopedManagers []*ScopedKeyManager for _, smgr := range m.scopedManagers { scopedManagers = append(scopedManagers, smgr) } return scopedManagers }
go
func (m *Manager) ActiveScopedKeyManagers() []*ScopedKeyManager { m.mtx.RLock() defer m.mtx.RUnlock() var scopedManagers []*ScopedKeyManager for _, smgr := range m.scopedManagers { scopedManagers = append(scopedManagers, smgr) } return scopedManagers }
[ "func", "(", "m", "*", "Manager", ")", "ActiveScopedKeyManagers", "(", ")", "[", "]", "*", "ScopedKeyManager", "{", "m", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "m", ".", "mtx", ".", "RUnlock", "(", ")", "\n\n", "var", "scopedManagers", "[", "]", "*", "ScopedKeyManager", "\n", "for", "_", ",", "smgr", ":=", "range", "m", ".", "scopedManagers", "{", "scopedManagers", "=", "append", "(", "scopedManagers", ",", "smgr", ")", "\n", "}", "\n\n", "return", "scopedManagers", "\n", "}" ]
// ActiveScopedKeyManagers returns a slice of all the active scoped key // managers currently known by the root key manager.
[ "ActiveScopedKeyManagers", "returns", "a", "slice", "of", "all", "the", "active", "scoped", "key", "managers", "currently", "known", "by", "the", "root", "key", "manager", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L554-L564
train
btcsuite/btcwallet
waddrmgr/manager.go
ScopesForExternalAddrType
func (m *Manager) ScopesForExternalAddrType(addrType AddressType) []KeyScope { m.mtx.RLock() defer m.mtx.RUnlock() scopes, _ := m.externalAddrSchemas[addrType] return scopes }
go
func (m *Manager) ScopesForExternalAddrType(addrType AddressType) []KeyScope { m.mtx.RLock() defer m.mtx.RUnlock() scopes, _ := m.externalAddrSchemas[addrType] return scopes }
[ "func", "(", "m", "*", "Manager", ")", "ScopesForExternalAddrType", "(", "addrType", "AddressType", ")", "[", "]", "KeyScope", "{", "m", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "m", ".", "mtx", ".", "RUnlock", "(", ")", "\n\n", "scopes", ",", "_", ":=", "m", ".", "externalAddrSchemas", "[", "addrType", "]", "\n", "return", "scopes", "\n", "}" ]
// ScopesForExternalAddrType returns the set of key scopes that are able to // produce the target address type as external addresses.
[ "ScopesForExternalAddrType", "returns", "the", "set", "of", "key", "scopes", "that", "are", "able", "to", "produce", "the", "target", "address", "type", "as", "external", "addresses", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L568-L574
train
btcsuite/btcwallet
waddrmgr/manager.go
ScopesForInternalAddrTypes
func (m *Manager) ScopesForInternalAddrTypes(addrType AddressType) []KeyScope { m.mtx.RLock() defer m.mtx.RUnlock() scopes, _ := m.internalAddrSchemas[addrType] return scopes }
go
func (m *Manager) ScopesForInternalAddrTypes(addrType AddressType) []KeyScope { m.mtx.RLock() defer m.mtx.RUnlock() scopes, _ := m.internalAddrSchemas[addrType] return scopes }
[ "func", "(", "m", "*", "Manager", ")", "ScopesForInternalAddrTypes", "(", "addrType", "AddressType", ")", "[", "]", "KeyScope", "{", "m", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "m", ".", "mtx", ".", "RUnlock", "(", ")", "\n\n", "scopes", ",", "_", ":=", "m", ".", "internalAddrSchemas", "[", "addrType", "]", "\n", "return", "scopes", "\n", "}" ]
// ScopesForInternalAddrTypes returns the set of key scopes that are able to // produce the target address type as internal addresses.
[ "ScopesForInternalAddrTypes", "returns", "the", "set", "of", "key", "scopes", "that", "are", "able", "to", "produce", "the", "target", "address", "type", "as", "internal", "addresses", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L578-L584
train
btcsuite/btcwallet
waddrmgr/manager.go
AddrAccount
func (m *Manager) AddrAccount(ns walletdb.ReadBucket, address btcutil.Address) (*ScopedKeyManager, uint32, error) { m.mtx.RLock() defer m.mtx.RUnlock() for _, scopedMgr := range m.scopedManagers { if _, err := scopedMgr.Address(ns, address); err != nil { continue } // We've found the manager that this address belongs to, so we // can retrieve the address' account along with the manager // that the addr belongs to. accNo, err := scopedMgr.AddrAccount(ns, address) if err != nil { return nil, 0, err } return scopedMgr, accNo, err } // If we get to this point, then we weren't able to find the address in // any of the managers, so we'll exit with an error. str := fmt.Sprintf("unable to find key for addr %v", address) return nil, 0, managerError(ErrAddressNotFound, str, nil) }
go
func (m *Manager) AddrAccount(ns walletdb.ReadBucket, address btcutil.Address) (*ScopedKeyManager, uint32, error) { m.mtx.RLock() defer m.mtx.RUnlock() for _, scopedMgr := range m.scopedManagers { if _, err := scopedMgr.Address(ns, address); err != nil { continue } // We've found the manager that this address belongs to, so we // can retrieve the address' account along with the manager // that the addr belongs to. accNo, err := scopedMgr.AddrAccount(ns, address) if err != nil { return nil, 0, err } return scopedMgr, accNo, err } // If we get to this point, then we weren't able to find the address in // any of the managers, so we'll exit with an error. str := fmt.Sprintf("unable to find key for addr %v", address) return nil, 0, managerError(ErrAddressNotFound, str, nil) }
[ "func", "(", "m", "*", "Manager", ")", "AddrAccount", "(", "ns", "walletdb", ".", "ReadBucket", ",", "address", "btcutil", ".", "Address", ")", "(", "*", "ScopedKeyManager", ",", "uint32", ",", "error", ")", "{", "m", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "m", ".", "mtx", ".", "RUnlock", "(", ")", "\n\n", "for", "_", ",", "scopedMgr", ":=", "range", "m", ".", "scopedManagers", "{", "if", "_", ",", "err", ":=", "scopedMgr", ".", "Address", "(", "ns", ",", "address", ")", ";", "err", "!=", "nil", "{", "continue", "\n", "}", "\n\n", "// We've found the manager that this address belongs to, so we", "// can retrieve the address' account along with the manager", "// that the addr belongs to.", "accNo", ",", "err", ":=", "scopedMgr", ".", "AddrAccount", "(", "ns", ",", "address", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "err", "\n", "}", "\n\n", "return", "scopedMgr", ",", "accNo", ",", "err", "\n", "}", "\n\n", "// If we get to this point, then we weren't able to find the address in", "// any of the managers, so we'll exit with an error.", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "address", ")", "\n", "return", "nil", ",", "0", ",", "managerError", "(", "ErrAddressNotFound", ",", "str", ",", "nil", ")", "\n", "}" ]
// AddrAccount returns the account to which the given address belongs. We also // return the scoped manager that owns the addr+account combo.
[ "AddrAccount", "returns", "the", "account", "to", "which", "the", "given", "address", "belongs", ".", "We", "also", "return", "the", "scoped", "manager", "that", "owns", "the", "addr", "+", "account", "combo", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L668-L694
train
btcsuite/btcwallet
waddrmgr/manager.go
IsLocked
func (m *Manager) IsLocked() bool { m.mtx.RLock() defer m.mtx.RUnlock() return m.isLocked() }
go
func (m *Manager) IsLocked() bool { m.mtx.RLock() defer m.mtx.RUnlock() return m.isLocked() }
[ "func", "(", "m", "*", "Manager", ")", "IsLocked", "(", ")", "bool", "{", "m", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "m", ".", "mtx", ".", "RUnlock", "(", ")", "\n\n", "return", "m", ".", "isLocked", "(", ")", "\n", "}" ]
// IsLocked returns whether or not the address managed is locked. When it is // unlocked, the decryption key needed to decrypt private keys used for signing // is in memory.
[ "IsLocked", "returns", "whether", "or", "not", "the", "address", "managed", "is", "locked", ".", "When", "it", "is", "unlocked", "the", "decryption", "key", "needed", "to", "decrypt", "private", "keys", "used", "for", "signing", "is", "in", "memory", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L1007-L1012
train
btcsuite/btcwallet
waddrmgr/manager.go
Lock
func (m *Manager) Lock() error { // A watching-only address manager can't be locked. if m.watchingOnly { return managerError(ErrWatchingOnly, errWatchingOnly, nil) } m.mtx.Lock() defer m.mtx.Unlock() // Error on attempt to lock an already locked manager. if m.locked { return managerError(ErrLocked, errLocked, nil) } m.lock() return nil }
go
func (m *Manager) Lock() error { // A watching-only address manager can't be locked. if m.watchingOnly { return managerError(ErrWatchingOnly, errWatchingOnly, nil) } m.mtx.Lock() defer m.mtx.Unlock() // Error on attempt to lock an already locked manager. if m.locked { return managerError(ErrLocked, errLocked, nil) } m.lock() return nil }
[ "func", "(", "m", "*", "Manager", ")", "Lock", "(", ")", "error", "{", "// A watching-only address manager can't be locked.", "if", "m", ".", "watchingOnly", "{", "return", "managerError", "(", "ErrWatchingOnly", ",", "errWatchingOnly", ",", "nil", ")", "\n", "}", "\n\n", "m", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "// Error on attempt to lock an already locked manager.", "if", "m", ".", "locked", "{", "return", "managerError", "(", "ErrLocked", ",", "errLocked", ",", "nil", ")", "\n", "}", "\n\n", "m", ".", "lock", "(", ")", "\n", "return", "nil", "\n", "}" ]
// Lock performs a best try effort to remove and zero all secret keys associated // with the address manager. // // This function will return an error if invoked on a watching-only address // manager.
[ "Lock", "performs", "a", "best", "try", "effort", "to", "remove", "and", "zero", "all", "secret", "keys", "associated", "with", "the", "address", "manager", ".", "This", "function", "will", "return", "an", "error", "if", "invoked", "on", "a", "watching", "-", "only", "address", "manager", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L1028-L1044
train
btcsuite/btcwallet
waddrmgr/manager.go
ValidateAccountName
func ValidateAccountName(name string) error { if name == "" { str := "accounts may not be named the empty string" return managerError(ErrInvalidAccount, str, nil) } if isReservedAccountName(name) { str := "reserved account name" return managerError(ErrInvalidAccount, str, nil) } return nil }
go
func ValidateAccountName(name string) error { if name == "" { str := "accounts may not be named the empty string" return managerError(ErrInvalidAccount, str, nil) } if isReservedAccountName(name) { str := "reserved account name" return managerError(ErrInvalidAccount, str, nil) } return nil }
[ "func", "ValidateAccountName", "(", "name", "string", ")", "error", "{", "if", "name", "==", "\"", "\"", "{", "str", ":=", "\"", "\"", "\n", "return", "managerError", "(", "ErrInvalidAccount", ",", "str", ",", "nil", ")", "\n", "}", "\n", "if", "isReservedAccountName", "(", "name", ")", "{", "str", ":=", "\"", "\"", "\n", "return", "managerError", "(", "ErrInvalidAccount", ",", "str", ",", "nil", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ValidateAccountName validates the given account name and returns an error, if any.
[ "ValidateAccountName", "validates", "the", "given", "account", "name", "and", "returns", "an", "error", "if", "any", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L1172-L1182
train
btcsuite/btcwallet
waddrmgr/manager.go
selectCryptoKey
func (m *Manager) selectCryptoKey(keyType CryptoKeyType) (EncryptorDecryptor, error) { if keyType == CKTPrivate || keyType == CKTScript { // The manager must be unlocked to work with the private keys. if m.locked || m.watchingOnly { return nil, managerError(ErrLocked, errLocked, nil) } } var cryptoKey EncryptorDecryptor switch keyType { case CKTPrivate: cryptoKey = m.cryptoKeyPriv case CKTScript: cryptoKey = m.cryptoKeyScript case CKTPublic: cryptoKey = m.cryptoKeyPub default: return nil, managerError(ErrInvalidKeyType, "invalid key type", nil) } return cryptoKey, nil }
go
func (m *Manager) selectCryptoKey(keyType CryptoKeyType) (EncryptorDecryptor, error) { if keyType == CKTPrivate || keyType == CKTScript { // The manager must be unlocked to work with the private keys. if m.locked || m.watchingOnly { return nil, managerError(ErrLocked, errLocked, nil) } } var cryptoKey EncryptorDecryptor switch keyType { case CKTPrivate: cryptoKey = m.cryptoKeyPriv case CKTScript: cryptoKey = m.cryptoKeyScript case CKTPublic: cryptoKey = m.cryptoKeyPub default: return nil, managerError(ErrInvalidKeyType, "invalid key type", nil) } return cryptoKey, nil }
[ "func", "(", "m", "*", "Manager", ")", "selectCryptoKey", "(", "keyType", "CryptoKeyType", ")", "(", "EncryptorDecryptor", ",", "error", ")", "{", "if", "keyType", "==", "CKTPrivate", "||", "keyType", "==", "CKTScript", "{", "// The manager must be unlocked to work with the private keys.", "if", "m", ".", "locked", "||", "m", ".", "watchingOnly", "{", "return", "nil", ",", "managerError", "(", "ErrLocked", ",", "errLocked", ",", "nil", ")", "\n", "}", "\n", "}", "\n\n", "var", "cryptoKey", "EncryptorDecryptor", "\n", "switch", "keyType", "{", "case", "CKTPrivate", ":", "cryptoKey", "=", "m", ".", "cryptoKeyPriv", "\n", "case", "CKTScript", ":", "cryptoKey", "=", "m", ".", "cryptoKeyScript", "\n", "case", "CKTPublic", ":", "cryptoKey", "=", "m", ".", "cryptoKeyPub", "\n", "default", ":", "return", "nil", ",", "managerError", "(", "ErrInvalidKeyType", ",", "\"", "\"", ",", "nil", ")", "\n", "}", "\n\n", "return", "cryptoKey", ",", "nil", "\n", "}" ]
// selectCryptoKey selects the appropriate crypto key based on the key type. An // error is returned when an invalid key type is specified or the requested key // requires the manager to be unlocked when it isn't. // // This function MUST be called with the manager lock held for reads.
[ "selectCryptoKey", "selects", "the", "appropriate", "crypto", "key", "based", "on", "the", "key", "type", ".", "An", "error", "is", "returned", "when", "an", "invalid", "key", "type", "is", "specified", "or", "the", "requested", "key", "requires", "the", "manager", "to", "be", "unlocked", "when", "it", "isn", "t", ".", "This", "function", "MUST", "be", "called", "with", "the", "manager", "lock", "held", "for", "reads", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L1189-L1211
train
btcsuite/btcwallet
waddrmgr/manager.go
Encrypt
func (m *Manager) Encrypt(keyType CryptoKeyType, in []byte) ([]byte, error) { // Encryption must be performed under the manager mutex since the // keys are cleared when the manager is locked. m.mtx.Lock() defer m.mtx.Unlock() cryptoKey, err := m.selectCryptoKey(keyType) if err != nil { return nil, err } encrypted, err := cryptoKey.Encrypt(in) if err != nil { return nil, managerError(ErrCrypto, "failed to encrypt", err) } return encrypted, nil }
go
func (m *Manager) Encrypt(keyType CryptoKeyType, in []byte) ([]byte, error) { // Encryption must be performed under the manager mutex since the // keys are cleared when the manager is locked. m.mtx.Lock() defer m.mtx.Unlock() cryptoKey, err := m.selectCryptoKey(keyType) if err != nil { return nil, err } encrypted, err := cryptoKey.Encrypt(in) if err != nil { return nil, managerError(ErrCrypto, "failed to encrypt", err) } return encrypted, nil }
[ "func", "(", "m", "*", "Manager", ")", "Encrypt", "(", "keyType", "CryptoKeyType", ",", "in", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// Encryption must be performed under the manager mutex since the", "// keys are cleared when the manager is locked.", "m", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "cryptoKey", ",", "err", ":=", "m", ".", "selectCryptoKey", "(", "keyType", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "encrypted", ",", "err", ":=", "cryptoKey", ".", "Encrypt", "(", "in", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "managerError", "(", "ErrCrypto", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "encrypted", ",", "nil", "\n", "}" ]
// Encrypt in using the crypto key type specified by keyType.
[ "Encrypt", "in", "using", "the", "crypto", "key", "type", "specified", "by", "keyType", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L1214-L1230
train
btcsuite/btcwallet
waddrmgr/manager.go
newManager
func newManager(chainParams *chaincfg.Params, masterKeyPub *snacl.SecretKey, masterKeyPriv *snacl.SecretKey, cryptoKeyPub EncryptorDecryptor, cryptoKeyPrivEncrypted, cryptoKeyScriptEncrypted []byte, syncInfo *syncState, birthday time.Time, privPassphraseSalt [saltSize]byte, scopedManagers map[KeyScope]*ScopedKeyManager) *Manager { m := &Manager{ chainParams: chainParams, syncState: *syncInfo, locked: true, birthday: birthday, masterKeyPub: masterKeyPub, masterKeyPriv: masterKeyPriv, cryptoKeyPub: cryptoKeyPub, cryptoKeyPrivEncrypted: cryptoKeyPrivEncrypted, cryptoKeyPriv: &cryptoKey{}, cryptoKeyScriptEncrypted: cryptoKeyScriptEncrypted, cryptoKeyScript: &cryptoKey{}, privPassphraseSalt: privPassphraseSalt, scopedManagers: scopedManagers, externalAddrSchemas: make(map[AddressType][]KeyScope), internalAddrSchemas: make(map[AddressType][]KeyScope), } for _, sMgr := range m.scopedManagers { externalType := sMgr.AddrSchema().ExternalAddrType internalType := sMgr.AddrSchema().InternalAddrType scope := sMgr.Scope() m.externalAddrSchemas[externalType] = append( m.externalAddrSchemas[externalType], scope, ) m.internalAddrSchemas[internalType] = append( m.internalAddrSchemas[internalType], scope, ) } return m }
go
func newManager(chainParams *chaincfg.Params, masterKeyPub *snacl.SecretKey, masterKeyPriv *snacl.SecretKey, cryptoKeyPub EncryptorDecryptor, cryptoKeyPrivEncrypted, cryptoKeyScriptEncrypted []byte, syncInfo *syncState, birthday time.Time, privPassphraseSalt [saltSize]byte, scopedManagers map[KeyScope]*ScopedKeyManager) *Manager { m := &Manager{ chainParams: chainParams, syncState: *syncInfo, locked: true, birthday: birthday, masterKeyPub: masterKeyPub, masterKeyPriv: masterKeyPriv, cryptoKeyPub: cryptoKeyPub, cryptoKeyPrivEncrypted: cryptoKeyPrivEncrypted, cryptoKeyPriv: &cryptoKey{}, cryptoKeyScriptEncrypted: cryptoKeyScriptEncrypted, cryptoKeyScript: &cryptoKey{}, privPassphraseSalt: privPassphraseSalt, scopedManagers: scopedManagers, externalAddrSchemas: make(map[AddressType][]KeyScope), internalAddrSchemas: make(map[AddressType][]KeyScope), } for _, sMgr := range m.scopedManagers { externalType := sMgr.AddrSchema().ExternalAddrType internalType := sMgr.AddrSchema().InternalAddrType scope := sMgr.Scope() m.externalAddrSchemas[externalType] = append( m.externalAddrSchemas[externalType], scope, ) m.internalAddrSchemas[internalType] = append( m.internalAddrSchemas[internalType], scope, ) } return m }
[ "func", "newManager", "(", "chainParams", "*", "chaincfg", ".", "Params", ",", "masterKeyPub", "*", "snacl", ".", "SecretKey", ",", "masterKeyPriv", "*", "snacl", ".", "SecretKey", ",", "cryptoKeyPub", "EncryptorDecryptor", ",", "cryptoKeyPrivEncrypted", ",", "cryptoKeyScriptEncrypted", "[", "]", "byte", ",", "syncInfo", "*", "syncState", ",", "birthday", "time", ".", "Time", ",", "privPassphraseSalt", "[", "saltSize", "]", "byte", ",", "scopedManagers", "map", "[", "KeyScope", "]", "*", "ScopedKeyManager", ")", "*", "Manager", "{", "m", ":=", "&", "Manager", "{", "chainParams", ":", "chainParams", ",", "syncState", ":", "*", "syncInfo", ",", "locked", ":", "true", ",", "birthday", ":", "birthday", ",", "masterKeyPub", ":", "masterKeyPub", ",", "masterKeyPriv", ":", "masterKeyPriv", ",", "cryptoKeyPub", ":", "cryptoKeyPub", ",", "cryptoKeyPrivEncrypted", ":", "cryptoKeyPrivEncrypted", ",", "cryptoKeyPriv", ":", "&", "cryptoKey", "{", "}", ",", "cryptoKeyScriptEncrypted", ":", "cryptoKeyScriptEncrypted", ",", "cryptoKeyScript", ":", "&", "cryptoKey", "{", "}", ",", "privPassphraseSalt", ":", "privPassphraseSalt", ",", "scopedManagers", ":", "scopedManagers", ",", "externalAddrSchemas", ":", "make", "(", "map", "[", "AddressType", "]", "[", "]", "KeyScope", ")", ",", "internalAddrSchemas", ":", "make", "(", "map", "[", "AddressType", "]", "[", "]", "KeyScope", ")", ",", "}", "\n\n", "for", "_", ",", "sMgr", ":=", "range", "m", ".", "scopedManagers", "{", "externalType", ":=", "sMgr", ".", "AddrSchema", "(", ")", ".", "ExternalAddrType", "\n", "internalType", ":=", "sMgr", ".", "AddrSchema", "(", ")", ".", "InternalAddrType", "\n", "scope", ":=", "sMgr", ".", "Scope", "(", ")", "\n\n", "m", ".", "externalAddrSchemas", "[", "externalType", "]", "=", "append", "(", "m", ".", "externalAddrSchemas", "[", "externalType", "]", ",", "scope", ",", ")", "\n", "m", ".", "internalAddrSchemas", "[", "internalType", "]", "=", "append", "(", "m", ".", "internalAddrSchemas", "[", "internalType", "]", ",", "scope", ",", ")", "\n", "}", "\n\n", "return", "m", "\n", "}" ]
// newManager returns a new locked address manager with the given parameters.
[ "newManager", "returns", "a", "new", "locked", "address", "manager", "with", "the", "given", "parameters", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L1252-L1290
train
btcsuite/btcwallet
waddrmgr/manager.go
Open
func Open(ns walletdb.ReadBucket, pubPassphrase []byte, chainParams *chaincfg.Params) (*Manager, error) { // Return an error if the manager has NOT already been created in the // given database namespace. exists := managerExists(ns) if !exists { str := "the specified address manager does not exist" return nil, managerError(ErrNoExist, str, nil) } return loadManager(ns, pubPassphrase, chainParams) }
go
func Open(ns walletdb.ReadBucket, pubPassphrase []byte, chainParams *chaincfg.Params) (*Manager, error) { // Return an error if the manager has NOT already been created in the // given database namespace. exists := managerExists(ns) if !exists { str := "the specified address manager does not exist" return nil, managerError(ErrNoExist, str, nil) } return loadManager(ns, pubPassphrase, chainParams) }
[ "func", "Open", "(", "ns", "walletdb", ".", "ReadBucket", ",", "pubPassphrase", "[", "]", "byte", ",", "chainParams", "*", "chaincfg", ".", "Params", ")", "(", "*", "Manager", ",", "error", ")", "{", "// Return an error if the manager has NOT already been created in the", "// given database namespace.", "exists", ":=", "managerExists", "(", "ns", ")", "\n", "if", "!", "exists", "{", "str", ":=", "\"", "\"", "\n", "return", "nil", ",", "managerError", "(", "ErrNoExist", ",", "str", ",", "nil", ")", "\n", "}", "\n\n", "return", "loadManager", "(", "ns", ",", "pubPassphrase", ",", "chainParams", ")", "\n", "}" ]
// Open loads an existing address manager from the given namespace. The public // passphrase is required to decrypt the public keys used to protect the public // information such as addresses. This is important since access to BIP0032 // extended keys means it is possible to generate all future addresses. // // If a config structure is passed to the function, that configuration will // override the defaults. // // A ManagerError with an error code of ErrNoExist will be returned if the // passed manager does not exist in the specified namespace.
[ "Open", "loads", "an", "existing", "address", "manager", "from", "the", "given", "namespace", ".", "The", "public", "passphrase", "is", "required", "to", "decrypt", "the", "public", "keys", "used", "to", "protect", "the", "public", "information", "such", "as", "addresses", ".", "This", "is", "important", "since", "access", "to", "BIP0032", "extended", "keys", "means", "it", "is", "possible", "to", "generate", "all", "future", "addresses", ".", "If", "a", "config", "structure", "is", "passed", "to", "the", "function", "that", "configuration", "will", "override", "the", "defaults", ".", "A", "ManagerError", "with", "an", "error", "code", "of", "ErrNoExist", "will", "be", "returned", "if", "the", "passed", "manager", "does", "not", "exist", "in", "the", "specified", "namespace", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L1519-L1531
train
btcsuite/btcwallet
waddrmgr/manager.go
createManagerKeyScope
func createManagerKeyScope(ns walletdb.ReadWriteBucket, scope KeyScope, root *hdkeychain.ExtendedKey, cryptoKeyPub, cryptoKeyPriv EncryptorDecryptor) error { // Derive the cointype key according to the passed scope. coinTypeKeyPriv, err := deriveCoinTypeKey(root, scope) if err != nil { str := "failed to derive cointype extended key" return managerError(ErrKeyChain, str, err) } defer coinTypeKeyPriv.Zero() // Derive the account key for the first account according our // BIP0044-like derivation. acctKeyPriv, err := deriveAccountKey(coinTypeKeyPriv, 0) if err != nil { // The seed is unusable if the any of the children in the // required hierarchy can't be derived due to invalid child. if err == hdkeychain.ErrInvalidChild { str := "the provided seed is unusable" return managerError(ErrKeyChain, str, hdkeychain.ErrUnusableSeed) } return err } // Ensure the branch keys can be derived for the provided seed according // to our BIP0044-like derivation. if err := checkBranchKeys(acctKeyPriv); err != nil { // The seed is unusable if the any of the children in the // required hierarchy can't be derived due to invalid child. if err == hdkeychain.ErrInvalidChild { str := "the provided seed is unusable" return managerError(ErrKeyChain, str, hdkeychain.ErrUnusableSeed) } return err } // The address manager needs the public extended key for the account. acctKeyPub, err := acctKeyPriv.Neuter() if err != nil { str := "failed to convert private key for account 0" return managerError(ErrKeyChain, str, err) } // Encrypt the cointype keys with the associated crypto keys. coinTypeKeyPub, err := coinTypeKeyPriv.Neuter() if err != nil { str := "failed to convert cointype private key" return managerError(ErrKeyChain, str, err) } coinTypePubEnc, err := cryptoKeyPub.Encrypt([]byte(coinTypeKeyPub.String())) if err != nil { str := "failed to encrypt cointype public key" return managerError(ErrCrypto, str, err) } coinTypePrivEnc, err := cryptoKeyPriv.Encrypt([]byte(coinTypeKeyPriv.String())) if err != nil { str := "failed to encrypt cointype private key" return managerError(ErrCrypto, str, err) } // Encrypt the default account keys with the associated crypto keys. acctPubEnc, err := cryptoKeyPub.Encrypt([]byte(acctKeyPub.String())) if err != nil { str := "failed to encrypt public key for account 0" return managerError(ErrCrypto, str, err) } acctPrivEnc, err := cryptoKeyPriv.Encrypt([]byte(acctKeyPriv.String())) if err != nil { str := "failed to encrypt private key for account 0" return managerError(ErrCrypto, str, err) } // Save the encrypted cointype keys to the database. err = putCoinTypeKeys(ns, &scope, coinTypePubEnc, coinTypePrivEnc) if err != nil { return err } // Save the information for the default account to the database. err = putAccountInfo( ns, &scope, DefaultAccountNum, acctPubEnc, acctPrivEnc, 0, 0, defaultAccountName, ) if err != nil { return err } return putAccountInfo( ns, &scope, ImportedAddrAccount, nil, nil, 0, 0, ImportedAddrAccountName, ) }
go
func createManagerKeyScope(ns walletdb.ReadWriteBucket, scope KeyScope, root *hdkeychain.ExtendedKey, cryptoKeyPub, cryptoKeyPriv EncryptorDecryptor) error { // Derive the cointype key according to the passed scope. coinTypeKeyPriv, err := deriveCoinTypeKey(root, scope) if err != nil { str := "failed to derive cointype extended key" return managerError(ErrKeyChain, str, err) } defer coinTypeKeyPriv.Zero() // Derive the account key for the first account according our // BIP0044-like derivation. acctKeyPriv, err := deriveAccountKey(coinTypeKeyPriv, 0) if err != nil { // The seed is unusable if the any of the children in the // required hierarchy can't be derived due to invalid child. if err == hdkeychain.ErrInvalidChild { str := "the provided seed is unusable" return managerError(ErrKeyChain, str, hdkeychain.ErrUnusableSeed) } return err } // Ensure the branch keys can be derived for the provided seed according // to our BIP0044-like derivation. if err := checkBranchKeys(acctKeyPriv); err != nil { // The seed is unusable if the any of the children in the // required hierarchy can't be derived due to invalid child. if err == hdkeychain.ErrInvalidChild { str := "the provided seed is unusable" return managerError(ErrKeyChain, str, hdkeychain.ErrUnusableSeed) } return err } // The address manager needs the public extended key for the account. acctKeyPub, err := acctKeyPriv.Neuter() if err != nil { str := "failed to convert private key for account 0" return managerError(ErrKeyChain, str, err) } // Encrypt the cointype keys with the associated crypto keys. coinTypeKeyPub, err := coinTypeKeyPriv.Neuter() if err != nil { str := "failed to convert cointype private key" return managerError(ErrKeyChain, str, err) } coinTypePubEnc, err := cryptoKeyPub.Encrypt([]byte(coinTypeKeyPub.String())) if err != nil { str := "failed to encrypt cointype public key" return managerError(ErrCrypto, str, err) } coinTypePrivEnc, err := cryptoKeyPriv.Encrypt([]byte(coinTypeKeyPriv.String())) if err != nil { str := "failed to encrypt cointype private key" return managerError(ErrCrypto, str, err) } // Encrypt the default account keys with the associated crypto keys. acctPubEnc, err := cryptoKeyPub.Encrypt([]byte(acctKeyPub.String())) if err != nil { str := "failed to encrypt public key for account 0" return managerError(ErrCrypto, str, err) } acctPrivEnc, err := cryptoKeyPriv.Encrypt([]byte(acctKeyPriv.String())) if err != nil { str := "failed to encrypt private key for account 0" return managerError(ErrCrypto, str, err) } // Save the encrypted cointype keys to the database. err = putCoinTypeKeys(ns, &scope, coinTypePubEnc, coinTypePrivEnc) if err != nil { return err } // Save the information for the default account to the database. err = putAccountInfo( ns, &scope, DefaultAccountNum, acctPubEnc, acctPrivEnc, 0, 0, defaultAccountName, ) if err != nil { return err } return putAccountInfo( ns, &scope, ImportedAddrAccount, nil, nil, 0, 0, ImportedAddrAccountName, ) }
[ "func", "createManagerKeyScope", "(", "ns", "walletdb", ".", "ReadWriteBucket", ",", "scope", "KeyScope", ",", "root", "*", "hdkeychain", ".", "ExtendedKey", ",", "cryptoKeyPub", ",", "cryptoKeyPriv", "EncryptorDecryptor", ")", "error", "{", "// Derive the cointype key according to the passed scope.", "coinTypeKeyPriv", ",", "err", ":=", "deriveCoinTypeKey", "(", "root", ",", "scope", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "managerError", "(", "ErrKeyChain", ",", "str", ",", "err", ")", "\n", "}", "\n", "defer", "coinTypeKeyPriv", ".", "Zero", "(", ")", "\n\n", "// Derive the account key for the first account according our", "// BIP0044-like derivation.", "acctKeyPriv", ",", "err", ":=", "deriveAccountKey", "(", "coinTypeKeyPriv", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "// The seed is unusable if the any of the children in the", "// required hierarchy can't be derived due to invalid child.", "if", "err", "==", "hdkeychain", ".", "ErrInvalidChild", "{", "str", ":=", "\"", "\"", "\n", "return", "managerError", "(", "ErrKeyChain", ",", "str", ",", "hdkeychain", ".", "ErrUnusableSeed", ")", "\n", "}", "\n\n", "return", "err", "\n", "}", "\n\n", "// Ensure the branch keys can be derived for the provided seed according", "// to our BIP0044-like derivation.", "if", "err", ":=", "checkBranchKeys", "(", "acctKeyPriv", ")", ";", "err", "!=", "nil", "{", "// The seed is unusable if the any of the children in the", "// required hierarchy can't be derived due to invalid child.", "if", "err", "==", "hdkeychain", ".", "ErrInvalidChild", "{", "str", ":=", "\"", "\"", "\n", "return", "managerError", "(", "ErrKeyChain", ",", "str", ",", "hdkeychain", ".", "ErrUnusableSeed", ")", "\n", "}", "\n\n", "return", "err", "\n", "}", "\n\n", "// The address manager needs the public extended key for the account.", "acctKeyPub", ",", "err", ":=", "acctKeyPriv", ".", "Neuter", "(", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "managerError", "(", "ErrKeyChain", ",", "str", ",", "err", ")", "\n", "}", "\n\n", "// Encrypt the cointype keys with the associated crypto keys.", "coinTypeKeyPub", ",", "err", ":=", "coinTypeKeyPriv", ".", "Neuter", "(", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "managerError", "(", "ErrKeyChain", ",", "str", ",", "err", ")", "\n", "}", "\n", "coinTypePubEnc", ",", "err", ":=", "cryptoKeyPub", ".", "Encrypt", "(", "[", "]", "byte", "(", "coinTypeKeyPub", ".", "String", "(", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "managerError", "(", "ErrCrypto", ",", "str", ",", "err", ")", "\n", "}", "\n", "coinTypePrivEnc", ",", "err", ":=", "cryptoKeyPriv", ".", "Encrypt", "(", "[", "]", "byte", "(", "coinTypeKeyPriv", ".", "String", "(", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "managerError", "(", "ErrCrypto", ",", "str", ",", "err", ")", "\n", "}", "\n\n", "// Encrypt the default account keys with the associated crypto keys.", "acctPubEnc", ",", "err", ":=", "cryptoKeyPub", ".", "Encrypt", "(", "[", "]", "byte", "(", "acctKeyPub", ".", "String", "(", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "managerError", "(", "ErrCrypto", ",", "str", ",", "err", ")", "\n", "}", "\n", "acctPrivEnc", ",", "err", ":=", "cryptoKeyPriv", ".", "Encrypt", "(", "[", "]", "byte", "(", "acctKeyPriv", ".", "String", "(", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "managerError", "(", "ErrCrypto", ",", "str", ",", "err", ")", "\n", "}", "\n\n", "// Save the encrypted cointype keys to the database.", "err", "=", "putCoinTypeKeys", "(", "ns", ",", "&", "scope", ",", "coinTypePubEnc", ",", "coinTypePrivEnc", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Save the information for the default account to the database.", "err", "=", "putAccountInfo", "(", "ns", ",", "&", "scope", ",", "DefaultAccountNum", ",", "acctPubEnc", ",", "acctPrivEnc", ",", "0", ",", "0", ",", "defaultAccountName", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "putAccountInfo", "(", "ns", ",", "&", "scope", ",", "ImportedAddrAccount", ",", "nil", ",", "nil", ",", "0", ",", "0", ",", "ImportedAddrAccountName", ",", ")", "\n", "}" ]
// createManagerKeyScope creates a new key scoped for a target manager's scope. // This partitions key derivation for a particular purpose+coin tuple, allowing // multiple address derivation schems to be maintained concurrently.
[ "createManagerKeyScope", "creates", "a", "new", "key", "scoped", "for", "a", "target", "manager", "s", "scope", ".", "This", "partitions", "key", "derivation", "for", "a", "particular", "purpose", "+", "coin", "tuple", "allowing", "multiple", "address", "derivation", "schems", "to", "be", "maintained", "concurrently", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/manager.go#L1536-L1632
train
btcsuite/btcwallet
walletsetup.go
networkDir
func networkDir(dataDir string, chainParams *chaincfg.Params) string { netname := chainParams.Name // For now, we must always name the testnet data directory as "testnet" // and not "testnet3" or any other version, as the chaincfg testnet3 // paramaters will likely be switched to being named "testnet3" in the // future. This is done to future proof that change, and an upgrade // plan to move the testnet3 data directory can be worked out later. if chainParams.Net == wire.TestNet3 { netname = "testnet" } return filepath.Join(dataDir, netname) }
go
func networkDir(dataDir string, chainParams *chaincfg.Params) string { netname := chainParams.Name // For now, we must always name the testnet data directory as "testnet" // and not "testnet3" or any other version, as the chaincfg testnet3 // paramaters will likely be switched to being named "testnet3" in the // future. This is done to future proof that change, and an upgrade // plan to move the testnet3 data directory can be worked out later. if chainParams.Net == wire.TestNet3 { netname = "testnet" } return filepath.Join(dataDir, netname) }
[ "func", "networkDir", "(", "dataDir", "string", ",", "chainParams", "*", "chaincfg", ".", "Params", ")", "string", "{", "netname", ":=", "chainParams", ".", "Name", "\n\n", "// For now, we must always name the testnet data directory as \"testnet\"", "// and not \"testnet3\" or any other version, as the chaincfg testnet3", "// paramaters will likely be switched to being named \"testnet3\" in the", "// future. This is done to future proof that change, and an upgrade", "// plan to move the testnet3 data directory can be worked out later.", "if", "chainParams", ".", "Net", "==", "wire", ".", "TestNet3", "{", "netname", "=", "\"", "\"", "\n", "}", "\n\n", "return", "filepath", ".", "Join", "(", "dataDir", ",", "netname", ")", "\n", "}" ]
// networkDir returns the directory name of a network directory to hold wallet // files.
[ "networkDir", "returns", "the", "directory", "name", "of", "a", "network", "directory", "to", "hold", "wallet", "files", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/walletsetup.go#L28-L41
train
btcsuite/btcwallet
walletsetup.go
convertLegacyKeystore
func convertLegacyKeystore(legacyKeyStore *keystore.Store, w *wallet.Wallet) error { netParams := legacyKeyStore.Net() blockStamp := waddrmgr.BlockStamp{ Height: 0, Hash: *netParams.GenesisHash, } for _, walletAddr := range legacyKeyStore.ActiveAddresses() { switch addr := walletAddr.(type) { case keystore.PubKeyAddress: privKey, err := addr.PrivKey() if err != nil { fmt.Printf("WARN: Failed to obtain private key "+ "for address %v: %v\n", addr.Address(), err) continue } wif, err := btcutil.NewWIF((*btcec.PrivateKey)(privKey), netParams, addr.Compressed()) if err != nil { fmt.Printf("WARN: Failed to create wallet "+ "import format for address %v: %v\n", addr.Address(), err) continue } _, err = w.ImportPrivateKey(waddrmgr.KeyScopeBIP0044, wif, &blockStamp, false) if err != nil { fmt.Printf("WARN: Failed to import private "+ "key for address %v: %v\n", addr.Address(), err) continue } case keystore.ScriptAddress: _, err := w.ImportP2SHRedeemScript(addr.Script()) if err != nil { fmt.Printf("WARN: Failed to import "+ "pay-to-script-hash script for "+ "address %v: %v\n", addr.Address(), err) continue } default: fmt.Printf("WARN: Skipping unrecognized legacy "+ "keystore type: %T\n", addr) continue } } return nil }
go
func convertLegacyKeystore(legacyKeyStore *keystore.Store, w *wallet.Wallet) error { netParams := legacyKeyStore.Net() blockStamp := waddrmgr.BlockStamp{ Height: 0, Hash: *netParams.GenesisHash, } for _, walletAddr := range legacyKeyStore.ActiveAddresses() { switch addr := walletAddr.(type) { case keystore.PubKeyAddress: privKey, err := addr.PrivKey() if err != nil { fmt.Printf("WARN: Failed to obtain private key "+ "for address %v: %v\n", addr.Address(), err) continue } wif, err := btcutil.NewWIF((*btcec.PrivateKey)(privKey), netParams, addr.Compressed()) if err != nil { fmt.Printf("WARN: Failed to create wallet "+ "import format for address %v: %v\n", addr.Address(), err) continue } _, err = w.ImportPrivateKey(waddrmgr.KeyScopeBIP0044, wif, &blockStamp, false) if err != nil { fmt.Printf("WARN: Failed to import private "+ "key for address %v: %v\n", addr.Address(), err) continue } case keystore.ScriptAddress: _, err := w.ImportP2SHRedeemScript(addr.Script()) if err != nil { fmt.Printf("WARN: Failed to import "+ "pay-to-script-hash script for "+ "address %v: %v\n", addr.Address(), err) continue } default: fmt.Printf("WARN: Skipping unrecognized legacy "+ "keystore type: %T\n", addr) continue } } return nil }
[ "func", "convertLegacyKeystore", "(", "legacyKeyStore", "*", "keystore", ".", "Store", ",", "w", "*", "wallet", ".", "Wallet", ")", "error", "{", "netParams", ":=", "legacyKeyStore", ".", "Net", "(", ")", "\n", "blockStamp", ":=", "waddrmgr", ".", "BlockStamp", "{", "Height", ":", "0", ",", "Hash", ":", "*", "netParams", ".", "GenesisHash", ",", "}", "\n", "for", "_", ",", "walletAddr", ":=", "range", "legacyKeyStore", ".", "ActiveAddresses", "(", ")", "{", "switch", "addr", ":=", "walletAddr", ".", "(", "type", ")", "{", "case", "keystore", ".", "PubKeyAddress", ":", "privKey", ",", "err", ":=", "addr", ".", "PrivKey", "(", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\"", "+", "\"", "\\n", "\"", ",", "addr", ".", "Address", "(", ")", ",", "err", ")", "\n", "continue", "\n", "}", "\n\n", "wif", ",", "err", ":=", "btcutil", ".", "NewWIF", "(", "(", "*", "btcec", ".", "PrivateKey", ")", "(", "privKey", ")", ",", "netParams", ",", "addr", ".", "Compressed", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\"", "+", "\"", "\\n", "\"", ",", "addr", ".", "Address", "(", ")", ",", "err", ")", "\n", "continue", "\n", "}", "\n\n", "_", ",", "err", "=", "w", ".", "ImportPrivateKey", "(", "waddrmgr", ".", "KeyScopeBIP0044", ",", "wif", ",", "&", "blockStamp", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\"", "+", "\"", "\\n", "\"", ",", "addr", ".", "Address", "(", ")", ",", "err", ")", "\n", "continue", "\n", "}", "\n\n", "case", "keystore", ".", "ScriptAddress", ":", "_", ",", "err", ":=", "w", ".", "ImportP2SHRedeemScript", "(", "addr", ".", "Script", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\\n", "\"", ",", "addr", ".", "Address", "(", ")", ",", "err", ")", "\n", "continue", "\n", "}", "\n\n", "default", ":", "fmt", ".", "Printf", "(", "\"", "\"", "+", "\"", "\\n", "\"", ",", "addr", ")", "\n", "continue", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// convertLegacyKeystore converts all of the addresses in the passed legacy // key store to the new waddrmgr.Manager format. Both the legacy keystore and // the new manager must be unlocked.
[ "convertLegacyKeystore", "converts", "all", "of", "the", "addresses", "in", "the", "passed", "legacy", "key", "store", "to", "the", "new", "waddrmgr", ".", "Manager", "format", ".", "Both", "the", "legacy", "keystore", "and", "the", "new", "manager", "must", "be", "unlocked", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/walletsetup.go#L46-L98
train
btcsuite/btcwallet
walletsetup.go
createWallet
func createWallet(cfg *config) error { dbDir := networkDir(cfg.AppDataDir.Value, activeNet.Params) loader := wallet.NewLoader(activeNet.Params, dbDir, 250) // When there is a legacy keystore, open it now to ensure any errors // don't end up exiting the process after the user has spent time // entering a bunch of information. netDir := networkDir(cfg.AppDataDir.Value, activeNet.Params) keystorePath := filepath.Join(netDir, keystore.Filename) var legacyKeyStore *keystore.Store _, err := os.Stat(keystorePath) if err != nil && !os.IsNotExist(err) { // A stat error not due to a non-existant file should be // returned to the caller. return err } else if err == nil { // Keystore file exists. legacyKeyStore, err = keystore.OpenDir(netDir) if err != nil { return err } } // Start by prompting for the private passphrase. When there is an // existing keystore, the user will be promped for that passphrase, // otherwise they will be prompted for a new one. reader := bufio.NewReader(os.Stdin) privPass, err := prompt.PrivatePass(reader, legacyKeyStore) if err != nil { return err } // When there exists a legacy keystore, unlock it now and set up a // callback to import all keystore keys into the new walletdb // wallet if legacyKeyStore != nil { err = legacyKeyStore.Unlock(privPass) if err != nil { return err } // Import the addresses in the legacy keystore to the new wallet if // any exist, locking each wallet again when finished. loader.RunAfterLoad(func(w *wallet.Wallet) { defer legacyKeyStore.Lock() fmt.Println("Importing addresses from existing wallet...") lockChan := make(chan time.Time, 1) defer func() { lockChan <- time.Time{} }() err := w.Unlock(privPass, lockChan) if err != nil { fmt.Printf("ERR: Failed to unlock new wallet "+ "during old wallet key import: %v", err) return } err = convertLegacyKeystore(legacyKeyStore, w) if err != nil { fmt.Printf("ERR: Failed to import keys from old "+ "wallet format: %v", err) return } // Remove the legacy key store. err = os.Remove(keystorePath) if err != nil { fmt.Printf("WARN: Failed to remove legacy wallet "+ "from'%s'\n", keystorePath) } }) } // Ascertain the public passphrase. This will either be a value // specified by the user or the default hard-coded public passphrase if // the user does not want the additional public data encryption. pubPass, err := prompt.PublicPass(reader, privPass, []byte(wallet.InsecurePubPassphrase), []byte(cfg.WalletPass)) if err != nil { return err } // Ascertain the wallet generation seed. This will either be an // automatically generated value the user has already confirmed or a // value the user has entered which has already been validated. seed, err := prompt.Seed(reader) if err != nil { return err } fmt.Println("Creating the wallet...") w, err := loader.CreateNewWallet(pubPass, privPass, seed, time.Now()) if err != nil { return err } w.Manager.Close() fmt.Println("The wallet has been created successfully.") return nil }
go
func createWallet(cfg *config) error { dbDir := networkDir(cfg.AppDataDir.Value, activeNet.Params) loader := wallet.NewLoader(activeNet.Params, dbDir, 250) // When there is a legacy keystore, open it now to ensure any errors // don't end up exiting the process after the user has spent time // entering a bunch of information. netDir := networkDir(cfg.AppDataDir.Value, activeNet.Params) keystorePath := filepath.Join(netDir, keystore.Filename) var legacyKeyStore *keystore.Store _, err := os.Stat(keystorePath) if err != nil && !os.IsNotExist(err) { // A stat error not due to a non-existant file should be // returned to the caller. return err } else if err == nil { // Keystore file exists. legacyKeyStore, err = keystore.OpenDir(netDir) if err != nil { return err } } // Start by prompting for the private passphrase. When there is an // existing keystore, the user will be promped for that passphrase, // otherwise they will be prompted for a new one. reader := bufio.NewReader(os.Stdin) privPass, err := prompt.PrivatePass(reader, legacyKeyStore) if err != nil { return err } // When there exists a legacy keystore, unlock it now and set up a // callback to import all keystore keys into the new walletdb // wallet if legacyKeyStore != nil { err = legacyKeyStore.Unlock(privPass) if err != nil { return err } // Import the addresses in the legacy keystore to the new wallet if // any exist, locking each wallet again when finished. loader.RunAfterLoad(func(w *wallet.Wallet) { defer legacyKeyStore.Lock() fmt.Println("Importing addresses from existing wallet...") lockChan := make(chan time.Time, 1) defer func() { lockChan <- time.Time{} }() err := w.Unlock(privPass, lockChan) if err != nil { fmt.Printf("ERR: Failed to unlock new wallet "+ "during old wallet key import: %v", err) return } err = convertLegacyKeystore(legacyKeyStore, w) if err != nil { fmt.Printf("ERR: Failed to import keys from old "+ "wallet format: %v", err) return } // Remove the legacy key store. err = os.Remove(keystorePath) if err != nil { fmt.Printf("WARN: Failed to remove legacy wallet "+ "from'%s'\n", keystorePath) } }) } // Ascertain the public passphrase. This will either be a value // specified by the user or the default hard-coded public passphrase if // the user does not want the additional public data encryption. pubPass, err := prompt.PublicPass(reader, privPass, []byte(wallet.InsecurePubPassphrase), []byte(cfg.WalletPass)) if err != nil { return err } // Ascertain the wallet generation seed. This will either be an // automatically generated value the user has already confirmed or a // value the user has entered which has already been validated. seed, err := prompt.Seed(reader) if err != nil { return err } fmt.Println("Creating the wallet...") w, err := loader.CreateNewWallet(pubPass, privPass, seed, time.Now()) if err != nil { return err } w.Manager.Close() fmt.Println("The wallet has been created successfully.") return nil }
[ "func", "createWallet", "(", "cfg", "*", "config", ")", "error", "{", "dbDir", ":=", "networkDir", "(", "cfg", ".", "AppDataDir", ".", "Value", ",", "activeNet", ".", "Params", ")", "\n", "loader", ":=", "wallet", ".", "NewLoader", "(", "activeNet", ".", "Params", ",", "dbDir", ",", "250", ")", "\n\n", "// When there is a legacy keystore, open it now to ensure any errors", "// don't end up exiting the process after the user has spent time", "// entering a bunch of information.", "netDir", ":=", "networkDir", "(", "cfg", ".", "AppDataDir", ".", "Value", ",", "activeNet", ".", "Params", ")", "\n", "keystorePath", ":=", "filepath", ".", "Join", "(", "netDir", ",", "keystore", ".", "Filename", ")", "\n", "var", "legacyKeyStore", "*", "keystore", ".", "Store", "\n", "_", ",", "err", ":=", "os", ".", "Stat", "(", "keystorePath", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "// A stat error not due to a non-existant file should be", "// returned to the caller.", "return", "err", "\n", "}", "else", "if", "err", "==", "nil", "{", "// Keystore file exists.", "legacyKeyStore", ",", "err", "=", "keystore", ".", "OpenDir", "(", "netDir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "// Start by prompting for the private passphrase. When there is an", "// existing keystore, the user will be promped for that passphrase,", "// otherwise they will be prompted for a new one.", "reader", ":=", "bufio", ".", "NewReader", "(", "os", ".", "Stdin", ")", "\n", "privPass", ",", "err", ":=", "prompt", ".", "PrivatePass", "(", "reader", ",", "legacyKeyStore", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// When there exists a legacy keystore, unlock it now and set up a", "// callback to import all keystore keys into the new walletdb", "// wallet", "if", "legacyKeyStore", "!=", "nil", "{", "err", "=", "legacyKeyStore", ".", "Unlock", "(", "privPass", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Import the addresses in the legacy keystore to the new wallet if", "// any exist, locking each wallet again when finished.", "loader", ".", "RunAfterLoad", "(", "func", "(", "w", "*", "wallet", ".", "Wallet", ")", "{", "defer", "legacyKeyStore", ".", "Lock", "(", ")", "\n\n", "fmt", ".", "Println", "(", "\"", "\"", ")", "\n\n", "lockChan", ":=", "make", "(", "chan", "time", ".", "Time", ",", "1", ")", "\n", "defer", "func", "(", ")", "{", "lockChan", "<-", "time", ".", "Time", "{", "}", "\n", "}", "(", ")", "\n", "err", ":=", "w", ".", "Unlock", "(", "privPass", ",", "lockChan", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\"", "+", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "err", "=", "convertLegacyKeystore", "(", "legacyKeyStore", ",", "w", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\"", "+", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "// Remove the legacy key store.", "err", "=", "os", ".", "Remove", "(", "keystorePath", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\"", "+", "\"", "\\n", "\"", ",", "keystorePath", ")", "\n", "}", "\n", "}", ")", "\n", "}", "\n\n", "// Ascertain the public passphrase. This will either be a value", "// specified by the user or the default hard-coded public passphrase if", "// the user does not want the additional public data encryption.", "pubPass", ",", "err", ":=", "prompt", ".", "PublicPass", "(", "reader", ",", "privPass", ",", "[", "]", "byte", "(", "wallet", ".", "InsecurePubPassphrase", ")", ",", "[", "]", "byte", "(", "cfg", ".", "WalletPass", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Ascertain the wallet generation seed. This will either be an", "// automatically generated value the user has already confirmed or a", "// value the user has entered which has already been validated.", "seed", ",", "err", ":=", "prompt", ".", "Seed", "(", "reader", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "fmt", ".", "Println", "(", "\"", "\"", ")", "\n", "w", ",", "err", ":=", "loader", ".", "CreateNewWallet", "(", "pubPass", ",", "privPass", ",", "seed", ",", "time", ".", "Now", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "w", ".", "Manager", ".", "Close", "(", ")", "\n", "fmt", ".", "Println", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}" ]
// createWallet prompts the user for information needed to generate a new wallet // and generates the wallet accordingly. The new wallet will reside at the // provided path.
[ "createWallet", "prompts", "the", "user", "for", "information", "needed", "to", "generate", "a", "new", "wallet", "and", "generates", "the", "wallet", "accordingly", ".", "The", "new", "wallet", "will", "reside", "at", "the", "provided", "path", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/walletsetup.go#L103-L204
train
btcsuite/btcwallet
walletsetup.go
createSimulationWallet
func createSimulationWallet(cfg *config) error { // Simulation wallet password is 'password'. privPass := []byte("password") // Public passphrase is the default. pubPass := []byte(wallet.InsecurePubPassphrase) netDir := networkDir(cfg.AppDataDir.Value, activeNet.Params) // Create the wallet. dbPath := filepath.Join(netDir, walletDbName) fmt.Println("Creating the wallet...") // Create the wallet database backed by bolt db. db, err := walletdb.Create("bdb", dbPath) if err != nil { return err } defer db.Close() // Create the wallet. err = wallet.Create(db, pubPass, privPass, nil, activeNet.Params, time.Now()) if err != nil { return err } fmt.Println("The wallet has been created successfully.") return nil }
go
func createSimulationWallet(cfg *config) error { // Simulation wallet password is 'password'. privPass := []byte("password") // Public passphrase is the default. pubPass := []byte(wallet.InsecurePubPassphrase) netDir := networkDir(cfg.AppDataDir.Value, activeNet.Params) // Create the wallet. dbPath := filepath.Join(netDir, walletDbName) fmt.Println("Creating the wallet...") // Create the wallet database backed by bolt db. db, err := walletdb.Create("bdb", dbPath) if err != nil { return err } defer db.Close() // Create the wallet. err = wallet.Create(db, pubPass, privPass, nil, activeNet.Params, time.Now()) if err != nil { return err } fmt.Println("The wallet has been created successfully.") return nil }
[ "func", "createSimulationWallet", "(", "cfg", "*", "config", ")", "error", "{", "// Simulation wallet password is 'password'.", "privPass", ":=", "[", "]", "byte", "(", "\"", "\"", ")", "\n\n", "// Public passphrase is the default.", "pubPass", ":=", "[", "]", "byte", "(", "wallet", ".", "InsecurePubPassphrase", ")", "\n\n", "netDir", ":=", "networkDir", "(", "cfg", ".", "AppDataDir", ".", "Value", ",", "activeNet", ".", "Params", ")", "\n\n", "// Create the wallet.", "dbPath", ":=", "filepath", ".", "Join", "(", "netDir", ",", "walletDbName", ")", "\n", "fmt", ".", "Println", "(", "\"", "\"", ")", "\n\n", "// Create the wallet database backed by bolt db.", "db", ",", "err", ":=", "walletdb", ".", "Create", "(", "\"", "\"", ",", "dbPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "db", ".", "Close", "(", ")", "\n\n", "// Create the wallet.", "err", "=", "wallet", ".", "Create", "(", "db", ",", "pubPass", ",", "privPass", ",", "nil", ",", "activeNet", ".", "Params", ",", "time", ".", "Now", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "fmt", ".", "Println", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}" ]
// createSimulationWallet is intended to be called from the rpcclient // and used to create a wallet for actors involved in simulations.
[ "createSimulationWallet", "is", "intended", "to", "be", "called", "from", "the", "rpcclient", "and", "used", "to", "create", "a", "wallet", "for", "actors", "involved", "in", "simulations", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/walletsetup.go#L208-L236
train
btcsuite/btcwallet
walletsetup.go
checkCreateDir
func checkCreateDir(path string) error { if fi, err := os.Stat(path); err != nil { if os.IsNotExist(err) { // Attempt data directory creation if err = os.MkdirAll(path, 0700); err != nil { return fmt.Errorf("cannot create directory: %s", err) } } else { return fmt.Errorf("error checking directory: %s", err) } } else { if !fi.IsDir() { return fmt.Errorf("path '%s' is not a directory", path) } } return nil }
go
func checkCreateDir(path string) error { if fi, err := os.Stat(path); err != nil { if os.IsNotExist(err) { // Attempt data directory creation if err = os.MkdirAll(path, 0700); err != nil { return fmt.Errorf("cannot create directory: %s", err) } } else { return fmt.Errorf("error checking directory: %s", err) } } else { if !fi.IsDir() { return fmt.Errorf("path '%s' is not a directory", path) } } return nil }
[ "func", "checkCreateDir", "(", "path", "string", ")", "error", "{", "if", "fi", ",", "err", ":=", "os", ".", "Stat", "(", "path", ")", ";", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "// Attempt data directory creation", "if", "err", "=", "os", ".", "MkdirAll", "(", "path", ",", "0700", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "else", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "else", "{", "if", "!", "fi", ".", "IsDir", "(", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "path", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// checkCreateDir checks that the path exists and is a directory. // If path does not exist, it is created.
[ "checkCreateDir", "checks", "that", "the", "path", "exists", "and", "is", "a", "directory", ".", "If", "path", "does", "not", "exist", "it", "is", "created", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/walletsetup.go#L240-L257
train
btcsuite/btcwallet
waddrmgr/db.go
maybeConvertDbError
func maybeConvertDbError(err error) error { // When the error is already a ManagerError, just return it. if _, ok := err.(ManagerError); ok { return err } return managerError(ErrDatabase, err.Error(), err) }
go
func maybeConvertDbError(err error) error { // When the error is already a ManagerError, just return it. if _, ok := err.(ManagerError); ok { return err } return managerError(ErrDatabase, err.Error(), err) }
[ "func", "maybeConvertDbError", "(", "err", "error", ")", "error", "{", "// When the error is already a ManagerError, just return it.", "if", "_", ",", "ok", ":=", "err", ".", "(", "ManagerError", ")", ";", "ok", "{", "return", "err", "\n", "}", "\n\n", "return", "managerError", "(", "ErrDatabase", ",", "err", ".", "Error", "(", ")", ",", "err", ")", "\n", "}" ]
// maybeConvertDbError converts the passed error to a ManagerError with an // error code of ErrDatabase if it is not already a ManagerError. This is // useful for potential errors returned from managed transaction an other parts // of the walletdb database.
[ "maybeConvertDbError", "converts", "the", "passed", "error", "to", "a", "ManagerError", "with", "an", "error", "code", "of", "ErrDatabase", "if", "it", "is", "not", "already", "a", "ManagerError", ".", "This", "is", "useful", "for", "potential", "errors", "returned", "from", "managed", "transaction", "an", "other", "parts", "of", "the", "walletdb", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L37-L44
train
btcsuite/btcwallet
waddrmgr/db.go
scopeToBytes
func scopeToBytes(scope *KeyScope) [scopeKeySize]byte { var scopeBytes [scopeKeySize]byte binary.LittleEndian.PutUint32(scopeBytes[:], scope.Purpose) binary.LittleEndian.PutUint32(scopeBytes[4:], scope.Coin) return scopeBytes }
go
func scopeToBytes(scope *KeyScope) [scopeKeySize]byte { var scopeBytes [scopeKeySize]byte binary.LittleEndian.PutUint32(scopeBytes[:], scope.Purpose) binary.LittleEndian.PutUint32(scopeBytes[4:], scope.Coin) return scopeBytes }
[ "func", "scopeToBytes", "(", "scope", "*", "KeyScope", ")", "[", "scopeKeySize", "]", "byte", "{", "var", "scopeBytes", "[", "scopeKeySize", "]", "byte", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "scopeBytes", "[", ":", "]", ",", "scope", ".", "Purpose", ")", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "scopeBytes", "[", "4", ":", "]", ",", "scope", ".", "Coin", ")", "\n\n", "return", "scopeBytes", "\n", "}" ]
// scopeToBytes transforms a manager's scope into the form that will be used to // retrieve the bucket that all information for a particular scope is stored // under
[ "scopeToBytes", "transforms", "a", "manager", "s", "scope", "into", "the", "form", "that", "will", "be", "used", "to", "retrieve", "the", "bucket", "that", "all", "information", "for", "a", "particular", "scope", "is", "stored", "under" ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L299-L305
train
btcsuite/btcwallet
waddrmgr/db.go
scopeFromBytes
func scopeFromBytes(scopeBytes []byte) KeyScope { return KeyScope{ Purpose: binary.LittleEndian.Uint32(scopeBytes[:]), Coin: binary.LittleEndian.Uint32(scopeBytes[4:]), } }
go
func scopeFromBytes(scopeBytes []byte) KeyScope { return KeyScope{ Purpose: binary.LittleEndian.Uint32(scopeBytes[:]), Coin: binary.LittleEndian.Uint32(scopeBytes[4:]), } }
[ "func", "scopeFromBytes", "(", "scopeBytes", "[", "]", "byte", ")", "KeyScope", "{", "return", "KeyScope", "{", "Purpose", ":", "binary", ".", "LittleEndian", ".", "Uint32", "(", "scopeBytes", "[", ":", "]", ")", ",", "Coin", ":", "binary", ".", "LittleEndian", ".", "Uint32", "(", "scopeBytes", "[", "4", ":", "]", ")", ",", "}", "\n", "}" ]
// scopeFromBytes decodes a serializes manager scope into its concrete manager // scope struct.
[ "scopeFromBytes", "decodes", "a", "serializes", "manager", "scope", "into", "its", "concrete", "manager", "scope", "struct", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L309-L314
train
btcsuite/btcwallet
waddrmgr/db.go
scopeSchemaToBytes
func scopeSchemaToBytes(schema *ScopeAddrSchema) []byte { var schemaBytes [2]byte schemaBytes[0] = byte(schema.InternalAddrType) schemaBytes[1] = byte(schema.ExternalAddrType) return schemaBytes[:] }
go
func scopeSchemaToBytes(schema *ScopeAddrSchema) []byte { var schemaBytes [2]byte schemaBytes[0] = byte(schema.InternalAddrType) schemaBytes[1] = byte(schema.ExternalAddrType) return schemaBytes[:] }
[ "func", "scopeSchemaToBytes", "(", "schema", "*", "ScopeAddrSchema", ")", "[", "]", "byte", "{", "var", "schemaBytes", "[", "2", "]", "byte", "\n", "schemaBytes", "[", "0", "]", "=", "byte", "(", "schema", ".", "InternalAddrType", ")", "\n", "schemaBytes", "[", "1", "]", "=", "byte", "(", "schema", ".", "ExternalAddrType", ")", "\n\n", "return", "schemaBytes", "[", ":", "]", "\n", "}" ]
// scopeSchemaToBytes encodes the passed scope schema as a set of bytes // suitable for storage within the database.
[ "scopeSchemaToBytes", "encodes", "the", "passed", "scope", "schema", "as", "a", "set", "of", "bytes", "suitable", "for", "storage", "within", "the", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L318-L324
train
btcsuite/btcwallet
waddrmgr/db.go
scopeSchemaFromBytes
func scopeSchemaFromBytes(schemaBytes []byte) *ScopeAddrSchema { return &ScopeAddrSchema{ InternalAddrType: AddressType(schemaBytes[0]), ExternalAddrType: AddressType(schemaBytes[1]), } }
go
func scopeSchemaFromBytes(schemaBytes []byte) *ScopeAddrSchema { return &ScopeAddrSchema{ InternalAddrType: AddressType(schemaBytes[0]), ExternalAddrType: AddressType(schemaBytes[1]), } }
[ "func", "scopeSchemaFromBytes", "(", "schemaBytes", "[", "]", "byte", ")", "*", "ScopeAddrSchema", "{", "return", "&", "ScopeAddrSchema", "{", "InternalAddrType", ":", "AddressType", "(", "schemaBytes", "[", "0", "]", ")", ",", "ExternalAddrType", ":", "AddressType", "(", "schemaBytes", "[", "1", "]", ")", ",", "}", "\n", "}" ]
// scopeSchemaFromBytes decodes a new scope schema instance from the set of // serialized bytes.
[ "scopeSchemaFromBytes", "decodes", "a", "new", "scope", "schema", "instance", "from", "the", "set", "of", "serialized", "bytes", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L328-L333
train
btcsuite/btcwallet
waddrmgr/db.go
fetchScopeAddrSchema
func fetchScopeAddrSchema(ns walletdb.ReadBucket, scope *KeyScope) (*ScopeAddrSchema, error) { schemaBucket := ns.NestedReadBucket(scopeSchemaBucketName) if schemaBucket == nil { str := fmt.Sprintf("unable to find scope schema bucket") return nil, managerError(ErrScopeNotFound, str, nil) } scopeKey := scopeToBytes(scope) schemaBytes := schemaBucket.Get(scopeKey[:]) if schemaBytes == nil { str := fmt.Sprintf("unable to find scope %v", scope) return nil, managerError(ErrScopeNotFound, str, nil) } return scopeSchemaFromBytes(schemaBytes), nil }
go
func fetchScopeAddrSchema(ns walletdb.ReadBucket, scope *KeyScope) (*ScopeAddrSchema, error) { schemaBucket := ns.NestedReadBucket(scopeSchemaBucketName) if schemaBucket == nil { str := fmt.Sprintf("unable to find scope schema bucket") return nil, managerError(ErrScopeNotFound, str, nil) } scopeKey := scopeToBytes(scope) schemaBytes := schemaBucket.Get(scopeKey[:]) if schemaBytes == nil { str := fmt.Sprintf("unable to find scope %v", scope) return nil, managerError(ErrScopeNotFound, str, nil) } return scopeSchemaFromBytes(schemaBytes), nil }
[ "func", "fetchScopeAddrSchema", "(", "ns", "walletdb", ".", "ReadBucket", ",", "scope", "*", "KeyScope", ")", "(", "*", "ScopeAddrSchema", ",", "error", ")", "{", "schemaBucket", ":=", "ns", ".", "NestedReadBucket", "(", "scopeSchemaBucketName", ")", "\n", "if", "schemaBucket", "==", "nil", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "managerError", "(", "ErrScopeNotFound", ",", "str", ",", "nil", ")", "\n", "}", "\n\n", "scopeKey", ":=", "scopeToBytes", "(", "scope", ")", "\n", "schemaBytes", ":=", "schemaBucket", ".", "Get", "(", "scopeKey", "[", ":", "]", ")", "\n", "if", "schemaBytes", "==", "nil", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "scope", ")", "\n", "return", "nil", ",", "managerError", "(", "ErrScopeNotFound", ",", "str", ",", "nil", ")", "\n", "}", "\n\n", "return", "scopeSchemaFromBytes", "(", "schemaBytes", ")", ",", "nil", "\n", "}" ]
// fetchScopeAddrSchema will attempt to retrieve the address schema for a // particular manager scope stored within the database. These are used in order // to properly type each address generated by the scope address manager.
[ "fetchScopeAddrSchema", "will", "attempt", "to", "retrieve", "the", "address", "schema", "for", "a", "particular", "manager", "scope", "stored", "within", "the", "database", ".", "These", "are", "used", "in", "order", "to", "properly", "type", "each", "address", "generated", "by", "the", "scope", "address", "manager", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L338-L355
train
btcsuite/btcwallet
waddrmgr/db.go
putScopeAddrTypes
func putScopeAddrTypes(ns walletdb.ReadWriteBucket, scope *KeyScope, schema *ScopeAddrSchema) error { scopeSchemaBucket := ns.NestedReadWriteBucket(scopeSchemaBucketName) if scopeSchemaBucket == nil { str := fmt.Sprintf("unable to find scope schema bucket") return managerError(ErrScopeNotFound, str, nil) } scopeKey := scopeToBytes(scope) schemaBytes := scopeSchemaToBytes(schema) return scopeSchemaBucket.Put(scopeKey[:], schemaBytes) }
go
func putScopeAddrTypes(ns walletdb.ReadWriteBucket, scope *KeyScope, schema *ScopeAddrSchema) error { scopeSchemaBucket := ns.NestedReadWriteBucket(scopeSchemaBucketName) if scopeSchemaBucket == nil { str := fmt.Sprintf("unable to find scope schema bucket") return managerError(ErrScopeNotFound, str, nil) } scopeKey := scopeToBytes(scope) schemaBytes := scopeSchemaToBytes(schema) return scopeSchemaBucket.Put(scopeKey[:], schemaBytes) }
[ "func", "putScopeAddrTypes", "(", "ns", "walletdb", ".", "ReadWriteBucket", ",", "scope", "*", "KeyScope", ",", "schema", "*", "ScopeAddrSchema", ")", "error", "{", "scopeSchemaBucket", ":=", "ns", ".", "NestedReadWriteBucket", "(", "scopeSchemaBucketName", ")", "\n", "if", "scopeSchemaBucket", "==", "nil", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ")", "\n", "return", "managerError", "(", "ErrScopeNotFound", ",", "str", ",", "nil", ")", "\n", "}", "\n\n", "scopeKey", ":=", "scopeToBytes", "(", "scope", ")", "\n", "schemaBytes", ":=", "scopeSchemaToBytes", "(", "schema", ")", "\n", "return", "scopeSchemaBucket", ".", "Put", "(", "scopeKey", "[", ":", "]", ",", "schemaBytes", ")", "\n", "}" ]
// putScopeAddrSchema attempts to store the passed addr scehma for the given // manager scope.
[ "putScopeAddrSchema", "attempts", "to", "store", "the", "passed", "addr", "scehma", "for", "the", "given", "manager", "scope", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L359-L371
train
btcsuite/btcwallet
waddrmgr/db.go
fetchManagerVersion
func fetchManagerVersion(ns walletdb.ReadBucket) (uint32, error) { mainBucket := ns.NestedReadBucket(mainBucketName) verBytes := mainBucket.Get(mgrVersionName) if verBytes == nil { str := "required version number not stored in database" return 0, managerError(ErrDatabase, str, nil) } version := binary.LittleEndian.Uint32(verBytes) return version, nil }
go
func fetchManagerVersion(ns walletdb.ReadBucket) (uint32, error) { mainBucket := ns.NestedReadBucket(mainBucketName) verBytes := mainBucket.Get(mgrVersionName) if verBytes == nil { str := "required version number not stored in database" return 0, managerError(ErrDatabase, str, nil) } version := binary.LittleEndian.Uint32(verBytes) return version, nil }
[ "func", "fetchManagerVersion", "(", "ns", "walletdb", ".", "ReadBucket", ")", "(", "uint32", ",", "error", ")", "{", "mainBucket", ":=", "ns", ".", "NestedReadBucket", "(", "mainBucketName", ")", "\n", "verBytes", ":=", "mainBucket", ".", "Get", "(", "mgrVersionName", ")", "\n", "if", "verBytes", "==", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "0", ",", "managerError", "(", "ErrDatabase", ",", "str", ",", "nil", ")", "\n", "}", "\n", "version", ":=", "binary", ".", "LittleEndian", ".", "Uint32", "(", "verBytes", ")", "\n", "return", "version", ",", "nil", "\n", "}" ]
// fetchManagerVersion fetches the current manager version from the database.
[ "fetchManagerVersion", "fetches", "the", "current", "manager", "version", "from", "the", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L402-L411
train
btcsuite/btcwallet
waddrmgr/db.go
putManagerVersion
func putManagerVersion(ns walletdb.ReadWriteBucket, version uint32) error { bucket := ns.NestedReadWriteBucket(mainBucketName) verBytes := uint32ToBytes(version) err := bucket.Put(mgrVersionName, verBytes) if err != nil { str := "failed to store version" return managerError(ErrDatabase, str, err) } return nil }
go
func putManagerVersion(ns walletdb.ReadWriteBucket, version uint32) error { bucket := ns.NestedReadWriteBucket(mainBucketName) verBytes := uint32ToBytes(version) err := bucket.Put(mgrVersionName, verBytes) if err != nil { str := "failed to store version" return managerError(ErrDatabase, str, err) } return nil }
[ "func", "putManagerVersion", "(", "ns", "walletdb", ".", "ReadWriteBucket", ",", "version", "uint32", ")", "error", "{", "bucket", ":=", "ns", ".", "NestedReadWriteBucket", "(", "mainBucketName", ")", "\n\n", "verBytes", ":=", "uint32ToBytes", "(", "version", ")", "\n", "err", ":=", "bucket", ".", "Put", "(", "mgrVersionName", ",", "verBytes", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "managerError", "(", "ErrDatabase", ",", "str", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// putManagerVersion stores the provided version to the database.
[ "putManagerVersion", "stores", "the", "provided", "version", "to", "the", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L414-L424
train
btcsuite/btcwallet
waddrmgr/db.go
putMasterKeyParams
func putMasterKeyParams(ns walletdb.ReadWriteBucket, pubParams, privParams []byte) error { bucket := ns.NestedReadWriteBucket(mainBucketName) if privParams != nil { err := bucket.Put(masterPrivKeyName, privParams) if err != nil { str := "failed to store master private key parameters" return managerError(ErrDatabase, str, err) } } if pubParams != nil { err := bucket.Put(masterPubKeyName, pubParams) if err != nil { str := "failed to store master public key parameters" return managerError(ErrDatabase, str, err) } } return nil }
go
func putMasterKeyParams(ns walletdb.ReadWriteBucket, pubParams, privParams []byte) error { bucket := ns.NestedReadWriteBucket(mainBucketName) if privParams != nil { err := bucket.Put(masterPrivKeyName, privParams) if err != nil { str := "failed to store master private key parameters" return managerError(ErrDatabase, str, err) } } if pubParams != nil { err := bucket.Put(masterPubKeyName, pubParams) if err != nil { str := "failed to store master public key parameters" return managerError(ErrDatabase, str, err) } } return nil }
[ "func", "putMasterKeyParams", "(", "ns", "walletdb", ".", "ReadWriteBucket", ",", "pubParams", ",", "privParams", "[", "]", "byte", ")", "error", "{", "bucket", ":=", "ns", ".", "NestedReadWriteBucket", "(", "mainBucketName", ")", "\n\n", "if", "privParams", "!=", "nil", "{", "err", ":=", "bucket", ".", "Put", "(", "masterPrivKeyName", ",", "privParams", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "managerError", "(", "ErrDatabase", ",", "str", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "if", "pubParams", "!=", "nil", "{", "err", ":=", "bucket", ".", "Put", "(", "masterPubKeyName", ",", "pubParams", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "managerError", "(", "ErrDatabase", ",", "str", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// putMasterKeyParams stores the master key parameters needed to derive them to // the database. Either parameter can be nil in which case no value is // written for the parameter.
[ "putMasterKeyParams", "stores", "the", "master", "key", "parameters", "needed", "to", "derive", "them", "to", "the", "database", ".", "Either", "parameter", "can", "be", "nil", "in", "which", "case", "no", "value", "is", "written", "for", "the", "parameter", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L457-L477
train
btcsuite/btcwallet
waddrmgr/db.go
fetchCoinTypeKeys
func fetchCoinTypeKeys(ns walletdb.ReadBucket, scope *KeyScope) ([]byte, []byte, error) { scopedBucket, err := fetchReadScopeBucket(ns, scope) if err != nil { return nil, nil, err } coinTypePubKeyEnc := scopedBucket.Get(coinTypePubKeyName) if coinTypePubKeyEnc == nil { str := "required encrypted cointype public key not stored in database" return nil, nil, managerError(ErrDatabase, str, nil) } coinTypePrivKeyEnc := scopedBucket.Get(coinTypePrivKeyName) if coinTypePrivKeyEnc == nil { str := "required encrypted cointype private key not stored in database" return nil, nil, managerError(ErrDatabase, str, nil) } return coinTypePubKeyEnc, coinTypePrivKeyEnc, nil }
go
func fetchCoinTypeKeys(ns walletdb.ReadBucket, scope *KeyScope) ([]byte, []byte, error) { scopedBucket, err := fetchReadScopeBucket(ns, scope) if err != nil { return nil, nil, err } coinTypePubKeyEnc := scopedBucket.Get(coinTypePubKeyName) if coinTypePubKeyEnc == nil { str := "required encrypted cointype public key not stored in database" return nil, nil, managerError(ErrDatabase, str, nil) } coinTypePrivKeyEnc := scopedBucket.Get(coinTypePrivKeyName) if coinTypePrivKeyEnc == nil { str := "required encrypted cointype private key not stored in database" return nil, nil, managerError(ErrDatabase, str, nil) } return coinTypePubKeyEnc, coinTypePrivKeyEnc, nil }
[ "func", "fetchCoinTypeKeys", "(", "ns", "walletdb", ".", "ReadBucket", ",", "scope", "*", "KeyScope", ")", "(", "[", "]", "byte", ",", "[", "]", "byte", ",", "error", ")", "{", "scopedBucket", ",", "err", ":=", "fetchReadScopeBucket", "(", "ns", ",", "scope", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "coinTypePubKeyEnc", ":=", "scopedBucket", ".", "Get", "(", "coinTypePubKeyName", ")", "\n", "if", "coinTypePubKeyEnc", "==", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "nil", ",", "nil", ",", "managerError", "(", "ErrDatabase", ",", "str", ",", "nil", ")", "\n", "}", "\n\n", "coinTypePrivKeyEnc", ":=", "scopedBucket", ".", "Get", "(", "coinTypePrivKeyName", ")", "\n", "if", "coinTypePrivKeyEnc", "==", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "nil", ",", "nil", ",", "managerError", "(", "ErrDatabase", ",", "str", ",", "nil", ")", "\n", "}", "\n\n", "return", "coinTypePubKeyEnc", ",", "coinTypePrivKeyEnc", ",", "nil", "\n", "}" ]
// fetchCoinTypeKeys loads the encrypted cointype keys which are in turn used // to derive the extended keys for all accounts. Each cointype key is // associated with a particular manager scoped.
[ "fetchCoinTypeKeys", "loads", "the", "encrypted", "cointype", "keys", "which", "are", "in", "turn", "used", "to", "derive", "the", "extended", "keys", "for", "all", "accounts", ".", "Each", "cointype", "key", "is", "associated", "with", "a", "particular", "manager", "scoped", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L482-L501
train
btcsuite/btcwallet
waddrmgr/db.go
putCoinTypeKeys
func putCoinTypeKeys(ns walletdb.ReadWriteBucket, scope *KeyScope, coinTypePubKeyEnc []byte, coinTypePrivKeyEnc []byte) error { scopedBucket, err := fetchWriteScopeBucket(ns, scope) if err != nil { return err } if coinTypePubKeyEnc != nil { err := scopedBucket.Put(coinTypePubKeyName, coinTypePubKeyEnc) if err != nil { str := "failed to store encrypted cointype public key" return managerError(ErrDatabase, str, err) } } if coinTypePrivKeyEnc != nil { err := scopedBucket.Put(coinTypePrivKeyName, coinTypePrivKeyEnc) if err != nil { str := "failed to store encrypted cointype private key" return managerError(ErrDatabase, str, err) } } return nil }
go
func putCoinTypeKeys(ns walletdb.ReadWriteBucket, scope *KeyScope, coinTypePubKeyEnc []byte, coinTypePrivKeyEnc []byte) error { scopedBucket, err := fetchWriteScopeBucket(ns, scope) if err != nil { return err } if coinTypePubKeyEnc != nil { err := scopedBucket.Put(coinTypePubKeyName, coinTypePubKeyEnc) if err != nil { str := "failed to store encrypted cointype public key" return managerError(ErrDatabase, str, err) } } if coinTypePrivKeyEnc != nil { err := scopedBucket.Put(coinTypePrivKeyName, coinTypePrivKeyEnc) if err != nil { str := "failed to store encrypted cointype private key" return managerError(ErrDatabase, str, err) } } return nil }
[ "func", "putCoinTypeKeys", "(", "ns", "walletdb", ".", "ReadWriteBucket", ",", "scope", "*", "KeyScope", ",", "coinTypePubKeyEnc", "[", "]", "byte", ",", "coinTypePrivKeyEnc", "[", "]", "byte", ")", "error", "{", "scopedBucket", ",", "err", ":=", "fetchWriteScopeBucket", "(", "ns", ",", "scope", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "coinTypePubKeyEnc", "!=", "nil", "{", "err", ":=", "scopedBucket", ".", "Put", "(", "coinTypePubKeyName", ",", "coinTypePubKeyEnc", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "managerError", "(", "ErrDatabase", ",", "str", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "if", "coinTypePrivKeyEnc", "!=", "nil", "{", "err", ":=", "scopedBucket", ".", "Put", "(", "coinTypePrivKeyName", ",", "coinTypePrivKeyEnc", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "managerError", "(", "ErrDatabase", ",", "str", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// putCoinTypeKeys stores the encrypted cointype keys which are in turn used to // derive the extended keys for all accounts. Either parameter can be nil in // which case no value is written for the parameter. Each cointype key is // associated with a particular manager scope.
[ "putCoinTypeKeys", "stores", "the", "encrypted", "cointype", "keys", "which", "are", "in", "turn", "used", "to", "derive", "the", "extended", "keys", "for", "all", "accounts", ".", "Either", "parameter", "can", "be", "nil", "in", "which", "case", "no", "value", "is", "written", "for", "the", "parameter", ".", "Each", "cointype", "key", "is", "associated", "with", "a", "particular", "manager", "scope", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L507-L532
train
btcsuite/btcwallet
waddrmgr/db.go
putMasterHDKeys
func putMasterHDKeys(ns walletdb.ReadWriteBucket, masterHDPrivEnc, masterHDPubEnc []byte) error { // As this is the key for the root manager, we don't need to fetch any // particular scope, and can insert directly within the main bucket. bucket := ns.NestedReadWriteBucket(mainBucketName) // Now that we have the main bucket, we can directly store each of the // relevant keys. If we're in watch only mode, then some or all of // these keys might not be available. if masterHDPrivEnc != nil { err := bucket.Put(masterHDPrivName, masterHDPrivEnc) if err != nil { str := "failed to store encrypted master HD private key" return managerError(ErrDatabase, str, err) } } if masterHDPubEnc != nil { err := bucket.Put(masterHDPubName, masterHDPubEnc) if err != nil { str := "failed to store encrypted master HD public key" return managerError(ErrDatabase, str, err) } } return nil }
go
func putMasterHDKeys(ns walletdb.ReadWriteBucket, masterHDPrivEnc, masterHDPubEnc []byte) error { // As this is the key for the root manager, we don't need to fetch any // particular scope, and can insert directly within the main bucket. bucket := ns.NestedReadWriteBucket(mainBucketName) // Now that we have the main bucket, we can directly store each of the // relevant keys. If we're in watch only mode, then some or all of // these keys might not be available. if masterHDPrivEnc != nil { err := bucket.Put(masterHDPrivName, masterHDPrivEnc) if err != nil { str := "failed to store encrypted master HD private key" return managerError(ErrDatabase, str, err) } } if masterHDPubEnc != nil { err := bucket.Put(masterHDPubName, masterHDPubEnc) if err != nil { str := "failed to store encrypted master HD public key" return managerError(ErrDatabase, str, err) } } return nil }
[ "func", "putMasterHDKeys", "(", "ns", "walletdb", ".", "ReadWriteBucket", ",", "masterHDPrivEnc", ",", "masterHDPubEnc", "[", "]", "byte", ")", "error", "{", "// As this is the key for the root manager, we don't need to fetch any", "// particular scope, and can insert directly within the main bucket.", "bucket", ":=", "ns", ".", "NestedReadWriteBucket", "(", "mainBucketName", ")", "\n\n", "// Now that we have the main bucket, we can directly store each of the", "// relevant keys. If we're in watch only mode, then some or all of", "// these keys might not be available.", "if", "masterHDPrivEnc", "!=", "nil", "{", "err", ":=", "bucket", ".", "Put", "(", "masterHDPrivName", ",", "masterHDPrivEnc", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "managerError", "(", "ErrDatabase", ",", "str", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "if", "masterHDPubEnc", "!=", "nil", "{", "err", ":=", "bucket", ".", "Put", "(", "masterHDPubName", ",", "masterHDPubEnc", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "managerError", "(", "ErrDatabase", ",", "str", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// putMasterHDKeys stores the encrypted master HD keys in the top level main // bucket. These are required in order to create any new manager scopes, as // those are created via hardened derivation of the children of this key.
[ "putMasterHDKeys", "stores", "the", "encrypted", "master", "HD", "keys", "in", "the", "top", "level", "main", "bucket", ".", "These", "are", "required", "in", "order", "to", "create", "any", "new", "manager", "scopes", "as", "those", "are", "created", "via", "hardened", "derivation", "of", "the", "children", "of", "this", "key", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L537-L562
train
btcsuite/btcwallet
waddrmgr/db.go
fetchMasterHDKeys
func fetchMasterHDKeys(ns walletdb.ReadBucket) ([]byte, []byte, error) { bucket := ns.NestedReadBucket(mainBucketName) var masterHDPrivEnc, masterHDPubEnc []byte // First, we'll try to fetch the master private key. If this database // is watch only, or the master has been neutered, then this won't be // found on disk. key := bucket.Get(masterHDPrivName) if key != nil { masterHDPrivEnc = make([]byte, len(key)) copy(masterHDPrivEnc[:], key) } key = bucket.Get(masterHDPubName) if key != nil { masterHDPubEnc = make([]byte, len(key)) copy(masterHDPubEnc[:], key) } return masterHDPrivEnc, masterHDPubEnc, nil }
go
func fetchMasterHDKeys(ns walletdb.ReadBucket) ([]byte, []byte, error) { bucket := ns.NestedReadBucket(mainBucketName) var masterHDPrivEnc, masterHDPubEnc []byte // First, we'll try to fetch the master private key. If this database // is watch only, or the master has been neutered, then this won't be // found on disk. key := bucket.Get(masterHDPrivName) if key != nil { masterHDPrivEnc = make([]byte, len(key)) copy(masterHDPrivEnc[:], key) } key = bucket.Get(masterHDPubName) if key != nil { masterHDPubEnc = make([]byte, len(key)) copy(masterHDPubEnc[:], key) } return masterHDPrivEnc, masterHDPubEnc, nil }
[ "func", "fetchMasterHDKeys", "(", "ns", "walletdb", ".", "ReadBucket", ")", "(", "[", "]", "byte", ",", "[", "]", "byte", ",", "error", ")", "{", "bucket", ":=", "ns", ".", "NestedReadBucket", "(", "mainBucketName", ")", "\n\n", "var", "masterHDPrivEnc", ",", "masterHDPubEnc", "[", "]", "byte", "\n\n", "// First, we'll try to fetch the master private key. If this database", "// is watch only, or the master has been neutered, then this won't be", "// found on disk.", "key", ":=", "bucket", ".", "Get", "(", "masterHDPrivName", ")", "\n", "if", "key", "!=", "nil", "{", "masterHDPrivEnc", "=", "make", "(", "[", "]", "byte", ",", "len", "(", "key", ")", ")", "\n", "copy", "(", "masterHDPrivEnc", "[", ":", "]", ",", "key", ")", "\n", "}", "\n\n", "key", "=", "bucket", ".", "Get", "(", "masterHDPubName", ")", "\n", "if", "key", "!=", "nil", "{", "masterHDPubEnc", "=", "make", "(", "[", "]", "byte", ",", "len", "(", "key", ")", ")", "\n", "copy", "(", "masterHDPubEnc", "[", ":", "]", ",", "key", ")", "\n", "}", "\n\n", "return", "masterHDPrivEnc", ",", "masterHDPubEnc", ",", "nil", "\n", "}" ]
// fetchMasterHDKeys attempts to fetch both the master HD private and public // keys from the database. If this is a watch only wallet, then it's possible // that the master private key isn't stored.
[ "fetchMasterHDKeys", "attempts", "to", "fetch", "both", "the", "master", "HD", "private", "and", "public", "keys", "from", "the", "database", ".", "If", "this", "is", "a", "watch", "only", "wallet", "then", "it", "s", "possible", "that", "the", "master", "private", "key", "isn", "t", "stored", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L567-L588
train
btcsuite/btcwallet
waddrmgr/db.go
fetchCryptoKeys
func fetchCryptoKeys(ns walletdb.ReadBucket) ([]byte, []byte, []byte, error) { bucket := ns.NestedReadBucket(mainBucketName) // Load the crypto public key parameters. Required. val := bucket.Get(cryptoPubKeyName) if val == nil { str := "required encrypted crypto public not stored in database" return nil, nil, nil, managerError(ErrDatabase, str, nil) } pubKey := make([]byte, len(val)) copy(pubKey, val) // Load the crypto private key parameters if they were stored. var privKey []byte val = bucket.Get(cryptoPrivKeyName) if val != nil { privKey = make([]byte, len(val)) copy(privKey, val) } // Load the crypto script key parameters if they were stored. var scriptKey []byte val = bucket.Get(cryptoScriptKeyName) if val != nil { scriptKey = make([]byte, len(val)) copy(scriptKey, val) } return pubKey, privKey, scriptKey, nil }
go
func fetchCryptoKeys(ns walletdb.ReadBucket) ([]byte, []byte, []byte, error) { bucket := ns.NestedReadBucket(mainBucketName) // Load the crypto public key parameters. Required. val := bucket.Get(cryptoPubKeyName) if val == nil { str := "required encrypted crypto public not stored in database" return nil, nil, nil, managerError(ErrDatabase, str, nil) } pubKey := make([]byte, len(val)) copy(pubKey, val) // Load the crypto private key parameters if they were stored. var privKey []byte val = bucket.Get(cryptoPrivKeyName) if val != nil { privKey = make([]byte, len(val)) copy(privKey, val) } // Load the crypto script key parameters if they were stored. var scriptKey []byte val = bucket.Get(cryptoScriptKeyName) if val != nil { scriptKey = make([]byte, len(val)) copy(scriptKey, val) } return pubKey, privKey, scriptKey, nil }
[ "func", "fetchCryptoKeys", "(", "ns", "walletdb", ".", "ReadBucket", ")", "(", "[", "]", "byte", ",", "[", "]", "byte", ",", "[", "]", "byte", ",", "error", ")", "{", "bucket", ":=", "ns", ".", "NestedReadBucket", "(", "mainBucketName", ")", "\n\n", "// Load the crypto public key parameters. Required.", "val", ":=", "bucket", ".", "Get", "(", "cryptoPubKeyName", ")", "\n", "if", "val", "==", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "nil", ",", "nil", ",", "nil", ",", "managerError", "(", "ErrDatabase", ",", "str", ",", "nil", ")", "\n", "}", "\n", "pubKey", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "val", ")", ")", "\n", "copy", "(", "pubKey", ",", "val", ")", "\n\n", "// Load the crypto private key parameters if they were stored.", "var", "privKey", "[", "]", "byte", "\n", "val", "=", "bucket", ".", "Get", "(", "cryptoPrivKeyName", ")", "\n", "if", "val", "!=", "nil", "{", "privKey", "=", "make", "(", "[", "]", "byte", ",", "len", "(", "val", ")", ")", "\n", "copy", "(", "privKey", ",", "val", ")", "\n", "}", "\n\n", "// Load the crypto script key parameters if they were stored.", "var", "scriptKey", "[", "]", "byte", "\n", "val", "=", "bucket", ".", "Get", "(", "cryptoScriptKeyName", ")", "\n", "if", "val", "!=", "nil", "{", "scriptKey", "=", "make", "(", "[", "]", "byte", ",", "len", "(", "val", ")", ")", "\n", "copy", "(", "scriptKey", ",", "val", ")", "\n", "}", "\n\n", "return", "pubKey", ",", "privKey", ",", "scriptKey", ",", "nil", "\n", "}" ]
// fetchCryptoKeys loads the encrypted crypto keys which are in turn used to // protect the extended keys, imported keys, and scripts. Any of the returned // values can be nil, but in practice only the crypto private and script keys // will be nil for a watching-only database.
[ "fetchCryptoKeys", "loads", "the", "encrypted", "crypto", "keys", "which", "are", "in", "turn", "used", "to", "protect", "the", "extended", "keys", "imported", "keys", "and", "scripts", ".", "Any", "of", "the", "returned", "values", "can", "be", "nil", "but", "in", "practice", "only", "the", "crypto", "private", "and", "script", "keys", "will", "be", "nil", "for", "a", "watching", "-", "only", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L594-L623
train
btcsuite/btcwallet
waddrmgr/db.go
putCryptoKeys
func putCryptoKeys(ns walletdb.ReadWriteBucket, pubKeyEncrypted, privKeyEncrypted, scriptKeyEncrypted []byte) error { bucket := ns.NestedReadWriteBucket(mainBucketName) if pubKeyEncrypted != nil { err := bucket.Put(cryptoPubKeyName, pubKeyEncrypted) if err != nil { str := "failed to store encrypted crypto public key" return managerError(ErrDatabase, str, err) } } if privKeyEncrypted != nil { err := bucket.Put(cryptoPrivKeyName, privKeyEncrypted) if err != nil { str := "failed to store encrypted crypto private key" return managerError(ErrDatabase, str, err) } } if scriptKeyEncrypted != nil { err := bucket.Put(cryptoScriptKeyName, scriptKeyEncrypted) if err != nil { str := "failed to store encrypted crypto script key" return managerError(ErrDatabase, str, err) } } return nil }
go
func putCryptoKeys(ns walletdb.ReadWriteBucket, pubKeyEncrypted, privKeyEncrypted, scriptKeyEncrypted []byte) error { bucket := ns.NestedReadWriteBucket(mainBucketName) if pubKeyEncrypted != nil { err := bucket.Put(cryptoPubKeyName, pubKeyEncrypted) if err != nil { str := "failed to store encrypted crypto public key" return managerError(ErrDatabase, str, err) } } if privKeyEncrypted != nil { err := bucket.Put(cryptoPrivKeyName, privKeyEncrypted) if err != nil { str := "failed to store encrypted crypto private key" return managerError(ErrDatabase, str, err) } } if scriptKeyEncrypted != nil { err := bucket.Put(cryptoScriptKeyName, scriptKeyEncrypted) if err != nil { str := "failed to store encrypted crypto script key" return managerError(ErrDatabase, str, err) } } return nil }
[ "func", "putCryptoKeys", "(", "ns", "walletdb", ".", "ReadWriteBucket", ",", "pubKeyEncrypted", ",", "privKeyEncrypted", ",", "scriptKeyEncrypted", "[", "]", "byte", ")", "error", "{", "bucket", ":=", "ns", ".", "NestedReadWriteBucket", "(", "mainBucketName", ")", "\n\n", "if", "pubKeyEncrypted", "!=", "nil", "{", "err", ":=", "bucket", ".", "Put", "(", "cryptoPubKeyName", ",", "pubKeyEncrypted", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "managerError", "(", "ErrDatabase", ",", "str", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "if", "privKeyEncrypted", "!=", "nil", "{", "err", ":=", "bucket", ".", "Put", "(", "cryptoPrivKeyName", ",", "privKeyEncrypted", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "managerError", "(", "ErrDatabase", ",", "str", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "if", "scriptKeyEncrypted", "!=", "nil", "{", "err", ":=", "bucket", ".", "Put", "(", "cryptoScriptKeyName", ",", "scriptKeyEncrypted", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "managerError", "(", "ErrDatabase", ",", "str", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// putCryptoKeys stores the encrypted crypto keys which are in turn used to // protect the extended and imported keys. Either parameter can be nil in // which case no value is written for the parameter.
[ "putCryptoKeys", "stores", "the", "encrypted", "crypto", "keys", "which", "are", "in", "turn", "used", "to", "protect", "the", "extended", "and", "imported", "keys", ".", "Either", "parameter", "can", "be", "nil", "in", "which", "case", "no", "value", "is", "written", "for", "the", "parameter", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L628-L658
train
btcsuite/btcwallet
waddrmgr/db.go
fetchWatchingOnly
func fetchWatchingOnly(ns walletdb.ReadBucket) (bool, error) { bucket := ns.NestedReadBucket(mainBucketName) buf := bucket.Get(watchingOnlyName) if len(buf) != 1 { str := "malformed watching-only flag stored in database" return false, managerError(ErrDatabase, str, nil) } return buf[0] != 0, nil }
go
func fetchWatchingOnly(ns walletdb.ReadBucket) (bool, error) { bucket := ns.NestedReadBucket(mainBucketName) buf := bucket.Get(watchingOnlyName) if len(buf) != 1 { str := "malformed watching-only flag stored in database" return false, managerError(ErrDatabase, str, nil) } return buf[0] != 0, nil }
[ "func", "fetchWatchingOnly", "(", "ns", "walletdb", ".", "ReadBucket", ")", "(", "bool", ",", "error", ")", "{", "bucket", ":=", "ns", ".", "NestedReadBucket", "(", "mainBucketName", ")", "\n\n", "buf", ":=", "bucket", ".", "Get", "(", "watchingOnlyName", ")", "\n", "if", "len", "(", "buf", ")", "!=", "1", "{", "str", ":=", "\"", "\"", "\n", "return", "false", ",", "managerError", "(", "ErrDatabase", ",", "str", ",", "nil", ")", "\n", "}", "\n\n", "return", "buf", "[", "0", "]", "!=", "0", ",", "nil", "\n", "}" ]
// fetchWatchingOnly loads the watching-only flag from the database.
[ "fetchWatchingOnly", "loads", "the", "watching", "-", "only", "flag", "from", "the", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L661-L671
train
btcsuite/btcwallet
waddrmgr/db.go
putWatchingOnly
func putWatchingOnly(ns walletdb.ReadWriteBucket, watchingOnly bool) error { bucket := ns.NestedReadWriteBucket(mainBucketName) var encoded byte if watchingOnly { encoded = 1 } if err := bucket.Put(watchingOnlyName, []byte{encoded}); err != nil { str := "failed to store watching only flag" return managerError(ErrDatabase, str, err) } return nil }
go
func putWatchingOnly(ns walletdb.ReadWriteBucket, watchingOnly bool) error { bucket := ns.NestedReadWriteBucket(mainBucketName) var encoded byte if watchingOnly { encoded = 1 } if err := bucket.Put(watchingOnlyName, []byte{encoded}); err != nil { str := "failed to store watching only flag" return managerError(ErrDatabase, str, err) } return nil }
[ "func", "putWatchingOnly", "(", "ns", "walletdb", ".", "ReadWriteBucket", ",", "watchingOnly", "bool", ")", "error", "{", "bucket", ":=", "ns", ".", "NestedReadWriteBucket", "(", "mainBucketName", ")", "\n\n", "var", "encoded", "byte", "\n", "if", "watchingOnly", "{", "encoded", "=", "1", "\n", "}", "\n\n", "if", "err", ":=", "bucket", ".", "Put", "(", "watchingOnlyName", ",", "[", "]", "byte", "{", "encoded", "}", ")", ";", "err", "!=", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "managerError", "(", "ErrDatabase", ",", "str", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// putWatchingOnly stores the watching-only flag to the database.
[ "putWatchingOnly", "stores", "the", "watching", "-", "only", "flag", "to", "the", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L674-L687
train
btcsuite/btcwallet
waddrmgr/db.go
deserializeAccountRow
func deserializeAccountRow(accountID []byte, serializedAccount []byte) (*dbAccountRow, error) { // The serialized account format is: // <acctType><rdlen><rawdata> // // 1 byte acctType + 4 bytes raw data length + raw data // Given the above, the length of the entry must be at a minimum // the constant value sizes. if len(serializedAccount) < 5 { str := fmt.Sprintf("malformed serialized account for key %x", accountID) return nil, managerError(ErrDatabase, str, nil) } row := dbAccountRow{} row.acctType = accountType(serializedAccount[0]) rdlen := binary.LittleEndian.Uint32(serializedAccount[1:5]) row.rawData = make([]byte, rdlen) copy(row.rawData, serializedAccount[5:5+rdlen]) return &row, nil }
go
func deserializeAccountRow(accountID []byte, serializedAccount []byte) (*dbAccountRow, error) { // The serialized account format is: // <acctType><rdlen><rawdata> // // 1 byte acctType + 4 bytes raw data length + raw data // Given the above, the length of the entry must be at a minimum // the constant value sizes. if len(serializedAccount) < 5 { str := fmt.Sprintf("malformed serialized account for key %x", accountID) return nil, managerError(ErrDatabase, str, nil) } row := dbAccountRow{} row.acctType = accountType(serializedAccount[0]) rdlen := binary.LittleEndian.Uint32(serializedAccount[1:5]) row.rawData = make([]byte, rdlen) copy(row.rawData, serializedAccount[5:5+rdlen]) return &row, nil }
[ "func", "deserializeAccountRow", "(", "accountID", "[", "]", "byte", ",", "serializedAccount", "[", "]", "byte", ")", "(", "*", "dbAccountRow", ",", "error", ")", "{", "// The serialized account format is:", "// <acctType><rdlen><rawdata>", "//", "// 1 byte acctType + 4 bytes raw data length + raw data", "// Given the above, the length of the entry must be at a minimum", "// the constant value sizes.", "if", "len", "(", "serializedAccount", ")", "<", "5", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "accountID", ")", "\n", "return", "nil", ",", "managerError", "(", "ErrDatabase", ",", "str", ",", "nil", ")", "\n", "}", "\n\n", "row", ":=", "dbAccountRow", "{", "}", "\n", "row", ".", "acctType", "=", "accountType", "(", "serializedAccount", "[", "0", "]", ")", "\n", "rdlen", ":=", "binary", ".", "LittleEndian", ".", "Uint32", "(", "serializedAccount", "[", "1", ":", "5", "]", ")", "\n", "row", ".", "rawData", "=", "make", "(", "[", "]", "byte", ",", "rdlen", ")", "\n", "copy", "(", "row", ".", "rawData", ",", "serializedAccount", "[", "5", ":", "5", "+", "rdlen", "]", ")", "\n\n", "return", "&", "row", ",", "nil", "\n", "}" ]
// deserializeAccountRow deserializes the passed serialized account information. // This is used as a common base for the various account types to deserialize // the common parts.
[ "deserializeAccountRow", "deserializes", "the", "passed", "serialized", "account", "information", ".", "This", "is", "used", "as", "a", "common", "base", "for", "the", "various", "account", "types", "to", "deserialize", "the", "common", "parts", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L692-L713
train
btcsuite/btcwallet
waddrmgr/db.go
serializeAccountRow
func serializeAccountRow(row *dbAccountRow) []byte { // The serialized account format is: // <acctType><rdlen><rawdata> // // 1 byte acctType + 4 bytes raw data length + raw data rdlen := len(row.rawData) buf := make([]byte, 5+rdlen) buf[0] = byte(row.acctType) binary.LittleEndian.PutUint32(buf[1:5], uint32(rdlen)) copy(buf[5:5+rdlen], row.rawData) return buf }
go
func serializeAccountRow(row *dbAccountRow) []byte { // The serialized account format is: // <acctType><rdlen><rawdata> // // 1 byte acctType + 4 bytes raw data length + raw data rdlen := len(row.rawData) buf := make([]byte, 5+rdlen) buf[0] = byte(row.acctType) binary.LittleEndian.PutUint32(buf[1:5], uint32(rdlen)) copy(buf[5:5+rdlen], row.rawData) return buf }
[ "func", "serializeAccountRow", "(", "row", "*", "dbAccountRow", ")", "[", "]", "byte", "{", "// The serialized account format is:", "// <acctType><rdlen><rawdata>", "//", "// 1 byte acctType + 4 bytes raw data length + raw data", "rdlen", ":=", "len", "(", "row", ".", "rawData", ")", "\n", "buf", ":=", "make", "(", "[", "]", "byte", ",", "5", "+", "rdlen", ")", "\n", "buf", "[", "0", "]", "=", "byte", "(", "row", ".", "acctType", ")", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "buf", "[", "1", ":", "5", "]", ",", "uint32", "(", "rdlen", ")", ")", "\n", "copy", "(", "buf", "[", "5", ":", "5", "+", "rdlen", "]", ",", "row", ".", "rawData", ")", "\n", "return", "buf", "\n", "}" ]
// serializeAccountRow returns the serialization of the passed account row.
[ "serializeAccountRow", "returns", "the", "serialization", "of", "the", "passed", "account", "row", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L716-L727
train
btcsuite/btcwallet
waddrmgr/db.go
deserializeDefaultAccountRow
func deserializeDefaultAccountRow(accountID []byte, row *dbAccountRow) (*dbDefaultAccountRow, error) { // The serialized BIP0044 account raw data format is: // <encpubkeylen><encpubkey><encprivkeylen><encprivkey><nextextidx> // <nextintidx><namelen><name> // // 4 bytes encrypted pubkey len + encrypted pubkey + 4 bytes encrypted // privkey len + encrypted privkey + 4 bytes next external index + // 4 bytes next internal index + 4 bytes name len + name // Given the above, the length of the entry must be at a minimum // the constant value sizes. if len(row.rawData) < 20 { str := fmt.Sprintf("malformed serialized bip0044 account for "+ "key %x", accountID) return nil, managerError(ErrDatabase, str, nil) } retRow := dbDefaultAccountRow{ dbAccountRow: *row, } pubLen := binary.LittleEndian.Uint32(row.rawData[0:4]) retRow.pubKeyEncrypted = make([]byte, pubLen) copy(retRow.pubKeyEncrypted, row.rawData[4:4+pubLen]) offset := 4 + pubLen privLen := binary.LittleEndian.Uint32(row.rawData[offset : offset+4]) offset += 4 retRow.privKeyEncrypted = make([]byte, privLen) copy(retRow.privKeyEncrypted, row.rawData[offset:offset+privLen]) offset += privLen retRow.nextExternalIndex = binary.LittleEndian.Uint32(row.rawData[offset : offset+4]) offset += 4 retRow.nextInternalIndex = binary.LittleEndian.Uint32(row.rawData[offset : offset+4]) offset += 4 nameLen := binary.LittleEndian.Uint32(row.rawData[offset : offset+4]) offset += 4 retRow.name = string(row.rawData[offset : offset+nameLen]) return &retRow, nil }
go
func deserializeDefaultAccountRow(accountID []byte, row *dbAccountRow) (*dbDefaultAccountRow, error) { // The serialized BIP0044 account raw data format is: // <encpubkeylen><encpubkey><encprivkeylen><encprivkey><nextextidx> // <nextintidx><namelen><name> // // 4 bytes encrypted pubkey len + encrypted pubkey + 4 bytes encrypted // privkey len + encrypted privkey + 4 bytes next external index + // 4 bytes next internal index + 4 bytes name len + name // Given the above, the length of the entry must be at a minimum // the constant value sizes. if len(row.rawData) < 20 { str := fmt.Sprintf("malformed serialized bip0044 account for "+ "key %x", accountID) return nil, managerError(ErrDatabase, str, nil) } retRow := dbDefaultAccountRow{ dbAccountRow: *row, } pubLen := binary.LittleEndian.Uint32(row.rawData[0:4]) retRow.pubKeyEncrypted = make([]byte, pubLen) copy(retRow.pubKeyEncrypted, row.rawData[4:4+pubLen]) offset := 4 + pubLen privLen := binary.LittleEndian.Uint32(row.rawData[offset : offset+4]) offset += 4 retRow.privKeyEncrypted = make([]byte, privLen) copy(retRow.privKeyEncrypted, row.rawData[offset:offset+privLen]) offset += privLen retRow.nextExternalIndex = binary.LittleEndian.Uint32(row.rawData[offset : offset+4]) offset += 4 retRow.nextInternalIndex = binary.LittleEndian.Uint32(row.rawData[offset : offset+4]) offset += 4 nameLen := binary.LittleEndian.Uint32(row.rawData[offset : offset+4]) offset += 4 retRow.name = string(row.rawData[offset : offset+nameLen]) return &retRow, nil }
[ "func", "deserializeDefaultAccountRow", "(", "accountID", "[", "]", "byte", ",", "row", "*", "dbAccountRow", ")", "(", "*", "dbDefaultAccountRow", ",", "error", ")", "{", "// The serialized BIP0044 account raw data format is:", "// <encpubkeylen><encpubkey><encprivkeylen><encprivkey><nextextidx>", "// <nextintidx><namelen><name>", "//", "// 4 bytes encrypted pubkey len + encrypted pubkey + 4 bytes encrypted", "// privkey len + encrypted privkey + 4 bytes next external index +", "// 4 bytes next internal index + 4 bytes name len + name", "// Given the above, the length of the entry must be at a minimum", "// the constant value sizes.", "if", "len", "(", "row", ".", "rawData", ")", "<", "20", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "accountID", ")", "\n", "return", "nil", ",", "managerError", "(", "ErrDatabase", ",", "str", ",", "nil", ")", "\n", "}", "\n\n", "retRow", ":=", "dbDefaultAccountRow", "{", "dbAccountRow", ":", "*", "row", ",", "}", "\n\n", "pubLen", ":=", "binary", ".", "LittleEndian", ".", "Uint32", "(", "row", ".", "rawData", "[", "0", ":", "4", "]", ")", "\n", "retRow", ".", "pubKeyEncrypted", "=", "make", "(", "[", "]", "byte", ",", "pubLen", ")", "\n", "copy", "(", "retRow", ".", "pubKeyEncrypted", ",", "row", ".", "rawData", "[", "4", ":", "4", "+", "pubLen", "]", ")", "\n", "offset", ":=", "4", "+", "pubLen", "\n", "privLen", ":=", "binary", ".", "LittleEndian", ".", "Uint32", "(", "row", ".", "rawData", "[", "offset", ":", "offset", "+", "4", "]", ")", "\n", "offset", "+=", "4", "\n", "retRow", ".", "privKeyEncrypted", "=", "make", "(", "[", "]", "byte", ",", "privLen", ")", "\n", "copy", "(", "retRow", ".", "privKeyEncrypted", ",", "row", ".", "rawData", "[", "offset", ":", "offset", "+", "privLen", "]", ")", "\n", "offset", "+=", "privLen", "\n", "retRow", ".", "nextExternalIndex", "=", "binary", ".", "LittleEndian", ".", "Uint32", "(", "row", ".", "rawData", "[", "offset", ":", "offset", "+", "4", "]", ")", "\n", "offset", "+=", "4", "\n", "retRow", ".", "nextInternalIndex", "=", "binary", ".", "LittleEndian", ".", "Uint32", "(", "row", ".", "rawData", "[", "offset", ":", "offset", "+", "4", "]", ")", "\n", "offset", "+=", "4", "\n", "nameLen", ":=", "binary", ".", "LittleEndian", ".", "Uint32", "(", "row", ".", "rawData", "[", "offset", ":", "offset", "+", "4", "]", ")", "\n", "offset", "+=", "4", "\n", "retRow", ".", "name", "=", "string", "(", "row", ".", "rawData", "[", "offset", ":", "offset", "+", "nameLen", "]", ")", "\n\n", "return", "&", "retRow", ",", "nil", "\n", "}" ]
// deserializeDefaultAccountRow deserializes the raw data from the passed // account row as a BIP0044-like account.
[ "deserializeDefaultAccountRow", "deserializes", "the", "raw", "data", "from", "the", "passed", "account", "row", "as", "a", "BIP0044", "-", "like", "account", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L731-L770
train
btcsuite/btcwallet
waddrmgr/db.go
serializeDefaultAccountRow
func serializeDefaultAccountRow(encryptedPubKey, encryptedPrivKey []byte, nextExternalIndex, nextInternalIndex uint32, name string) []byte { // The serialized BIP0044 account raw data format is: // <encpubkeylen><encpubkey><encprivkeylen><encprivkey><nextextidx> // <nextintidx><namelen><name> // // 4 bytes encrypted pubkey len + encrypted pubkey + 4 bytes encrypted // privkey len + encrypted privkey + 4 bytes next external index + // 4 bytes next internal index + 4 bytes name len + name pubLen := uint32(len(encryptedPubKey)) privLen := uint32(len(encryptedPrivKey)) nameLen := uint32(len(name)) rawData := make([]byte, 20+pubLen+privLen+nameLen) 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) offset += privLen binary.LittleEndian.PutUint32(rawData[offset:offset+4], nextExternalIndex) offset += 4 binary.LittleEndian.PutUint32(rawData[offset:offset+4], nextInternalIndex) offset += 4 binary.LittleEndian.PutUint32(rawData[offset:offset+4], nameLen) offset += 4 copy(rawData[offset:offset+nameLen], name) return rawData }
go
func serializeDefaultAccountRow(encryptedPubKey, encryptedPrivKey []byte, nextExternalIndex, nextInternalIndex uint32, name string) []byte { // The serialized BIP0044 account raw data format is: // <encpubkeylen><encpubkey><encprivkeylen><encprivkey><nextextidx> // <nextintidx><namelen><name> // // 4 bytes encrypted pubkey len + encrypted pubkey + 4 bytes encrypted // privkey len + encrypted privkey + 4 bytes next external index + // 4 bytes next internal index + 4 bytes name len + name pubLen := uint32(len(encryptedPubKey)) privLen := uint32(len(encryptedPrivKey)) nameLen := uint32(len(name)) rawData := make([]byte, 20+pubLen+privLen+nameLen) 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) offset += privLen binary.LittleEndian.PutUint32(rawData[offset:offset+4], nextExternalIndex) offset += 4 binary.LittleEndian.PutUint32(rawData[offset:offset+4], nextInternalIndex) offset += 4 binary.LittleEndian.PutUint32(rawData[offset:offset+4], nameLen) offset += 4 copy(rawData[offset:offset+nameLen], name) return rawData }
[ "func", "serializeDefaultAccountRow", "(", "encryptedPubKey", ",", "encryptedPrivKey", "[", "]", "byte", ",", "nextExternalIndex", ",", "nextInternalIndex", "uint32", ",", "name", "string", ")", "[", "]", "byte", "{", "// The serialized BIP0044 account raw data format is:", "// <encpubkeylen><encpubkey><encprivkeylen><encprivkey><nextextidx>", "// <nextintidx><namelen><name>", "//", "// 4 bytes encrypted pubkey len + encrypted pubkey + 4 bytes encrypted", "// privkey len + encrypted privkey + 4 bytes next external index +", "// 4 bytes next internal index + 4 bytes name len + name", "pubLen", ":=", "uint32", "(", "len", "(", "encryptedPubKey", ")", ")", "\n", "privLen", ":=", "uint32", "(", "len", "(", "encryptedPrivKey", ")", ")", "\n", "nameLen", ":=", "uint32", "(", "len", "(", "name", ")", ")", "\n", "rawData", ":=", "make", "(", "[", "]", "byte", ",", "20", "+", "pubLen", "+", "privLen", "+", "nameLen", ")", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "rawData", "[", "0", ":", "4", "]", ",", "pubLen", ")", "\n", "copy", "(", "rawData", "[", "4", ":", "4", "+", "pubLen", "]", ",", "encryptedPubKey", ")", "\n", "offset", ":=", "4", "+", "pubLen", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "rawData", "[", "offset", ":", "offset", "+", "4", "]", ",", "privLen", ")", "\n", "offset", "+=", "4", "\n", "copy", "(", "rawData", "[", "offset", ":", "offset", "+", "privLen", "]", ",", "encryptedPrivKey", ")", "\n", "offset", "+=", "privLen", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "rawData", "[", "offset", ":", "offset", "+", "4", "]", ",", "nextExternalIndex", ")", "\n", "offset", "+=", "4", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "rawData", "[", "offset", ":", "offset", "+", "4", "]", ",", "nextInternalIndex", ")", "\n", "offset", "+=", "4", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "rawData", "[", "offset", ":", "offset", "+", "4", "]", ",", "nameLen", ")", "\n", "offset", "+=", "4", "\n", "copy", "(", "rawData", "[", "offset", ":", "offset", "+", "nameLen", "]", ",", "name", ")", "\n", "return", "rawData", "\n", "}" ]
// serializeDefaultAccountRow returns the serialization of the raw data field // for a BIP0044-like account.
[ "serializeDefaultAccountRow", "returns", "the", "serialization", "of", "the", "raw", "data", "field", "for", "a", "BIP0044", "-", "like", "account", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L774-L803
train
btcsuite/btcwallet
waddrmgr/db.go
forEachKeyScope
func forEachKeyScope(ns walletdb.ReadBucket, fn func(KeyScope) error) error { bucket := ns.NestedReadBucket(scopeBucketName) return bucket.ForEach(func(k, v []byte) error { // skip non-bucket if len(k) != 8 { return nil } scope := KeyScope{ Purpose: binary.LittleEndian.Uint32(k[:]), Coin: binary.LittleEndian.Uint32(k[4:]), } return fn(scope) }) }
go
func forEachKeyScope(ns walletdb.ReadBucket, fn func(KeyScope) error) error { bucket := ns.NestedReadBucket(scopeBucketName) return bucket.ForEach(func(k, v []byte) error { // skip non-bucket if len(k) != 8 { return nil } scope := KeyScope{ Purpose: binary.LittleEndian.Uint32(k[:]), Coin: binary.LittleEndian.Uint32(k[4:]), } return fn(scope) }) }
[ "func", "forEachKeyScope", "(", "ns", "walletdb", ".", "ReadBucket", ",", "fn", "func", "(", "KeyScope", ")", "error", ")", "error", "{", "bucket", ":=", "ns", ".", "NestedReadBucket", "(", "scopeBucketName", ")", "\n\n", "return", "bucket", ".", "ForEach", "(", "func", "(", "k", ",", "v", "[", "]", "byte", ")", "error", "{", "// skip non-bucket", "if", "len", "(", "k", ")", "!=", "8", "{", "return", "nil", "\n", "}", "\n\n", "scope", ":=", "KeyScope", "{", "Purpose", ":", "binary", ".", "LittleEndian", ".", "Uint32", "(", "k", "[", ":", "]", ")", ",", "Coin", ":", "binary", ".", "LittleEndian", ".", "Uint32", "(", "k", "[", "4", ":", "]", ")", ",", "}", "\n\n", "return", "fn", "(", "scope", ")", "\n", "}", ")", "\n", "}" ]
// forEachKeyScope calls the given function for each known manager scope // within the set of scopes known by the root manager.
[ "forEachKeyScope", "calls", "the", "given", "function", "for", "each", "known", "manager", "scope", "within", "the", "set", "of", "scopes", "known", "by", "the", "root", "manager", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L807-L823
train
btcsuite/btcwallet
waddrmgr/db.go
forEachAccount
func forEachAccount(ns walletdb.ReadBucket, scope *KeyScope, fn func(account uint32) error) error { scopedBucket, err := fetchReadScopeBucket(ns, scope) if err != nil { return err } acctBucket := scopedBucket.NestedReadBucket(acctBucketName) return acctBucket.ForEach(func(k, v []byte) error { // Skip buckets. if v == nil { return nil } return fn(binary.LittleEndian.Uint32(k)) }) }
go
func forEachAccount(ns walletdb.ReadBucket, scope *KeyScope, fn func(account uint32) error) error { scopedBucket, err := fetchReadScopeBucket(ns, scope) if err != nil { return err } acctBucket := scopedBucket.NestedReadBucket(acctBucketName) return acctBucket.ForEach(func(k, v []byte) error { // Skip buckets. if v == nil { return nil } return fn(binary.LittleEndian.Uint32(k)) }) }
[ "func", "forEachAccount", "(", "ns", "walletdb", ".", "ReadBucket", ",", "scope", "*", "KeyScope", ",", "fn", "func", "(", "account", "uint32", ")", "error", ")", "error", "{", "scopedBucket", ",", "err", ":=", "fetchReadScopeBucket", "(", "ns", ",", "scope", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "acctBucket", ":=", "scopedBucket", ".", "NestedReadBucket", "(", "acctBucketName", ")", "\n", "return", "acctBucket", ".", "ForEach", "(", "func", "(", "k", ",", "v", "[", "]", "byte", ")", "error", "{", "// Skip buckets.", "if", "v", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "fn", "(", "binary", ".", "LittleEndian", ".", "Uint32", "(", "k", ")", ")", "\n", "}", ")", "\n", "}" ]
// forEachAccount calls the given function with each account stored in the // manager, breaking early on error.
[ "forEachAccount", "calls", "the", "given", "function", "with", "each", "account", "stored", "in", "the", "manager", "breaking", "early", "on", "error", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L827-L843
train
btcsuite/btcwallet
waddrmgr/db.go
fetchLastAccount
func fetchLastAccount(ns walletdb.ReadBucket, scope *KeyScope) (uint32, error) { scopedBucket, err := fetchReadScopeBucket(ns, scope) if err != nil { return 0, err } metaBucket := scopedBucket.NestedReadBucket(metaBucketName) val := metaBucket.Get(lastAccountName) if len(val) != 4 { str := fmt.Sprintf("malformed metadata '%s' stored in database", lastAccountName) return 0, managerError(ErrDatabase, str, nil) } account := binary.LittleEndian.Uint32(val[0:4]) return account, nil }
go
func fetchLastAccount(ns walletdb.ReadBucket, scope *KeyScope) (uint32, error) { scopedBucket, err := fetchReadScopeBucket(ns, scope) if err != nil { return 0, err } metaBucket := scopedBucket.NestedReadBucket(metaBucketName) val := metaBucket.Get(lastAccountName) if len(val) != 4 { str := fmt.Sprintf("malformed metadata '%s' stored in database", lastAccountName) return 0, managerError(ErrDatabase, str, nil) } account := binary.LittleEndian.Uint32(val[0:4]) return account, nil }
[ "func", "fetchLastAccount", "(", "ns", "walletdb", ".", "ReadBucket", ",", "scope", "*", "KeyScope", ")", "(", "uint32", ",", "error", ")", "{", "scopedBucket", ",", "err", ":=", "fetchReadScopeBucket", "(", "ns", ",", "scope", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "metaBucket", ":=", "scopedBucket", ".", "NestedReadBucket", "(", "metaBucketName", ")", "\n\n", "val", ":=", "metaBucket", ".", "Get", "(", "lastAccountName", ")", "\n", "if", "len", "(", "val", ")", "!=", "4", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "lastAccountName", ")", "\n", "return", "0", ",", "managerError", "(", "ErrDatabase", ",", "str", ",", "nil", ")", "\n", "}", "\n\n", "account", ":=", "binary", ".", "LittleEndian", ".", "Uint32", "(", "val", "[", "0", ":", "4", "]", ")", "\n", "return", "account", ",", "nil", "\n", "}" ]
// fetchLastAccount retrieves the last account from the database.
[ "fetchLastAccount", "retrieves", "the", "last", "account", "from", "the", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L846-L863
train
btcsuite/btcwallet
waddrmgr/db.go
fetchAccountName
func fetchAccountName(ns walletdb.ReadBucket, scope *KeyScope, account uint32) (string, error) { scopedBucket, err := fetchReadScopeBucket(ns, scope) if err != nil { return "", err } acctIDxBucket := scopedBucket.NestedReadBucket(acctIDIdxBucketName) val := acctIDxBucket.Get(uint32ToBytes(account)) if val == nil { str := fmt.Sprintf("account %d not found", account) return "", managerError(ErrAccountNotFound, str, nil) } offset := uint32(0) nameLen := binary.LittleEndian.Uint32(val[offset : offset+4]) offset += 4 acctName := string(val[offset : offset+nameLen]) return acctName, nil }
go
func fetchAccountName(ns walletdb.ReadBucket, scope *KeyScope, account uint32) (string, error) { scopedBucket, err := fetchReadScopeBucket(ns, scope) if err != nil { return "", err } acctIDxBucket := scopedBucket.NestedReadBucket(acctIDIdxBucketName) val := acctIDxBucket.Get(uint32ToBytes(account)) if val == nil { str := fmt.Sprintf("account %d not found", account) return "", managerError(ErrAccountNotFound, str, nil) } offset := uint32(0) nameLen := binary.LittleEndian.Uint32(val[offset : offset+4]) offset += 4 acctName := string(val[offset : offset+nameLen]) return acctName, nil }
[ "func", "fetchAccountName", "(", "ns", "walletdb", ".", "ReadBucket", ",", "scope", "*", "KeyScope", ",", "account", "uint32", ")", "(", "string", ",", "error", ")", "{", "scopedBucket", ",", "err", ":=", "fetchReadScopeBucket", "(", "ns", ",", "scope", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "acctIDxBucket", ":=", "scopedBucket", ".", "NestedReadBucket", "(", "acctIDIdxBucketName", ")", "\n\n", "val", ":=", "acctIDxBucket", ".", "Get", "(", "uint32ToBytes", "(", "account", ")", ")", "\n", "if", "val", "==", "nil", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "account", ")", "\n", "return", "\"", "\"", ",", "managerError", "(", "ErrAccountNotFound", ",", "str", ",", "nil", ")", "\n", "}", "\n\n", "offset", ":=", "uint32", "(", "0", ")", "\n", "nameLen", ":=", "binary", ".", "LittleEndian", ".", "Uint32", "(", "val", "[", "offset", ":", "offset", "+", "4", "]", ")", "\n", "offset", "+=", "4", "\n", "acctName", ":=", "string", "(", "val", "[", "offset", ":", "offset", "+", "nameLen", "]", ")", "\n\n", "return", "acctName", ",", "nil", "\n", "}" ]
// fetchAccountName retrieves the account name given an account number from the // database.
[ "fetchAccountName", "retrieves", "the", "account", "name", "given", "an", "account", "number", "from", "the", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L867-L889
train
btcsuite/btcwallet
waddrmgr/db.go
fetchAccountByName
func fetchAccountByName(ns walletdb.ReadBucket, scope *KeyScope, name string) (uint32, error) { scopedBucket, err := fetchReadScopeBucket(ns, scope) if err != nil { return 0, err } idxBucket := scopedBucket.NestedReadBucket(acctNameIdxBucketName) val := idxBucket.Get(stringToBytes(name)) if val == nil { str := fmt.Sprintf("account name '%s' not found", name) return 0, managerError(ErrAccountNotFound, str, nil) } return binary.LittleEndian.Uint32(val), nil }
go
func fetchAccountByName(ns walletdb.ReadBucket, scope *KeyScope, name string) (uint32, error) { scopedBucket, err := fetchReadScopeBucket(ns, scope) if err != nil { return 0, err } idxBucket := scopedBucket.NestedReadBucket(acctNameIdxBucketName) val := idxBucket.Get(stringToBytes(name)) if val == nil { str := fmt.Sprintf("account name '%s' not found", name) return 0, managerError(ErrAccountNotFound, str, nil) } return binary.LittleEndian.Uint32(val), nil }
[ "func", "fetchAccountByName", "(", "ns", "walletdb", ".", "ReadBucket", ",", "scope", "*", "KeyScope", ",", "name", "string", ")", "(", "uint32", ",", "error", ")", "{", "scopedBucket", ",", "err", ":=", "fetchReadScopeBucket", "(", "ns", ",", "scope", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "idxBucket", ":=", "scopedBucket", ".", "NestedReadBucket", "(", "acctNameIdxBucketName", ")", "\n\n", "val", ":=", "idxBucket", ".", "Get", "(", "stringToBytes", "(", "name", ")", ")", "\n", "if", "val", "==", "nil", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ")", "\n", "return", "0", ",", "managerError", "(", "ErrAccountNotFound", ",", "str", ",", "nil", ")", "\n", "}", "\n\n", "return", "binary", ".", "LittleEndian", ".", "Uint32", "(", "val", ")", ",", "nil", "\n", "}" ]
// fetchAccountByName retrieves the account number given an account name from // the database.
[ "fetchAccountByName", "retrieves", "the", "account", "number", "given", "an", "account", "name", "from", "the", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L893-L910
train
btcsuite/btcwallet
waddrmgr/db.go
fetchAccountInfo
func fetchAccountInfo(ns walletdb.ReadBucket, scope *KeyScope, account uint32) (interface{}, error) { scopedBucket, err := fetchReadScopeBucket(ns, scope) if err != nil { return nil, err } acctBucket := scopedBucket.NestedReadBucket(acctBucketName) accountID := uint32ToBytes(account) serializedRow := acctBucket.Get(accountID) if serializedRow == nil { str := fmt.Sprintf("account %d not found", account) return nil, managerError(ErrAccountNotFound, str, nil) } row, err := deserializeAccountRow(accountID, serializedRow) if err != nil { return nil, err } switch row.acctType { case accountDefault: return deserializeDefaultAccountRow(accountID, row) } str := fmt.Sprintf("unsupported account type '%d'", row.acctType) return nil, managerError(ErrDatabase, str, nil) }
go
func fetchAccountInfo(ns walletdb.ReadBucket, scope *KeyScope, account uint32) (interface{}, error) { scopedBucket, err := fetchReadScopeBucket(ns, scope) if err != nil { return nil, err } acctBucket := scopedBucket.NestedReadBucket(acctBucketName) accountID := uint32ToBytes(account) serializedRow := acctBucket.Get(accountID) if serializedRow == nil { str := fmt.Sprintf("account %d not found", account) return nil, managerError(ErrAccountNotFound, str, nil) } row, err := deserializeAccountRow(accountID, serializedRow) if err != nil { return nil, err } switch row.acctType { case accountDefault: return deserializeDefaultAccountRow(accountID, row) } str := fmt.Sprintf("unsupported account type '%d'", row.acctType) return nil, managerError(ErrDatabase, str, nil) }
[ "func", "fetchAccountInfo", "(", "ns", "walletdb", ".", "ReadBucket", ",", "scope", "*", "KeyScope", ",", "account", "uint32", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "scopedBucket", ",", "err", ":=", "fetchReadScopeBucket", "(", "ns", ",", "scope", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "acctBucket", ":=", "scopedBucket", ".", "NestedReadBucket", "(", "acctBucketName", ")", "\n\n", "accountID", ":=", "uint32ToBytes", "(", "account", ")", "\n", "serializedRow", ":=", "acctBucket", ".", "Get", "(", "accountID", ")", "\n", "if", "serializedRow", "==", "nil", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "account", ")", "\n", "return", "nil", ",", "managerError", "(", "ErrAccountNotFound", ",", "str", ",", "nil", ")", "\n", "}", "\n\n", "row", ",", "err", ":=", "deserializeAccountRow", "(", "accountID", ",", "serializedRow", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "switch", "row", ".", "acctType", "{", "case", "accountDefault", ":", "return", "deserializeDefaultAccountRow", "(", "accountID", ",", "row", ")", "\n", "}", "\n\n", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "row", ".", "acctType", ")", "\n", "return", "nil", ",", "managerError", "(", "ErrDatabase", ",", "str", ",", "nil", ")", "\n", "}" ]
// fetchAccountInfo loads information about the passed account from the // database.
[ "fetchAccountInfo", "loads", "information", "about", "the", "passed", "account", "from", "the", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L914-L943
train
btcsuite/btcwallet
waddrmgr/db.go
deleteAccountNameIndex
func deleteAccountNameIndex(ns walletdb.ReadWriteBucket, scope *KeyScope, name string) error { scopedBucket, err := fetchWriteScopeBucket(ns, scope) if err != nil { return err } bucket := scopedBucket.NestedReadWriteBucket(acctNameIdxBucketName) // Delete the account name key err = bucket.Delete(stringToBytes(name)) if err != nil { str := fmt.Sprintf("failed to delete account name index key %s", name) return managerError(ErrDatabase, str, err) } return nil }
go
func deleteAccountNameIndex(ns walletdb.ReadWriteBucket, scope *KeyScope, name string) error { scopedBucket, err := fetchWriteScopeBucket(ns, scope) if err != nil { return err } bucket := scopedBucket.NestedReadWriteBucket(acctNameIdxBucketName) // Delete the account name key err = bucket.Delete(stringToBytes(name)) if err != nil { str := fmt.Sprintf("failed to delete account name index key %s", name) return managerError(ErrDatabase, str, err) } return nil }
[ "func", "deleteAccountNameIndex", "(", "ns", "walletdb", ".", "ReadWriteBucket", ",", "scope", "*", "KeyScope", ",", "name", "string", ")", "error", "{", "scopedBucket", ",", "err", ":=", "fetchWriteScopeBucket", "(", "ns", ",", "scope", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "bucket", ":=", "scopedBucket", ".", "NestedReadWriteBucket", "(", "acctNameIdxBucketName", ")", "\n\n", "// Delete the account name key", "err", "=", "bucket", ".", "Delete", "(", "stringToBytes", "(", "name", ")", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ")", "\n", "return", "managerError", "(", "ErrDatabase", ",", "str", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// deleteAccountNameIndex deletes the given key from the account name index of the database.
[ "deleteAccountNameIndex", "deletes", "the", "given", "key", "from", "the", "account", "name", "index", "of", "the", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L946-L963
train
btcsuite/btcwallet
waddrmgr/db.go
deleteAccountIDIndex
func deleteAccountIDIndex(ns walletdb.ReadWriteBucket, scope *KeyScope, account uint32) error { scopedBucket, err := fetchWriteScopeBucket(ns, scope) if err != nil { return err } bucket := scopedBucket.NestedReadWriteBucket(acctIDIdxBucketName) // Delete the account id key err = bucket.Delete(uint32ToBytes(account)) if err != nil { str := fmt.Sprintf("failed to delete account id index key %d", account) return managerError(ErrDatabase, str, err) } return nil }
go
func deleteAccountIDIndex(ns walletdb.ReadWriteBucket, scope *KeyScope, account uint32) error { scopedBucket, err := fetchWriteScopeBucket(ns, scope) if err != nil { return err } bucket := scopedBucket.NestedReadWriteBucket(acctIDIdxBucketName) // Delete the account id key err = bucket.Delete(uint32ToBytes(account)) if err != nil { str := fmt.Sprintf("failed to delete account id index key %d", account) return managerError(ErrDatabase, str, err) } return nil }
[ "func", "deleteAccountIDIndex", "(", "ns", "walletdb", ".", "ReadWriteBucket", ",", "scope", "*", "KeyScope", ",", "account", "uint32", ")", "error", "{", "scopedBucket", ",", "err", ":=", "fetchWriteScopeBucket", "(", "ns", ",", "scope", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "bucket", ":=", "scopedBucket", ".", "NestedReadWriteBucket", "(", "acctIDIdxBucketName", ")", "\n\n", "// Delete the account id key", "err", "=", "bucket", ".", "Delete", "(", "uint32ToBytes", "(", "account", ")", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "account", ")", "\n", "return", "managerError", "(", "ErrDatabase", ",", "str", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// deleteAccounIdIndex deletes the given key from the account id index of the database.
[ "deleteAccounIdIndex", "deletes", "the", "given", "key", "from", "the", "account", "id", "index", "of", "the", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L966-L983
train
btcsuite/btcwallet
waddrmgr/db.go
putAccountNameIndex
func putAccountNameIndex(ns walletdb.ReadWriteBucket, scope *KeyScope, account uint32, name string) error { scopedBucket, err := fetchWriteScopeBucket(ns, scope) if err != nil { return err } bucket := scopedBucket.NestedReadWriteBucket(acctNameIdxBucketName) // Write the account number keyed by the account name. err = bucket.Put(stringToBytes(name), uint32ToBytes(account)) if err != nil { str := fmt.Sprintf("failed to store account name index key %s", name) return managerError(ErrDatabase, str, err) } return nil }
go
func putAccountNameIndex(ns walletdb.ReadWriteBucket, scope *KeyScope, account uint32, name string) error { scopedBucket, err := fetchWriteScopeBucket(ns, scope) if err != nil { return err } bucket := scopedBucket.NestedReadWriteBucket(acctNameIdxBucketName) // Write the account number keyed by the account name. err = bucket.Put(stringToBytes(name), uint32ToBytes(account)) if err != nil { str := fmt.Sprintf("failed to store account name index key %s", name) return managerError(ErrDatabase, str, err) } return nil }
[ "func", "putAccountNameIndex", "(", "ns", "walletdb", ".", "ReadWriteBucket", ",", "scope", "*", "KeyScope", ",", "account", "uint32", ",", "name", "string", ")", "error", "{", "scopedBucket", ",", "err", ":=", "fetchWriteScopeBucket", "(", "ns", ",", "scope", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "bucket", ":=", "scopedBucket", ".", "NestedReadWriteBucket", "(", "acctNameIdxBucketName", ")", "\n\n", "// Write the account number keyed by the account name.", "err", "=", "bucket", ".", "Put", "(", "stringToBytes", "(", "name", ")", ",", "uint32ToBytes", "(", "account", ")", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ")", "\n", "return", "managerError", "(", "ErrDatabase", ",", "str", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// putAccountNameIndex stores the given key to the account name index of the // database.
[ "putAccountNameIndex", "stores", "the", "given", "key", "to", "the", "account", "name", "index", "of", "the", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L987-L1004
train
btcsuite/btcwallet
waddrmgr/db.go
putAddrAccountIndex
func putAddrAccountIndex(ns walletdb.ReadWriteBucket, scope *KeyScope, account uint32, addrHash []byte) error { scopedBucket, err := fetchWriteScopeBucket(ns, scope) if err != nil { return err } bucket := scopedBucket.NestedReadWriteBucket(addrAcctIdxBucketName) // Write account keyed by address hash err = bucket.Put(addrHash, uint32ToBytes(account)) if err != nil { return nil } bucket, err = bucket.CreateBucketIfNotExists(uint32ToBytes(account)) if err != nil { return err } // In account bucket, write a null value keyed by the address hash err = bucket.Put(addrHash, nullVal) if err != nil { str := fmt.Sprintf("failed to store address account index key %s", addrHash) return managerError(ErrDatabase, str, err) } return nil }
go
func putAddrAccountIndex(ns walletdb.ReadWriteBucket, scope *KeyScope, account uint32, addrHash []byte) error { scopedBucket, err := fetchWriteScopeBucket(ns, scope) if err != nil { return err } bucket := scopedBucket.NestedReadWriteBucket(addrAcctIdxBucketName) // Write account keyed by address hash err = bucket.Put(addrHash, uint32ToBytes(account)) if err != nil { return nil } bucket, err = bucket.CreateBucketIfNotExists(uint32ToBytes(account)) if err != nil { return err } // In account bucket, write a null value keyed by the address hash err = bucket.Put(addrHash, nullVal) if err != nil { str := fmt.Sprintf("failed to store address account index key %s", addrHash) return managerError(ErrDatabase, str, err) } return nil }
[ "func", "putAddrAccountIndex", "(", "ns", "walletdb", ".", "ReadWriteBucket", ",", "scope", "*", "KeyScope", ",", "account", "uint32", ",", "addrHash", "[", "]", "byte", ")", "error", "{", "scopedBucket", ",", "err", ":=", "fetchWriteScopeBucket", "(", "ns", ",", "scope", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "bucket", ":=", "scopedBucket", ".", "NestedReadWriteBucket", "(", "addrAcctIdxBucketName", ")", "\n\n", "// Write account keyed by address hash", "err", "=", "bucket", ".", "Put", "(", "addrHash", ",", "uint32ToBytes", "(", "account", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n\n", "bucket", ",", "err", "=", "bucket", ".", "CreateBucketIfNotExists", "(", "uint32ToBytes", "(", "account", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// In account bucket, write a null value keyed by the address hash", "err", "=", "bucket", ".", "Put", "(", "addrHash", ",", "nullVal", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "addrHash", ")", "\n", "return", "managerError", "(", "ErrDatabase", ",", "str", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// putAddrAccountIndex stores the given key to the address account index of the // database.
[ "putAddrAccountIndex", "stores", "the", "given", "key", "to", "the", "address", "account", "index", "of", "the", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1028-L1056
train
btcsuite/btcwallet
waddrmgr/db.go
putAccountRow
func putAccountRow(ns walletdb.ReadWriteBucket, scope *KeyScope, account uint32, row *dbAccountRow) error { scopedBucket, err := fetchWriteScopeBucket(ns, scope) if err != nil { return err } bucket := scopedBucket.NestedReadWriteBucket(acctBucketName) // Write the serialized value keyed by the account number. err = bucket.Put(uint32ToBytes(account), serializeAccountRow(row)) if err != nil { str := fmt.Sprintf("failed to store account %d", account) return managerError(ErrDatabase, str, err) } return nil }
go
func putAccountRow(ns walletdb.ReadWriteBucket, scope *KeyScope, account uint32, row *dbAccountRow) error { scopedBucket, err := fetchWriteScopeBucket(ns, scope) if err != nil { return err } bucket := scopedBucket.NestedReadWriteBucket(acctBucketName) // Write the serialized value keyed by the account number. err = bucket.Put(uint32ToBytes(account), serializeAccountRow(row)) if err != nil { str := fmt.Sprintf("failed to store account %d", account) return managerError(ErrDatabase, str, err) } return nil }
[ "func", "putAccountRow", "(", "ns", "walletdb", ".", "ReadWriteBucket", ",", "scope", "*", "KeyScope", ",", "account", "uint32", ",", "row", "*", "dbAccountRow", ")", "error", "{", "scopedBucket", ",", "err", ":=", "fetchWriteScopeBucket", "(", "ns", ",", "scope", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "bucket", ":=", "scopedBucket", ".", "NestedReadWriteBucket", "(", "acctBucketName", ")", "\n\n", "// Write the serialized value keyed by the account number.", "err", "=", "bucket", ".", "Put", "(", "uint32ToBytes", "(", "account", ")", ",", "serializeAccountRow", "(", "row", ")", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "account", ")", "\n", "return", "managerError", "(", "ErrDatabase", ",", "str", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// putAccountRow stores the provided account information to the database. This // is used a common base for storing the various account types.
[ "putAccountRow", "stores", "the", "provided", "account", "information", "to", "the", "database", ".", "This", "is", "used", "a", "common", "base", "for", "storing", "the", "various", "account", "types", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1060-L1077
train
btcsuite/btcwallet
waddrmgr/db.go
putAccountInfo
func putAccountInfo(ns walletdb.ReadWriteBucket, scope *KeyScope, account uint32, encryptedPubKey, encryptedPrivKey []byte, nextExternalIndex, nextInternalIndex uint32, name string) error { rawData := serializeDefaultAccountRow( encryptedPubKey, encryptedPrivKey, nextExternalIndex, nextInternalIndex, name, ) // TODO(roasbeef): pass scope bucket directly?? acctRow := dbAccountRow{ acctType: accountDefault, rawData: rawData, } if err := putAccountRow(ns, scope, account, &acctRow); err != nil { return err } // Update account id index. if err := putAccountIDIndex(ns, scope, account, name); err != nil { return err } // Update account name index. if err := putAccountNameIndex(ns, scope, account, name); err != nil { return err } return nil }
go
func putAccountInfo(ns walletdb.ReadWriteBucket, scope *KeyScope, account uint32, encryptedPubKey, encryptedPrivKey []byte, nextExternalIndex, nextInternalIndex uint32, name string) error { rawData := serializeDefaultAccountRow( encryptedPubKey, encryptedPrivKey, nextExternalIndex, nextInternalIndex, name, ) // TODO(roasbeef): pass scope bucket directly?? acctRow := dbAccountRow{ acctType: accountDefault, rawData: rawData, } if err := putAccountRow(ns, scope, account, &acctRow); err != nil { return err } // Update account id index. if err := putAccountIDIndex(ns, scope, account, name); err != nil { return err } // Update account name index. if err := putAccountNameIndex(ns, scope, account, name); err != nil { return err } return nil }
[ "func", "putAccountInfo", "(", "ns", "walletdb", ".", "ReadWriteBucket", ",", "scope", "*", "KeyScope", ",", "account", "uint32", ",", "encryptedPubKey", ",", "encryptedPrivKey", "[", "]", "byte", ",", "nextExternalIndex", ",", "nextInternalIndex", "uint32", ",", "name", "string", ")", "error", "{", "rawData", ":=", "serializeDefaultAccountRow", "(", "encryptedPubKey", ",", "encryptedPrivKey", ",", "nextExternalIndex", ",", "nextInternalIndex", ",", "name", ",", ")", "\n\n", "// TODO(roasbeef): pass scope bucket directly??", "acctRow", ":=", "dbAccountRow", "{", "acctType", ":", "accountDefault", ",", "rawData", ":", "rawData", ",", "}", "\n", "if", "err", ":=", "putAccountRow", "(", "ns", ",", "scope", ",", "account", ",", "&", "acctRow", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Update account id index.", "if", "err", ":=", "putAccountIDIndex", "(", "ns", ",", "scope", ",", "account", ",", "name", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Update account name index.", "if", "err", ":=", "putAccountNameIndex", "(", "ns", ",", "scope", ",", "account", ",", "name", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// putAccountInfo stores the provided account information to the database.
[ "putAccountInfo", "stores", "the", "provided", "account", "information", "to", "the", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1080-L1110
train
btcsuite/btcwallet
waddrmgr/db.go
putLastAccount
func putLastAccount(ns walletdb.ReadWriteBucket, scope *KeyScope, account uint32) error { scopedBucket, err := fetchWriteScopeBucket(ns, scope) if err != nil { return err } bucket := scopedBucket.NestedReadWriteBucket(metaBucketName) err = bucket.Put(lastAccountName, uint32ToBytes(account)) if err != nil { str := fmt.Sprintf("failed to update metadata '%s'", lastAccountName) return managerError(ErrDatabase, str, err) } return nil }
go
func putLastAccount(ns walletdb.ReadWriteBucket, scope *KeyScope, account uint32) error { scopedBucket, err := fetchWriteScopeBucket(ns, scope) if err != nil { return err } bucket := scopedBucket.NestedReadWriteBucket(metaBucketName) err = bucket.Put(lastAccountName, uint32ToBytes(account)) if err != nil { str := fmt.Sprintf("failed to update metadata '%s'", lastAccountName) return managerError(ErrDatabase, str, err) } return nil }
[ "func", "putLastAccount", "(", "ns", "walletdb", ".", "ReadWriteBucket", ",", "scope", "*", "KeyScope", ",", "account", "uint32", ")", "error", "{", "scopedBucket", ",", "err", ":=", "fetchWriteScopeBucket", "(", "ns", ",", "scope", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "bucket", ":=", "scopedBucket", ".", "NestedReadWriteBucket", "(", "metaBucketName", ")", "\n\n", "err", "=", "bucket", ".", "Put", "(", "lastAccountName", ",", "uint32ToBytes", "(", "account", ")", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "lastAccountName", ")", "\n", "return", "managerError", "(", "ErrDatabase", ",", "str", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// putLastAccount stores the provided metadata - last account - to the // database.
[ "putLastAccount", "stores", "the", "provided", "metadata", "-", "last", "account", "-", "to", "the", "database", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1114-L1130
train
btcsuite/btcwallet
waddrmgr/db.go
deserializeAddressRow
func deserializeAddressRow(serializedAddress []byte) (*dbAddressRow, error) { // The serialized address format is: // <addrType><account><addedTime><syncStatus><rawdata> // // 1 byte addrType + 4 bytes account + 8 bytes addTime + 1 byte // syncStatus + 4 bytes raw data length + raw data // Given the above, the length of the entry must be at a minimum // the constant value sizes. if len(serializedAddress) < 18 { str := "malformed serialized address" return nil, managerError(ErrDatabase, str, nil) } row := dbAddressRow{} row.addrType = addressType(serializedAddress[0]) row.account = binary.LittleEndian.Uint32(serializedAddress[1:5]) row.addTime = binary.LittleEndian.Uint64(serializedAddress[5:13]) row.syncStatus = syncStatus(serializedAddress[13]) rdlen := binary.LittleEndian.Uint32(serializedAddress[14:18]) row.rawData = make([]byte, rdlen) copy(row.rawData, serializedAddress[18:18+rdlen]) return &row, nil }
go
func deserializeAddressRow(serializedAddress []byte) (*dbAddressRow, error) { // The serialized address format is: // <addrType><account><addedTime><syncStatus><rawdata> // // 1 byte addrType + 4 bytes account + 8 bytes addTime + 1 byte // syncStatus + 4 bytes raw data length + raw data // Given the above, the length of the entry must be at a minimum // the constant value sizes. if len(serializedAddress) < 18 { str := "malformed serialized address" return nil, managerError(ErrDatabase, str, nil) } row := dbAddressRow{} row.addrType = addressType(serializedAddress[0]) row.account = binary.LittleEndian.Uint32(serializedAddress[1:5]) row.addTime = binary.LittleEndian.Uint64(serializedAddress[5:13]) row.syncStatus = syncStatus(serializedAddress[13]) rdlen := binary.LittleEndian.Uint32(serializedAddress[14:18]) row.rawData = make([]byte, rdlen) copy(row.rawData, serializedAddress[18:18+rdlen]) return &row, nil }
[ "func", "deserializeAddressRow", "(", "serializedAddress", "[", "]", "byte", ")", "(", "*", "dbAddressRow", ",", "error", ")", "{", "// The serialized address format is:", "// <addrType><account><addedTime><syncStatus><rawdata>", "//", "// 1 byte addrType + 4 bytes account + 8 bytes addTime + 1 byte", "// syncStatus + 4 bytes raw data length + raw data", "// Given the above, the length of the entry must be at a minimum", "// the constant value sizes.", "if", "len", "(", "serializedAddress", ")", "<", "18", "{", "str", ":=", "\"", "\"", "\n", "return", "nil", ",", "managerError", "(", "ErrDatabase", ",", "str", ",", "nil", ")", "\n", "}", "\n\n", "row", ":=", "dbAddressRow", "{", "}", "\n", "row", ".", "addrType", "=", "addressType", "(", "serializedAddress", "[", "0", "]", ")", "\n", "row", ".", "account", "=", "binary", ".", "LittleEndian", ".", "Uint32", "(", "serializedAddress", "[", "1", ":", "5", "]", ")", "\n", "row", ".", "addTime", "=", "binary", ".", "LittleEndian", ".", "Uint64", "(", "serializedAddress", "[", "5", ":", "13", "]", ")", "\n", "row", ".", "syncStatus", "=", "syncStatus", "(", "serializedAddress", "[", "13", "]", ")", "\n", "rdlen", ":=", "binary", ".", "LittleEndian", ".", "Uint32", "(", "serializedAddress", "[", "14", ":", "18", "]", ")", "\n", "row", ".", "rawData", "=", "make", "(", "[", "]", "byte", ",", "rdlen", ")", "\n", "copy", "(", "row", ".", "rawData", ",", "serializedAddress", "[", "18", ":", "18", "+", "rdlen", "]", ")", "\n\n", "return", "&", "row", ",", "nil", "\n", "}" ]
// deserializeAddressRow deserializes the passed serialized address // information. This is used as a common base for the various address types to // deserialize the common parts.
[ "deserializeAddressRow", "deserializes", "the", "passed", "serialized", "address", "information", ".", "This", "is", "used", "as", "a", "common", "base", "for", "the", "various", "address", "types", "to", "deserialize", "the", "common", "parts", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1135-L1159
train
btcsuite/btcwallet
waddrmgr/db.go
serializeAddressRow
func serializeAddressRow(row *dbAddressRow) []byte { // The serialized address format is: // <addrType><account><addedTime><syncStatus><commentlen><comment> // <rawdata> // // 1 byte addrType + 4 bytes account + 8 bytes addTime + 1 byte // syncStatus + 4 bytes raw data length + raw data rdlen := len(row.rawData) buf := make([]byte, 18+rdlen) buf[0] = byte(row.addrType) binary.LittleEndian.PutUint32(buf[1:5], row.account) binary.LittleEndian.PutUint64(buf[5:13], row.addTime) buf[13] = byte(row.syncStatus) binary.LittleEndian.PutUint32(buf[14:18], uint32(rdlen)) copy(buf[18:18+rdlen], row.rawData) return buf }
go
func serializeAddressRow(row *dbAddressRow) []byte { // The serialized address format is: // <addrType><account><addedTime><syncStatus><commentlen><comment> // <rawdata> // // 1 byte addrType + 4 bytes account + 8 bytes addTime + 1 byte // syncStatus + 4 bytes raw data length + raw data rdlen := len(row.rawData) buf := make([]byte, 18+rdlen) buf[0] = byte(row.addrType) binary.LittleEndian.PutUint32(buf[1:5], row.account) binary.LittleEndian.PutUint64(buf[5:13], row.addTime) buf[13] = byte(row.syncStatus) binary.LittleEndian.PutUint32(buf[14:18], uint32(rdlen)) copy(buf[18:18+rdlen], row.rawData) return buf }
[ "func", "serializeAddressRow", "(", "row", "*", "dbAddressRow", ")", "[", "]", "byte", "{", "// The serialized address format is:", "// <addrType><account><addedTime><syncStatus><commentlen><comment>", "// <rawdata>", "//", "// 1 byte addrType + 4 bytes account + 8 bytes addTime + 1 byte", "// syncStatus + 4 bytes raw data length + raw data", "rdlen", ":=", "len", "(", "row", ".", "rawData", ")", "\n", "buf", ":=", "make", "(", "[", "]", "byte", ",", "18", "+", "rdlen", ")", "\n", "buf", "[", "0", "]", "=", "byte", "(", "row", ".", "addrType", ")", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "buf", "[", "1", ":", "5", "]", ",", "row", ".", "account", ")", "\n", "binary", ".", "LittleEndian", ".", "PutUint64", "(", "buf", "[", "5", ":", "13", "]", ",", "row", ".", "addTime", ")", "\n", "buf", "[", "13", "]", "=", "byte", "(", "row", ".", "syncStatus", ")", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "buf", "[", "14", ":", "18", "]", ",", "uint32", "(", "rdlen", ")", ")", "\n", "copy", "(", "buf", "[", "18", ":", "18", "+", "rdlen", "]", ",", "row", ".", "rawData", ")", "\n", "return", "buf", "\n", "}" ]
// serializeAddressRow returns the serialization of the passed address row.
[ "serializeAddressRow", "returns", "the", "serialization", "of", "the", "passed", "address", "row", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1162-L1178
train
btcsuite/btcwallet
waddrmgr/db.go
deserializeChainedAddress
func deserializeChainedAddress(row *dbAddressRow) (*dbChainAddressRow, error) { // The serialized chain address raw data format is: // <branch><index> // // 4 bytes branch + 4 bytes address index if len(row.rawData) != 8 { str := "malformed serialized chained address" return nil, managerError(ErrDatabase, str, nil) } retRow := dbChainAddressRow{ dbAddressRow: *row, } retRow.branch = binary.LittleEndian.Uint32(row.rawData[0:4]) retRow.index = binary.LittleEndian.Uint32(row.rawData[4:8]) return &retRow, nil }
go
func deserializeChainedAddress(row *dbAddressRow) (*dbChainAddressRow, error) { // The serialized chain address raw data format is: // <branch><index> // // 4 bytes branch + 4 bytes address index if len(row.rawData) != 8 { str := "malformed serialized chained address" return nil, managerError(ErrDatabase, str, nil) } retRow := dbChainAddressRow{ dbAddressRow: *row, } retRow.branch = binary.LittleEndian.Uint32(row.rawData[0:4]) retRow.index = binary.LittleEndian.Uint32(row.rawData[4:8]) return &retRow, nil }
[ "func", "deserializeChainedAddress", "(", "row", "*", "dbAddressRow", ")", "(", "*", "dbChainAddressRow", ",", "error", ")", "{", "// The serialized chain address raw data format is:", "// <branch><index>", "//", "// 4 bytes branch + 4 bytes address index", "if", "len", "(", "row", ".", "rawData", ")", "!=", "8", "{", "str", ":=", "\"", "\"", "\n", "return", "nil", ",", "managerError", "(", "ErrDatabase", ",", "str", ",", "nil", ")", "\n", "}", "\n\n", "retRow", ":=", "dbChainAddressRow", "{", "dbAddressRow", ":", "*", "row", ",", "}", "\n\n", "retRow", ".", "branch", "=", "binary", ".", "LittleEndian", ".", "Uint32", "(", "row", ".", "rawData", "[", "0", ":", "4", "]", ")", "\n", "retRow", ".", "index", "=", "binary", ".", "LittleEndian", ".", "Uint32", "(", "row", ".", "rawData", "[", "4", ":", "8", "]", ")", "\n\n", "return", "&", "retRow", ",", "nil", "\n", "}" ]
// deserializeChainedAddress deserializes the raw data from the passed address // row as a chained address.
[ "deserializeChainedAddress", "deserializes", "the", "raw", "data", "from", "the", "passed", "address", "row", "as", "a", "chained", "address", "." ]
9d95f76e99a72ffaf73b8a6581d8781c52d756f5
https://github.com/btcsuite/btcwallet/blob/9d95f76e99a72ffaf73b8a6581d8781c52d756f5/waddrmgr/db.go#L1182-L1200
train
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", "{", "// The serialized chain address raw data format is:", "// <branch><index>", "//", "// 4 bytes branch + 4 bytes address index", "rawData", ":=", "make", "(", "[", "]", "byte", ",", "8", ")", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "rawData", "[", "0", ":", "4", "]", ",", "branch", ")", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "rawData", "[", "4", ":", "8", "]", ",", "index", ")", "\n", "return", "rawData", "\n", "}" ]
// 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", ")", "{", "// 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", ":=", "\"", "\"", "\n", "return", "nil", ",", "managerError", "(", "ErrDatabase", ",", "str", ",", "nil", ")", "\n", "}", "\n\n", "retRow", ":=", "dbImportedAddressRow", "{", "dbAddressRow", ":", "*", "row", ",", "}", "\n\n", "pubLen", ":=", "binary", ".", "LittleEndian", ".", "Uint32", "(", "row", ".", "rawData", "[", "0", ":", "4", "]", ")", "\n", "retRow", ".", "encryptedPubKey", "=", "make", "(", "[", "]", "byte", ",", "pubLen", ")", "\n", "copy", "(", "retRow", ".", "encryptedPubKey", ",", "row", ".", "rawData", "[", "4", ":", "4", "+", "pubLen", "]", ")", "\n", "offset", ":=", "4", "+", "pubLen", "\n", "privLen", ":=", "binary", ".", "LittleEndian", ".", "Uint32", "(", "row", ".", "rawData", "[", "offset", ":", "offset", "+", "4", "]", ")", "\n", "offset", "+=", "4", "\n", "retRow", ".", "encryptedPrivKey", "=", "make", "(", "[", "]", "byte", ",", "privLen", ")", "\n", "copy", "(", "retRow", ".", "encryptedPrivKey", ",", "row", ".", "rawData", "[", "offset", ":", "offset", "+", "privLen", "]", ")", "\n\n", "return", "&", "retRow", ",", "nil", "\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", "{", "// 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", ")", ")", "\n", "privLen", ":=", "uint32", "(", "len", "(", "encryptedPrivKey", ")", ")", "\n", "rawData", ":=", "make", "(", "[", "]", "byte", ",", "8", "+", "pubLen", "+", "privLen", ")", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "rawData", "[", "0", ":", "4", "]", ",", "pubLen", ")", "\n", "copy", "(", "rawData", "[", "4", ":", "4", "+", "pubLen", "]", ",", "encryptedPubKey", ")", "\n", "offset", ":=", "4", "+", "pubLen", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "rawData", "[", "offset", ":", "offset", "+", "4", "]", ",", "privLen", ")", "\n", "offset", "+=", "4", "\n", "copy", "(", "rawData", "[", "offset", ":", "offset", "+", "privLen", "]", ",", "encryptedPrivKey", ")", "\n", "return", "rawData", "\n", "}" ]
// 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", ")", "{", "// 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", ":=", "\"", "\"", "\n", "return", "nil", ",", "managerError", "(", "ErrDatabase", ",", "str", ",", "nil", ")", "\n", "}", "\n\n", "retRow", ":=", "dbScriptAddressRow", "{", "dbAddressRow", ":", "*", "row", ",", "}", "\n\n", "hashLen", ":=", "binary", ".", "LittleEndian", ".", "Uint32", "(", "row", ".", "rawData", "[", "0", ":", "4", "]", ")", "\n", "retRow", ".", "encryptedHash", "=", "make", "(", "[", "]", "byte", ",", "hashLen", ")", "\n", "copy", "(", "retRow", ".", "encryptedHash", ",", "row", ".", "rawData", "[", "4", ":", "4", "+", "hashLen", "]", ")", "\n", "offset", ":=", "4", "+", "hashLen", "\n", "scriptLen", ":=", "binary", ".", "LittleEndian", ".", "Uint32", "(", "row", ".", "rawData", "[", "offset", ":", "offset", "+", "4", "]", ")", "\n", "offset", "+=", "4", "\n", "retRow", ".", "encryptedScript", "=", "make", "(", "[", "]", "byte", ",", "scriptLen", ")", "\n", "copy", "(", "retRow", ".", "encryptedScript", ",", "row", ".", "rawData", "[", "offset", ":", "offset", "+", "scriptLen", "]", ")", "\n\n", "return", "&", "retRow", ",", "nil", "\n", "}" ]
// 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", "{", "// 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", ")", ")", "\n", "scriptLen", ":=", "uint32", "(", "len", "(", "encryptedScript", ")", ")", "\n", "rawData", ":=", "make", "(", "[", "]", "byte", ",", "8", "+", "hashLen", "+", "scriptLen", ")", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "rawData", "[", "0", ":", "4", "]", ",", "hashLen", ")", "\n", "copy", "(", "rawData", "[", "4", ":", "4", "+", "hashLen", "]", ",", "encryptedHash", ")", "\n", "offset", ":=", "4", "+", "hashLen", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "rawData", "[", "offset", ":", "offset", "+", "4", "]", ",", "scriptLen", ")", "\n", "offset", "+=", "4", "\n", "copy", "(", "rawData", "[", "offset", ":", "offset", "+", "scriptLen", "]", ",", "encryptedScript", ")", "\n", "return", "rawData", "\n", "}" ]
// 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", "(", "ns", ",", "scope", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "bucket", ":=", "scopedBucket", ".", "NestedReadBucket", "(", "addrBucketName", ")", "\n\n", "serializedRow", ":=", "bucket", ".", "Get", "(", "addrHash", "[", ":", "]", ")", "\n", "if", "serializedRow", "==", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "nil", ",", "managerError", "(", "ErrAddressNotFound", ",", "str", ",", "nil", ")", "\n", "}", "\n\n", "row", ",", "err", ":=", "deserializeAddressRow", "(", "serializedRow", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "switch", "row", ".", "addrType", "{", "case", "adtChain", ":", "return", "deserializeChainedAddress", "(", "row", ")", "\n", "case", "adtImport", ":", "return", "deserializeImportedAddress", "(", "row", ")", "\n", "case", "adtScript", ":", "return", "deserializeScriptAddress", "(", "row", ")", "\n", "}", "\n\n", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "row", ".", "addrType", ")", "\n", "return", "nil", ",", "managerError", "(", "ErrDatabase", ",", "str", ",", "nil", ")", "\n", "}" ]
// 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", ".", "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", "." ]
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", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n\n", "bucket", ":=", "scopedBucket", ".", "NestedReadBucket", "(", "usedAddrBucketName", ")", "\n\n", "addrHash", ":=", "sha256", ".", "Sum256", "(", "addressID", ")", "\n", "return", "bucket", ".", "Get", "(", "addrHash", "[", ":", "]", ")", "!=", "nil", "\n", "}" ]
// 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", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "bucket", ":=", "scopedBucket", ".", "NestedReadWriteBucket", "(", "usedAddrBucketName", ")", "\n\n", "addrHash", ":=", "sha256", ".", "Sum256", "(", "addressID", ")", "\n", "val", ":=", "bucket", ".", "Get", "(", "addrHash", "[", ":", "]", ")", "\n", "if", "val", "!=", "nil", "{", "return", "nil", "\n", "}", "\n\n", "err", "=", "bucket", ".", "Put", "(", "addrHash", "[", ":", "]", ",", "[", "]", "byte", "{", "0", "}", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "addressID", ")", "\n", "return", "managerError", "(", "ErrDatabase", ",", "str", ",", "err", ")", "\n", "}", "\n\n", "return", "nil", "\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", ")", "\n", "return", "fetchAddressByHash", "(", "ns", ",", "scope", ",", "addrHash", "[", ":", "]", ")", "\n", "}" ]
// 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", "caller", "should", "use", "type", "assertions", "to", "ascertain", "the", "type", ".", "The", "caller", "should", "prefix", "the", "error", "message", "with", "the", "address", "which", "caused", "the", "failure", "." ]
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", ",", "scope", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "bucket", ":=", "scopedBucket", ".", "NestedReadWriteBucket", "(", "addrBucketName", ")", "\n\n", "// 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", ")", "\n", "err", "=", "bucket", ".", "Put", "(", "addrHash", "[", ":", "]", ",", "serializeAddressRow", "(", "row", ")", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "addressID", ")", "\n", "return", "managerError", "(", "ErrDatabase", ",", "str", ",", "err", ")", "\n", "}", "\n\n", "// Update address account index", "return", "putAddrAccountIndex", "(", "ns", ",", "scope", ",", "row", ".", "account", ",", "addrHash", "[", ":", "]", ")", "\n", "}" ]
// 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", "addressType", ")", "error", "{", "scopedBucket", ",", "err", ":=", "fetchWriteScopeBucket", "(", "ns", ",", "scope", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "addrRow", ":=", "dbAddressRow", "{", "addrType", ":", "addrType", ",", "account", ":", "account", ",", "addTime", ":", "uint64", "(", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", ")", ",", "syncStatus", ":", "status", ",", "rawData", ":", "serializeChainedAddress", "(", "branch", ",", "index", ")", ",", "}", "\n", "if", "err", ":=", "putAddress", "(", "ns", ",", "scope", ",", "addressID", ",", "&", "addrRow", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Update the next index for the appropriate internal or external", "// branch.", "accountID", ":=", "uint32ToBytes", "(", "account", ")", "\n", "bucket", ":=", "scopedBucket", ".", "NestedReadWriteBucket", "(", "acctBucketName", ")", "\n", "serializedAccount", ":=", "bucket", ".", "Get", "(", "accountID", ")", "\n\n", "// Deserialize the account row.", "row", ",", "err", ":=", "deserializeAccountRow", "(", "accountID", ",", "serializedAccount", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "arow", ",", "err", ":=", "deserializeDefaultAccountRow", "(", "accountID", ",", "row", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Increment the appropriate next index depending on whether the branch", "// is internal or external.", "nextExternalIndex", ":=", "arow", ".", "nextExternalIndex", "\n", "nextInternalIndex", ":=", "arow", ".", "nextInternalIndex", "\n", "if", "branch", "==", "InternalBranch", "{", "nextInternalIndex", "=", "index", "+", "1", "\n", "}", "else", "{", "nextExternalIndex", "=", "index", "+", "1", "\n", "}", "\n\n", "// Reserialize the account with the updated index and store it.", "row", ".", "rawData", "=", "serializeDefaultAccountRow", "(", "arow", ".", "pubKeyEncrypted", ",", "arow", ".", "privKeyEncrypted", ",", "nextExternalIndex", ",", "nextInternalIndex", ",", "arow", ".", "name", ",", ")", "\n", "err", "=", "bucket", ".", "Put", "(", "accountID", ",", "serializeAccountRow", "(", "row", ")", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "addressID", ",", "account", ")", "\n", "return", "managerError", "(", "ErrDatabase", ",", "str", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// 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", "[", "]", "byte", ")", "error", "{", "rawData", ":=", "serializeImportedAddress", "(", "encryptedPubKey", ",", "encryptedPrivKey", ")", "\n", "addrRow", ":=", "dbAddressRow", "{", "addrType", ":", "adtImport", ",", "account", ":", "account", ",", "addTime", ":", "uint64", "(", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", ")", ",", "syncStatus", ":", "status", ",", "rawData", ":", "rawData", ",", "}", "\n", "return", "putAddress", "(", "ns", ",", "scope", ",", "addressID", ",", "&", "addrRow", ")", "\n", "}" ]
// 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", ")", "error", "{", "rawData", ":=", "serializeScriptAddress", "(", "encryptedHash", ",", "encryptedScript", ")", "\n", "addrRow", ":=", "dbAddressRow", "{", "addrType", ":", "adtScript", ",", "account", ":", "account", ",", "addTime", ":", "uint64", "(", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", ")", ",", "syncStatus", ":", "status", ",", "rawData", ":", "rawData", ",", "}", "\n", "if", "err", ":=", "putAddress", "(", "ns", ",", "scope", ",", "addressID", ",", "&", "addrRow", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// 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", ",", "scope", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "bucket", ":=", "scopedBucket", ".", "NestedReadBucket", "(", "addrAcctIdxBucketName", ")", "\n\n", "addrHash", ":=", "sha256", ".", "Sum256", "(", "addressID", ")", "\n", "val", ":=", "bucket", ".", "Get", "(", "addrHash", "[", ":", "]", ")", "\n", "if", "val", "==", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "0", ",", "managerError", "(", "ErrAddressNotFound", ",", "str", ",", "nil", ")", "\n", "}", "\n", "return", "binary", ".", "LittleEndian", ".", "Uint32", "(", "val", ")", ",", "nil", "\n", "}" ]
// 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", "corresponding", "account", "id", "." ]
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", ":=", "fetchReadScopeBucket", "(", "ns", ",", "scope", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "bucket", ":=", "scopedBucket", ".", "NestedReadBucket", "(", "addrAcctIdxBucketName", ")", ".", "NestedReadBucket", "(", "uint32ToBytes", "(", "account", ")", ")", "\n\n", "// If index bucket is missing the account, there hasn't been any", "// address entries yet", "if", "bucket", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "err", "=", "bucket", ".", "ForEach", "(", "func", "(", "k", ",", "v", "[", "]", "byte", ")", "error", "{", "// Skip buckets.", "if", "v", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "addrRow", ",", "err", ":=", "fetchAddressByHash", "(", "ns", ",", "scope", ",", "k", ")", "\n", "if", "err", "!=", "nil", "{", "if", "merr", ",", "ok", ":=", "err", ".", "(", "*", "ManagerError", ")", ";", "ok", "{", "desc", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "k", ",", "merr", ".", "Description", ")", "\n", "merr", ".", "Description", "=", "desc", "\n", "return", "merr", "\n", "}", "\n", "return", "err", "\n", "}", "\n\n", "return", "fn", "(", "addrRow", ")", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "maybeConvertDbError", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// 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\n", "// The serialized synced to format is:", "// <blockheight><blockhash><timestamp>", "//", "// 4 bytes block height + 32 bytes hash length", "buf", ":=", "bucket", ".", "Get", "(", "syncedToName", ")", "\n", "if", "len", "(", "buf", ")", "<", "36", "{", "str", ":=", "\"", "\"", "\n", "return", "nil", ",", "managerError", "(", "ErrDatabase", ",", "str", ",", "nil", ")", "\n", "}", "\n\n", "var", "bs", "BlockStamp", "\n", "bs", ".", "Height", "=", "int32", "(", "binary", ".", "LittleEndian", ".", "Uint32", "(", "buf", "[", "0", ":", "4", "]", ")", ")", "\n", "copy", "(", "bs", ".", "Hash", "[", ":", "]", ",", "buf", "[", "4", ":", "36", "]", ")", "\n\n", "if", "len", "(", "buf", ")", "==", "40", "{", "bs", ".", "Timestamp", "=", "time", ".", "Unix", "(", "int64", "(", "binary", ".", "LittleEndian", ".", "Uint32", "(", "buf", "[", "36", ":", "]", ")", ")", ",", "0", ",", ")", "\n", "}", "\n\n", "return", "&", "bs", ",", "nil", "\n", "}" ]
// 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", "(", "\"", "\"", ",", "bs", ".", "Hash", ")", "\n\n", "// 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", ")", "\n", "}", "\n", "}", "\n\n", "// Store the block hash by block height.", "height", ":=", "make", "(", "[", "]", "byte", ",", "4", ")", "\n", "binary", ".", "BigEndian", ".", "PutUint32", "(", "height", ",", "uint32", "(", "bs", ".", "Height", ")", ")", "\n", "err", ":=", "bucket", ".", "Put", "(", "height", ",", "bs", ".", "Hash", "[", "0", ":", "32", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "managerError", "(", "ErrDatabase", ",", "errStr", ",", "err", ")", "\n", "}", "\n\n", "// 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", ")", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "buf", "[", "0", ":", "4", "]", ",", "uint32", "(", "bs", ".", "Height", ")", ")", "\n", "copy", "(", "buf", "[", "4", ":", "36", "]", ",", "bs", ".", "Hash", "[", "0", ":", "32", "]", ")", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "buf", "[", "36", ":", "]", ",", "uint32", "(", "bs", ".", "Timestamp", ".", "Unix", "(", ")", ")", ")", "\n\n", "err", "=", "bucket", ".", "Put", "(", "syncedToName", ",", "buf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "managerError", "(", "ErrDatabase", ",", "errStr", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// 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", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "height", ")", "\n\n", "heightBytes", ":=", "make", "(", "[", "]", "byte", ",", "4", ")", "\n", "binary", ".", "BigEndian", ".", "PutUint32", "(", "heightBytes", ",", "uint32", "(", "height", ")", ")", "\n", "hashBytes", ":=", "bucket", ".", "Get", "(", "heightBytes", ")", "\n", "if", "hashBytes", "==", "nil", "{", "err", ":=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "managerError", "(", "ErrBlockNotFound", ",", "errStr", ",", "err", ")", "\n", "}", "\n", "if", "len", "(", "hashBytes", ")", "!=", "32", "{", "err", ":=", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "managerError", "(", "ErrDatabase", ",", "errStr", ",", "err", ")", "\n", "}", "\n", "var", "hash", "chainhash", ".", "Hash", "\n", "if", "err", ":=", "hash", ".", "SetBytes", "(", "hashBytes", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "managerError", "(", "ErrDatabase", ",", "errStr", ",", "err", ")", "\n", "}", "\n", "return", "&", "hash", ",", "nil", "\n", "}" ]
// 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\n", "// The serialized start block format is:", "// <blockheight><blockhash>", "//", "// 4 bytes block height + 32 bytes hash length", "buf", ":=", "bucket", ".", "Get", "(", "startBlockName", ")", "\n", "if", "len", "(", "buf", ")", "!=", "36", "{", "str", ":=", "\"", "\"", "\n", "return", "nil", ",", "managerError", "(", "ErrDatabase", ",", "str", ",", "nil", ")", "\n", "}", "\n\n", "var", "bs", "BlockStamp", "\n", "bs", ".", "Height", "=", "int32", "(", "binary", ".", "LittleEndian", ".", "Uint32", "(", "buf", "[", "0", ":", "4", "]", ")", ")", "\n", "copy", "(", "bs", ".", "Hash", "[", ":", "]", ",", "buf", "[", "4", ":", "36", "]", ")", "\n", "return", "&", "bs", ",", "nil", "\n", "}" ]
// 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\n", "// The serialized start block format is:", "// <blockheight><blockhash>", "//", "// 4 bytes block height + 32 bytes hash length", "buf", ":=", "make", "(", "[", "]", "byte", ",", "36", ")", "\n", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "buf", "[", "0", ":", "4", "]", ",", "uint32", "(", "bs", ".", "Height", ")", ")", "\n", "copy", "(", "buf", "[", "4", ":", "36", "]", ",", "bs", ".", "Hash", "[", "0", ":", "32", "]", ")", "\n\n", "err", ":=", "bucket", ".", "Put", "(", "startBlockName", ",", "buf", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "bs", ".", "Hash", ")", "\n", "return", "managerError", "(", "ErrDatabase", ",", "str", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// 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\n", "bucket", ":=", "ns", ".", "NestedReadBucket", "(", "syncBucketName", ")", "\n", "birthdayTimestamp", ":=", "bucket", ".", "Get", "(", "birthdayName", ")", "\n", "if", "len", "(", "birthdayTimestamp", ")", "!=", "8", "{", "str", ":=", "\"", "\"", "\n", "return", "t", ",", "managerError", "(", "ErrDatabase", ",", "str", ",", "nil", ")", "\n", "}", "\n\n", "t", "=", "time", ".", "Unix", "(", "int64", "(", "binary", ".", "BigEndian", ".", "Uint64", "(", "birthdayTimestamp", ")", ")", ",", "0", ")", "\n\n", "return", "t", ",", "nil", "\n", "}" ]
// 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", "[", ":", "]", ",", "uint64", "(", "t", ".", "Unix", "(", ")", ")", ")", "\n\n", "bucket", ":=", "ns", ".", "NestedReadWriteBucket", "(", "syncBucketName", ")", "\n", "if", "err", ":=", "bucket", ".", "Put", "(", "birthdayName", ",", "birthdayTimestamp", "[", ":", "]", ")", ";", "err", "!=", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "managerError", "(", "ErrDatabase", ",", "str", ",", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// 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