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
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
btcsuite/btcd
blockchain/indexers/txindex.go
Init
func (idx *TxIndex) Init() error { // Find the latest known block id field for the internal block id // index and initialize it. This is done because it's a lot more // efficient to do a single search at initialize time than it is to // write another value to the database on every update. err := idx.db.View(func(dbTx database.Tx) error { // Scan forward in large gaps to find a block id that doesn't // exist yet to serve as an upper bound for the binary search // below. var highestKnown, nextUnknown uint32 testBlockID := uint32(1) increment := uint32(100000) for { _, err := dbFetchBlockHashByID(dbTx, testBlockID) if err != nil { nextUnknown = testBlockID break } highestKnown = testBlockID testBlockID += increment } log.Tracef("Forward scan (highest known %d, next unknown %d)", highestKnown, nextUnknown) // No used block IDs due to new database. if nextUnknown == 1 { return nil } // Use a binary search to find the final highest used block id. // This will take at most ceil(log_2(increment)) attempts. for { testBlockID = (highestKnown + nextUnknown) / 2 _, err := dbFetchBlockHashByID(dbTx, testBlockID) if err != nil { nextUnknown = testBlockID } else { highestKnown = testBlockID } log.Tracef("Binary scan (highest known %d, next "+ "unknown %d)", highestKnown, nextUnknown) if highestKnown+1 == nextUnknown { break } } idx.curBlockID = highestKnown return nil }) if err != nil { return err } log.Debugf("Current internal block ID: %d", idx.curBlockID) return nil }
go
func (idx *TxIndex) Init() error { // Find the latest known block id field for the internal block id // index and initialize it. This is done because it's a lot more // efficient to do a single search at initialize time than it is to // write another value to the database on every update. err := idx.db.View(func(dbTx database.Tx) error { // Scan forward in large gaps to find a block id that doesn't // exist yet to serve as an upper bound for the binary search // below. var highestKnown, nextUnknown uint32 testBlockID := uint32(1) increment := uint32(100000) for { _, err := dbFetchBlockHashByID(dbTx, testBlockID) if err != nil { nextUnknown = testBlockID break } highestKnown = testBlockID testBlockID += increment } log.Tracef("Forward scan (highest known %d, next unknown %d)", highestKnown, nextUnknown) // No used block IDs due to new database. if nextUnknown == 1 { return nil } // Use a binary search to find the final highest used block id. // This will take at most ceil(log_2(increment)) attempts. for { testBlockID = (highestKnown + nextUnknown) / 2 _, err := dbFetchBlockHashByID(dbTx, testBlockID) if err != nil { nextUnknown = testBlockID } else { highestKnown = testBlockID } log.Tracef("Binary scan (highest known %d, next "+ "unknown %d)", highestKnown, nextUnknown) if highestKnown+1 == nextUnknown { break } } idx.curBlockID = highestKnown return nil }) if err != nil { return err } log.Debugf("Current internal block ID: %d", idx.curBlockID) return nil }
[ "func", "(", "idx", "*", "TxIndex", ")", "Init", "(", ")", "error", "{", "// Find the latest known block id field for the internal block id", "// index and initialize it. This is done because it's a lot more", "// efficient to do a single search at initialize time than it is to", "// write another value to the database on every update.", "err", ":=", "idx", ".", "db", ".", "View", "(", "func", "(", "dbTx", "database", ".", "Tx", ")", "error", "{", "// Scan forward in large gaps to find a block id that doesn't", "// exist yet to serve as an upper bound for the binary search", "// below.", "var", "highestKnown", ",", "nextUnknown", "uint32", "\n", "testBlockID", ":=", "uint32", "(", "1", ")", "\n", "increment", ":=", "uint32", "(", "100000", ")", "\n", "for", "{", "_", ",", "err", ":=", "dbFetchBlockHashByID", "(", "dbTx", ",", "testBlockID", ")", "\n", "if", "err", "!=", "nil", "{", "nextUnknown", "=", "testBlockID", "\n", "break", "\n", "}", "\n\n", "highestKnown", "=", "testBlockID", "\n", "testBlockID", "+=", "increment", "\n", "}", "\n", "log", ".", "Tracef", "(", "\"", "\"", ",", "highestKnown", ",", "nextUnknown", ")", "\n\n", "// No used block IDs due to new database.", "if", "nextUnknown", "==", "1", "{", "return", "nil", "\n", "}", "\n\n", "// Use a binary search to find the final highest used block id.", "// This will take at most ceil(log_2(increment)) attempts.", "for", "{", "testBlockID", "=", "(", "highestKnown", "+", "nextUnknown", ")", "/", "2", "\n", "_", ",", "err", ":=", "dbFetchBlockHashByID", "(", "dbTx", ",", "testBlockID", ")", "\n", "if", "err", "!=", "nil", "{", "nextUnknown", "=", "testBlockID", "\n", "}", "else", "{", "highestKnown", "=", "testBlockID", "\n", "}", "\n", "log", ".", "Tracef", "(", "\"", "\"", "+", "\"", "\"", ",", "highestKnown", ",", "nextUnknown", ")", "\n", "if", "highestKnown", "+", "1", "==", "nextUnknown", "{", "break", "\n", "}", "\n", "}", "\n\n", "idx", ".", "curBlockID", "=", "highestKnown", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "idx", ".", "curBlockID", ")", "\n", "return", "nil", "\n", "}" ]
// Init initializes the hash-based transaction index. In particular, it finds // the highest used block ID and stores it for later use when connecting or // disconnecting blocks. // // This is part of the Indexer interface.
[ "Init", "initializes", "the", "hash", "-", "based", "transaction", "index", ".", "In", "particular", "it", "finds", "the", "highest", "used", "block", "ID", "and", "stores", "it", "for", "later", "use", "when", "connecting", "or", "disconnecting", "blocks", ".", "This", "is", "part", "of", "the", "Indexer", "interface", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/txindex.go#L297-L353
train
btcsuite/btcd
blockchain/indexers/txindex.go
Create
func (idx *TxIndex) Create(dbTx database.Tx) error { meta := dbTx.Metadata() if _, err := meta.CreateBucket(idByHashIndexBucketName); err != nil { return err } if _, err := meta.CreateBucket(hashByIDIndexBucketName); err != nil { return err } _, err := meta.CreateBucket(txIndexKey) return err }
go
func (idx *TxIndex) Create(dbTx database.Tx) error { meta := dbTx.Metadata() if _, err := meta.CreateBucket(idByHashIndexBucketName); err != nil { return err } if _, err := meta.CreateBucket(hashByIDIndexBucketName); err != nil { return err } _, err := meta.CreateBucket(txIndexKey) return err }
[ "func", "(", "idx", "*", "TxIndex", ")", "Create", "(", "dbTx", "database", ".", "Tx", ")", "error", "{", "meta", ":=", "dbTx", ".", "Metadata", "(", ")", "\n", "if", "_", ",", "err", ":=", "meta", ".", "CreateBucket", "(", "idByHashIndexBucketName", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "_", ",", "err", ":=", "meta", ".", "CreateBucket", "(", "hashByIDIndexBucketName", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", ",", "err", ":=", "meta", ".", "CreateBucket", "(", "txIndexKey", ")", "\n", "return", "err", "\n", "}" ]
// Create is invoked when the indexer manager determines the index needs // to be created for the first time. It creates the buckets for the hash-based // transaction index and the internal block ID indexes. // // This is part of the Indexer interface.
[ "Create", "is", "invoked", "when", "the", "indexer", "manager", "determines", "the", "index", "needs", "to", "be", "created", "for", "the", "first", "time", ".", "It", "creates", "the", "buckets", "for", "the", "hash", "-", "based", "transaction", "index", "and", "the", "internal", "block", "ID", "indexes", ".", "This", "is", "part", "of", "the", "Indexer", "interface", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/txindex.go#L374-L384
train
btcsuite/btcd
blockchain/indexers/txindex.go
ConnectBlock
func (idx *TxIndex) ConnectBlock(dbTx database.Tx, block *btcutil.Block, stxos []blockchain.SpentTxOut) error { // Increment the internal block ID to use for the block being connected // and add all of the transactions in the block to the index. newBlockID := idx.curBlockID + 1 if err := dbAddTxIndexEntries(dbTx, block, newBlockID); err != nil { return err } // Add the new block ID index entry for the block being connected and // update the current internal block ID accordingly. err := dbPutBlockIDIndexEntry(dbTx, block.Hash(), newBlockID) if err != nil { return err } idx.curBlockID = newBlockID return nil }
go
func (idx *TxIndex) ConnectBlock(dbTx database.Tx, block *btcutil.Block, stxos []blockchain.SpentTxOut) error { // Increment the internal block ID to use for the block being connected // and add all of the transactions in the block to the index. newBlockID := idx.curBlockID + 1 if err := dbAddTxIndexEntries(dbTx, block, newBlockID); err != nil { return err } // Add the new block ID index entry for the block being connected and // update the current internal block ID accordingly. err := dbPutBlockIDIndexEntry(dbTx, block.Hash(), newBlockID) if err != nil { return err } idx.curBlockID = newBlockID return nil }
[ "func", "(", "idx", "*", "TxIndex", ")", "ConnectBlock", "(", "dbTx", "database", ".", "Tx", ",", "block", "*", "btcutil", ".", "Block", ",", "stxos", "[", "]", "blockchain", ".", "SpentTxOut", ")", "error", "{", "// Increment the internal block ID to use for the block being connected", "// and add all of the transactions in the block to the index.", "newBlockID", ":=", "idx", ".", "curBlockID", "+", "1", "\n", "if", "err", ":=", "dbAddTxIndexEntries", "(", "dbTx", ",", "block", ",", "newBlockID", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Add the new block ID index entry for the block being connected and", "// update the current internal block ID accordingly.", "err", ":=", "dbPutBlockIDIndexEntry", "(", "dbTx", ",", "block", ".", "Hash", "(", ")", ",", "newBlockID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "idx", ".", "curBlockID", "=", "newBlockID", "\n", "return", "nil", "\n", "}" ]
// ConnectBlock is invoked by the index manager when a new block has been // connected to the main chain. This indexer adds a hash-to-transaction mapping // for every transaction in the passed block. // // This is part of the Indexer interface.
[ "ConnectBlock", "is", "invoked", "by", "the", "index", "manager", "when", "a", "new", "block", "has", "been", "connected", "to", "the", "main", "chain", ".", "This", "indexer", "adds", "a", "hash", "-", "to", "-", "transaction", "mapping", "for", "every", "transaction", "in", "the", "passed", "block", ".", "This", "is", "part", "of", "the", "Indexer", "interface", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/txindex.go#L391-L409
train
btcsuite/btcd
blockchain/indexers/txindex.go
DisconnectBlock
func (idx *TxIndex) DisconnectBlock(dbTx database.Tx, block *btcutil.Block, stxos []blockchain.SpentTxOut) error { // Remove all of the transactions in the block from the index. if err := dbRemoveTxIndexEntries(dbTx, block); err != nil { return err } // Remove the block ID index entry for the block being disconnected and // decrement the current internal block ID to account for it. if err := dbRemoveBlockIDIndexEntry(dbTx, block.Hash()); err != nil { return err } idx.curBlockID-- return nil }
go
func (idx *TxIndex) DisconnectBlock(dbTx database.Tx, block *btcutil.Block, stxos []blockchain.SpentTxOut) error { // Remove all of the transactions in the block from the index. if err := dbRemoveTxIndexEntries(dbTx, block); err != nil { return err } // Remove the block ID index entry for the block being disconnected and // decrement the current internal block ID to account for it. if err := dbRemoveBlockIDIndexEntry(dbTx, block.Hash()); err != nil { return err } idx.curBlockID-- return nil }
[ "func", "(", "idx", "*", "TxIndex", ")", "DisconnectBlock", "(", "dbTx", "database", ".", "Tx", ",", "block", "*", "btcutil", ".", "Block", ",", "stxos", "[", "]", "blockchain", ".", "SpentTxOut", ")", "error", "{", "// Remove all of the transactions in the block from the index.", "if", "err", ":=", "dbRemoveTxIndexEntries", "(", "dbTx", ",", "block", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Remove the block ID index entry for the block being disconnected and", "// decrement the current internal block ID to account for it.", "if", "err", ":=", "dbRemoveBlockIDIndexEntry", "(", "dbTx", ",", "block", ".", "Hash", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "idx", ".", "curBlockID", "--", "\n", "return", "nil", "\n", "}" ]
// DisconnectBlock is invoked by the index manager when a block has been // disconnected from the main chain. This indexer removes the // hash-to-transaction mapping for every transaction in the block. // // This is part of the Indexer interface.
[ "DisconnectBlock", "is", "invoked", "by", "the", "index", "manager", "when", "a", "block", "has", "been", "disconnected", "from", "the", "main", "chain", ".", "This", "indexer", "removes", "the", "hash", "-", "to", "-", "transaction", "mapping", "for", "every", "transaction", "in", "the", "block", ".", "This", "is", "part", "of", "the", "Indexer", "interface", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/txindex.go#L416-L431
train
btcsuite/btcd
blockchain/indexers/txindex.go
TxBlockRegion
func (idx *TxIndex) TxBlockRegion(hash *chainhash.Hash) (*database.BlockRegion, error) { var region *database.BlockRegion err := idx.db.View(func(dbTx database.Tx) error { var err error region, err = dbFetchTxIndexEntry(dbTx, hash) return err }) return region, err }
go
func (idx *TxIndex) TxBlockRegion(hash *chainhash.Hash) (*database.BlockRegion, error) { var region *database.BlockRegion err := idx.db.View(func(dbTx database.Tx) error { var err error region, err = dbFetchTxIndexEntry(dbTx, hash) return err }) return region, err }
[ "func", "(", "idx", "*", "TxIndex", ")", "TxBlockRegion", "(", "hash", "*", "chainhash", ".", "Hash", ")", "(", "*", "database", ".", "BlockRegion", ",", "error", ")", "{", "var", "region", "*", "database", ".", "BlockRegion", "\n", "err", ":=", "idx", ".", "db", ".", "View", "(", "func", "(", "dbTx", "database", ".", "Tx", ")", "error", "{", "var", "err", "error", "\n", "region", ",", "err", "=", "dbFetchTxIndexEntry", "(", "dbTx", ",", "hash", ")", "\n", "return", "err", "\n", "}", ")", "\n", "return", "region", ",", "err", "\n", "}" ]
// TxBlockRegion returns the block region for the provided transaction hash // from the transaction index. The block region can in turn be used to load the // raw transaction bytes. When there is no entry for the provided hash, nil // will be returned for the both the entry and the error. // // This function is safe for concurrent access.
[ "TxBlockRegion", "returns", "the", "block", "region", "for", "the", "provided", "transaction", "hash", "from", "the", "transaction", "index", ".", "The", "block", "region", "can", "in", "turn", "be", "used", "to", "load", "the", "raw", "transaction", "bytes", ".", "When", "there", "is", "no", "entry", "for", "the", "provided", "hash", "nil", "will", "be", "returned", "for", "the", "both", "the", "entry", "and", "the", "error", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/txindex.go#L439-L447
train
btcsuite/btcd
blockchain/indexers/txindex.go
dropBlockIDIndex
func dropBlockIDIndex(db database.DB) error { return db.Update(func(dbTx database.Tx) error { meta := dbTx.Metadata() err := meta.DeleteBucket(idByHashIndexBucketName) if err != nil { return err } return meta.DeleteBucket(hashByIDIndexBucketName) }) }
go
func dropBlockIDIndex(db database.DB) error { return db.Update(func(dbTx database.Tx) error { meta := dbTx.Metadata() err := meta.DeleteBucket(idByHashIndexBucketName) if err != nil { return err } return meta.DeleteBucket(hashByIDIndexBucketName) }) }
[ "func", "dropBlockIDIndex", "(", "db", "database", ".", "DB", ")", "error", "{", "return", "db", ".", "Update", "(", "func", "(", "dbTx", "database", ".", "Tx", ")", "error", "{", "meta", ":=", "dbTx", ".", "Metadata", "(", ")", "\n", "err", ":=", "meta", ".", "DeleteBucket", "(", "idByHashIndexBucketName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "meta", ".", "DeleteBucket", "(", "hashByIDIndexBucketName", ")", "\n", "}", ")", "\n", "}" ]
// dropBlockIDIndex drops the internal block id index.
[ "dropBlockIDIndex", "drops", "the", "internal", "block", "id", "index", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/txindex.go#L461-L471
train
btcsuite/btcd
blockchain/indexers/txindex.go
DropTxIndex
func DropTxIndex(db database.DB, interrupt <-chan struct{}) error { err := dropIndex(db, addrIndexKey, addrIndexName, interrupt) if err != nil { return err } return dropIndex(db, txIndexKey, txIndexName, interrupt) }
go
func DropTxIndex(db database.DB, interrupt <-chan struct{}) error { err := dropIndex(db, addrIndexKey, addrIndexName, interrupt) if err != nil { return err } return dropIndex(db, txIndexKey, txIndexName, interrupt) }
[ "func", "DropTxIndex", "(", "db", "database", ".", "DB", ",", "interrupt", "<-", "chan", "struct", "{", "}", ")", "error", "{", "err", ":=", "dropIndex", "(", "db", ",", "addrIndexKey", ",", "addrIndexName", ",", "interrupt", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "dropIndex", "(", "db", ",", "txIndexKey", ",", "txIndexName", ",", "interrupt", ")", "\n", "}" ]
// DropTxIndex drops the transaction index from the provided database if it // exists. Since the address index relies on it, the address index will also be // dropped when it exists.
[ "DropTxIndex", "drops", "the", "transaction", "index", "from", "the", "provided", "database", "if", "it", "exists", ".", "Since", "the", "address", "index", "relies", "on", "it", "the", "address", "index", "will", "also", "be", "dropped", "when", "it", "exists", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/txindex.go#L476-L483
train
btcsuite/btcd
database/ffldb/ldbtreapiter.go
newLdbTreapIter
func newLdbTreapIter(tx *transaction, slice *util.Range) *ldbTreapIter { iter := tx.pendingKeys.Iterator(slice.Start, slice.Limit) tx.addActiveIter(iter) return &ldbTreapIter{Iterator: iter, tx: tx} }
go
func newLdbTreapIter(tx *transaction, slice *util.Range) *ldbTreapIter { iter := tx.pendingKeys.Iterator(slice.Start, slice.Limit) tx.addActiveIter(iter) return &ldbTreapIter{Iterator: iter, tx: tx} }
[ "func", "newLdbTreapIter", "(", "tx", "*", "transaction", ",", "slice", "*", "util", ".", "Range", ")", "*", "ldbTreapIter", "{", "iter", ":=", "tx", ".", "pendingKeys", ".", "Iterator", "(", "slice", ".", "Start", ",", "slice", ".", "Limit", ")", "\n", "tx", ".", "addActiveIter", "(", "iter", ")", "\n", "return", "&", "ldbTreapIter", "{", "Iterator", ":", "iter", ",", "tx", ":", "tx", "}", "\n", "}" ]
// newLdbTreapIter creates a new treap iterator for the given slice against the // pending keys for the passed transaction and returns it wrapped in an // ldbTreapIter so it can be used as a leveldb iterator. It also adds the new // iterator to the list of active iterators for the transaction.
[ "newLdbTreapIter", "creates", "a", "new", "treap", "iterator", "for", "the", "given", "slice", "against", "the", "pending", "keys", "for", "the", "passed", "transaction", "and", "returns", "it", "wrapped", "in", "an", "ldbTreapIter", "so", "it", "can", "be", "used", "as", "a", "leveldb", "iterator", ".", "It", "also", "adds", "the", "new", "iterator", "to", "the", "list", "of", "active", "iterators", "for", "the", "transaction", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/ldbtreapiter.go#L54-L58
train
btcsuite/btcd
btcjson/walletsvrwscmds.go
NewExportWatchingWalletCmd
func NewExportWatchingWalletCmd(account *string, download *bool) *ExportWatchingWalletCmd { return &ExportWatchingWalletCmd{ Account: account, Download: download, } }
go
func NewExportWatchingWalletCmd(account *string, download *bool) *ExportWatchingWalletCmd { return &ExportWatchingWalletCmd{ Account: account, Download: download, } }
[ "func", "NewExportWatchingWalletCmd", "(", "account", "*", "string", ",", "download", "*", "bool", ")", "*", "ExportWatchingWalletCmd", "{", "return", "&", "ExportWatchingWalletCmd", "{", "Account", ":", "account", ",", "Download", ":", "download", ",", "}", "\n", "}" ]
// NewExportWatchingWalletCmd returns a new instance which can be used to issue // a exportwatchingwallet JSON-RPC command. // // The parameters which are pointers indicate they are optional. Passing nil // for optional parameters will use the default value.
[ "NewExportWatchingWalletCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "exportwatchingwallet", "JSON", "-", "RPC", "command", ".", "The", "parameters", "which", "are", "pointers", "indicate", "they", "are", "optional", ".", "Passing", "nil", "for", "optional", "parameters", "will", "use", "the", "default", "value", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/walletsvrwscmds.go#L34-L39
train
btcsuite/btcd
btcjson/walletsvrwscmds.go
NewListAddressTransactionsCmd
func NewListAddressTransactionsCmd(addresses []string, account *string) *ListAddressTransactionsCmd { return &ListAddressTransactionsCmd{ Addresses: addresses, Account: account, } }
go
func NewListAddressTransactionsCmd(addresses []string, account *string) *ListAddressTransactionsCmd { return &ListAddressTransactionsCmd{ Addresses: addresses, Account: account, } }
[ "func", "NewListAddressTransactionsCmd", "(", "addresses", "[", "]", "string", ",", "account", "*", "string", ")", "*", "ListAddressTransactionsCmd", "{", "return", "&", "ListAddressTransactionsCmd", "{", "Addresses", ":", "addresses", ",", "Account", ":", "account", ",", "}", "\n", "}" ]
// NewListAddressTransactionsCmd returns a new instance which can be used to // issue a listaddresstransactions JSON-RPC command. // // The parameters which are pointers indicate they are optional. Passing nil // for optional parameters will use the default value.
[ "NewListAddressTransactionsCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "listaddresstransactions", "JSON", "-", "RPC", "command", ".", "The", "parameters", "which", "are", "pointers", "indicate", "they", "are", "optional", ".", "Passing", "nil", "for", "optional", "parameters", "will", "use", "the", "default", "value", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/walletsvrwscmds.go#L69-L74
train
btcsuite/btcd
btcjson/walletsvrwscmds.go
NewRecoverAddressesCmd
func NewRecoverAddressesCmd(account string, n int) *RecoverAddressesCmd { return &RecoverAddressesCmd{ Account: account, N: n, } }
go
func NewRecoverAddressesCmd(account string, n int) *RecoverAddressesCmd { return &RecoverAddressesCmd{ Account: account, N: n, } }
[ "func", "NewRecoverAddressesCmd", "(", "account", "string", ",", "n", "int", ")", "*", "RecoverAddressesCmd", "{", "return", "&", "RecoverAddressesCmd", "{", "Account", ":", "account", ",", "N", ":", "n", ",", "}", "\n", "}" ]
// NewRecoverAddressesCmd returns a new instance which can be used to issue a // recoveraddresses JSON-RPC command.
[ "NewRecoverAddressesCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "recoveraddresses", "JSON", "-", "RPC", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/walletsvrwscmds.go#L100-L105
train
btcsuite/btcd
blockchain/merkle.go
nextPowerOfTwo
func nextPowerOfTwo(n int) int { // Return the number if it's already a power of 2. if n&(n-1) == 0 { return n } // Figure out and return the next power of two. exponent := uint(math.Log2(float64(n))) + 1 return 1 << exponent // 2^exponent }
go
func nextPowerOfTwo(n int) int { // Return the number if it's already a power of 2. if n&(n-1) == 0 { return n } // Figure out and return the next power of two. exponent := uint(math.Log2(float64(n))) + 1 return 1 << exponent // 2^exponent }
[ "func", "nextPowerOfTwo", "(", "n", "int", ")", "int", "{", "// Return the number if it's already a power of 2.", "if", "n", "&", "(", "n", "-", "1", ")", "==", "0", "{", "return", "n", "\n", "}", "\n\n", "// Figure out and return the next power of two.", "exponent", ":=", "uint", "(", "math", ".", "Log2", "(", "float64", "(", "n", ")", ")", ")", "+", "1", "\n", "return", "1", "<<", "exponent", "// 2^exponent", "\n", "}" ]
// nextPowerOfTwo returns the next highest power of two from a given number if // it is not already a power of two. This is a helper function used during the // calculation of a merkle tree.
[ "nextPowerOfTwo", "returns", "the", "next", "highest", "power", "of", "two", "from", "a", "given", "number", "if", "it", "is", "not", "already", "a", "power", "of", "two", ".", "This", "is", "a", "helper", "function", "used", "during", "the", "calculation", "of", "a", "merkle", "tree", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/merkle.go#L47-L56
train
btcsuite/btcd
blockchain/merkle.go
HashMerkleBranches
func HashMerkleBranches(left *chainhash.Hash, right *chainhash.Hash) *chainhash.Hash { // Concatenate the left and right nodes. var hash [chainhash.HashSize * 2]byte copy(hash[:chainhash.HashSize], left[:]) copy(hash[chainhash.HashSize:], right[:]) newHash := chainhash.DoubleHashH(hash[:]) return &newHash }
go
func HashMerkleBranches(left *chainhash.Hash, right *chainhash.Hash) *chainhash.Hash { // Concatenate the left and right nodes. var hash [chainhash.HashSize * 2]byte copy(hash[:chainhash.HashSize], left[:]) copy(hash[chainhash.HashSize:], right[:]) newHash := chainhash.DoubleHashH(hash[:]) return &newHash }
[ "func", "HashMerkleBranches", "(", "left", "*", "chainhash", ".", "Hash", ",", "right", "*", "chainhash", ".", "Hash", ")", "*", "chainhash", ".", "Hash", "{", "// Concatenate the left and right nodes.", "var", "hash", "[", "chainhash", ".", "HashSize", "*", "2", "]", "byte", "\n", "copy", "(", "hash", "[", ":", "chainhash", ".", "HashSize", "]", ",", "left", "[", ":", "]", ")", "\n", "copy", "(", "hash", "[", "chainhash", ".", "HashSize", ":", "]", ",", "right", "[", ":", "]", ")", "\n\n", "newHash", ":=", "chainhash", ".", "DoubleHashH", "(", "hash", "[", ":", "]", ")", "\n", "return", "&", "newHash", "\n", "}" ]
// HashMerkleBranches takes two hashes, treated as the left and right tree // nodes, and returns the hash of their concatenation. This is a helper // function used to aid in the generation of a merkle tree.
[ "HashMerkleBranches", "takes", "two", "hashes", "treated", "as", "the", "left", "and", "right", "tree", "nodes", "and", "returns", "the", "hash", "of", "their", "concatenation", ".", "This", "is", "a", "helper", "function", "used", "to", "aid", "in", "the", "generation", "of", "a", "merkle", "tree", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/merkle.go#L61-L69
train
btcsuite/btcd
btcjson/walletsvrcmds.go
NewAddMultisigAddressCmd
func NewAddMultisigAddressCmd(nRequired int, keys []string, account *string) *AddMultisigAddressCmd { return &AddMultisigAddressCmd{ NRequired: nRequired, Keys: keys, Account: account, } }
go
func NewAddMultisigAddressCmd(nRequired int, keys []string, account *string) *AddMultisigAddressCmd { return &AddMultisigAddressCmd{ NRequired: nRequired, Keys: keys, Account: account, } }
[ "func", "NewAddMultisigAddressCmd", "(", "nRequired", "int", ",", "keys", "[", "]", "string", ",", "account", "*", "string", ")", "*", "AddMultisigAddressCmd", "{", "return", "&", "AddMultisigAddressCmd", "{", "NRequired", ":", "nRequired", ",", "Keys", ":", "keys", ",", "Account", ":", "account", ",", "}", "\n", "}" ]
// NewAddMultisigAddressCmd returns a new instance which can be used to issue a // addmultisigaddress JSON-RPC command. // // The parameters which are pointers indicate they are optional. Passing nil // for optional parameters will use the default value.
[ "NewAddMultisigAddressCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "addmultisigaddress", "JSON", "-", "RPC", "command", ".", "The", "parameters", "which", "are", "pointers", "indicate", "they", "are", "optional", ".", "Passing", "nil", "for", "optional", "parameters", "will", "use", "the", "default", "value", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/walletsvrcmds.go#L22-L28
train
btcsuite/btcd
btcjson/walletsvrcmds.go
NewCreateMultisigCmd
func NewCreateMultisigCmd(nRequired int, keys []string) *CreateMultisigCmd { return &CreateMultisigCmd{ NRequired: nRequired, Keys: keys, } }
go
func NewCreateMultisigCmd(nRequired int, keys []string) *CreateMultisigCmd { return &CreateMultisigCmd{ NRequired: nRequired, Keys: keys, } }
[ "func", "NewCreateMultisigCmd", "(", "nRequired", "int", ",", "keys", "[", "]", "string", ")", "*", "CreateMultisigCmd", "{", "return", "&", "CreateMultisigCmd", "{", "NRequired", ":", "nRequired", ",", "Keys", ":", "keys", ",", "}", "\n", "}" ]
// NewCreateMultisigCmd returns a new instance which can be used to issue a // createmultisig JSON-RPC command.
[ "NewCreateMultisigCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "createmultisig", "JSON", "-", "RPC", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/walletsvrcmds.go#L51-L56
train
btcsuite/btcd
btcjson/walletsvrcmds.go
NewGetBalanceCmd
func NewGetBalanceCmd(account *string, minConf *int) *GetBalanceCmd { return &GetBalanceCmd{ Account: account, MinConf: minConf, } }
go
func NewGetBalanceCmd(account *string, minConf *int) *GetBalanceCmd { return &GetBalanceCmd{ Account: account, MinConf: minConf, } }
[ "func", "NewGetBalanceCmd", "(", "account", "*", "string", ",", "minConf", "*", "int", ")", "*", "GetBalanceCmd", "{", "return", "&", "GetBalanceCmd", "{", "Account", ":", "account", ",", "MinConf", ":", "minConf", ",", "}", "\n", "}" ]
// NewGetBalanceCmd returns a new instance which can be used to issue a // getbalance JSON-RPC command. // // The parameters which are pointers indicate they are optional. Passing nil // for optional parameters will use the default value.
[ "NewGetBalanceCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "getbalance", "JSON", "-", "RPC", "command", ".", "The", "parameters", "which", "are", "pointers", "indicate", "they", "are", "optional", ".", "Passing", "nil", "for", "optional", "parameters", "will", "use", "the", "default", "value", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/walletsvrcmds.go#L160-L165
train
btcsuite/btcd
btcjson/walletsvrcmds.go
NewGetReceivedByAccountCmd
func NewGetReceivedByAccountCmd(account string, minConf *int) *GetReceivedByAccountCmd { return &GetReceivedByAccountCmd{ Account: account, MinConf: minConf, } }
go
func NewGetReceivedByAccountCmd(account string, minConf *int) *GetReceivedByAccountCmd { return &GetReceivedByAccountCmd{ Account: account, MinConf: minConf, } }
[ "func", "NewGetReceivedByAccountCmd", "(", "account", "string", ",", "minConf", "*", "int", ")", "*", "GetReceivedByAccountCmd", "{", "return", "&", "GetReceivedByAccountCmd", "{", "Account", ":", "account", ",", "MinConf", ":", "minConf", ",", "}", "\n", "}" ]
// NewGetReceivedByAccountCmd returns a new instance which can be used to issue // a getreceivedbyaccount JSON-RPC command. // // The parameters which are pointers indicate they are optional. Passing nil // for optional parameters will use the default value.
[ "NewGetReceivedByAccountCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "getreceivedbyaccount", "JSON", "-", "RPC", "command", ".", "The", "parameters", "which", "are", "pointers", "indicate", "they", "are", "optional", ".", "Passing", "nil", "for", "optional", "parameters", "will", "use", "the", "default", "value", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/walletsvrcmds.go#L210-L215
train
btcsuite/btcd
btcjson/walletsvrcmds.go
NewGetReceivedByAddressCmd
func NewGetReceivedByAddressCmd(address string, minConf *int) *GetReceivedByAddressCmd { return &GetReceivedByAddressCmd{ Address: address, MinConf: minConf, } }
go
func NewGetReceivedByAddressCmd(address string, minConf *int) *GetReceivedByAddressCmd { return &GetReceivedByAddressCmd{ Address: address, MinConf: minConf, } }
[ "func", "NewGetReceivedByAddressCmd", "(", "address", "string", ",", "minConf", "*", "int", ")", "*", "GetReceivedByAddressCmd", "{", "return", "&", "GetReceivedByAddressCmd", "{", "Address", ":", "address", ",", "MinConf", ":", "minConf", ",", "}", "\n", "}" ]
// NewGetReceivedByAddressCmd returns a new instance which can be used to issue // a getreceivedbyaddress JSON-RPC command. // // The parameters which are pointers indicate they are optional. Passing nil // for optional parameters will use the default value.
[ "NewGetReceivedByAddressCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "getreceivedbyaddress", "JSON", "-", "RPC", "command", ".", "The", "parameters", "which", "are", "pointers", "indicate", "they", "are", "optional", ".", "Passing", "nil", "for", "optional", "parameters", "will", "use", "the", "default", "value", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/walletsvrcmds.go#L228-L233
train
btcsuite/btcd
btcjson/walletsvrcmds.go
NewGetTransactionCmd
func NewGetTransactionCmd(txHash string, includeWatchOnly *bool) *GetTransactionCmd { return &GetTransactionCmd{ Txid: txHash, IncludeWatchOnly: includeWatchOnly, } }
go
func NewGetTransactionCmd(txHash string, includeWatchOnly *bool) *GetTransactionCmd { return &GetTransactionCmd{ Txid: txHash, IncludeWatchOnly: includeWatchOnly, } }
[ "func", "NewGetTransactionCmd", "(", "txHash", "string", ",", "includeWatchOnly", "*", "bool", ")", "*", "GetTransactionCmd", "{", "return", "&", "GetTransactionCmd", "{", "Txid", ":", "txHash", ",", "IncludeWatchOnly", ":", "includeWatchOnly", ",", "}", "\n", "}" ]
// NewGetTransactionCmd returns a new instance which can be used to issue a // gettransaction JSON-RPC command. // // The parameters which are pointers indicate they are optional. Passing nil // for optional parameters will use the default value.
[ "NewGetTransactionCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "gettransaction", "JSON", "-", "RPC", "command", ".", "The", "parameters", "which", "are", "pointers", "indicate", "they", "are", "optional", ".", "Passing", "nil", "for", "optional", "parameters", "will", "use", "the", "default", "value", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/walletsvrcmds.go#L246-L251
train
btcsuite/btcd
btcjson/walletsvrcmds.go
NewImportPrivKeyCmd
func NewImportPrivKeyCmd(privKey string, label *string, rescan *bool) *ImportPrivKeyCmd { return &ImportPrivKeyCmd{ PrivKey: privKey, Label: label, Rescan: rescan, } }
go
func NewImportPrivKeyCmd(privKey string, label *string, rescan *bool) *ImportPrivKeyCmd { return &ImportPrivKeyCmd{ PrivKey: privKey, Label: label, Rescan: rescan, } }
[ "func", "NewImportPrivKeyCmd", "(", "privKey", "string", ",", "label", "*", "string", ",", "rescan", "*", "bool", ")", "*", "ImportPrivKeyCmd", "{", "return", "&", "ImportPrivKeyCmd", "{", "PrivKey", ":", "privKey", ",", "Label", ":", "label", ",", "Rescan", ":", "rescan", ",", "}", "\n", "}" ]
// NewImportPrivKeyCmd returns a new instance which can be used to issue a // importprivkey JSON-RPC command. // // The parameters which are pointers indicate they are optional. Passing nil // for optional parameters will use the default value.
[ "NewImportPrivKeyCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "importprivkey", "JSON", "-", "RPC", "command", ".", "The", "parameters", "which", "are", "pointers", "indicate", "they", "are", "optional", ".", "Passing", "nil", "for", "optional", "parameters", "will", "use", "the", "default", "value", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/walletsvrcmds.go#L274-L280
train
btcsuite/btcd
btcjson/walletsvrcmds.go
NewListReceivedByAccountCmd
func NewListReceivedByAccountCmd(minConf *int, includeEmpty, includeWatchOnly *bool) *ListReceivedByAccountCmd { return &ListReceivedByAccountCmd{ MinConf: minConf, IncludeEmpty: includeEmpty, IncludeWatchOnly: includeWatchOnly, } }
go
func NewListReceivedByAccountCmd(minConf *int, includeEmpty, includeWatchOnly *bool) *ListReceivedByAccountCmd { return &ListReceivedByAccountCmd{ MinConf: minConf, IncludeEmpty: includeEmpty, IncludeWatchOnly: includeWatchOnly, } }
[ "func", "NewListReceivedByAccountCmd", "(", "minConf", "*", "int", ",", "includeEmpty", ",", "includeWatchOnly", "*", "bool", ")", "*", "ListReceivedByAccountCmd", "{", "return", "&", "ListReceivedByAccountCmd", "{", "MinConf", ":", "minConf", ",", "IncludeEmpty", ":", "includeEmpty", ",", "IncludeWatchOnly", ":", "includeWatchOnly", ",", "}", "\n", "}" ]
// NewListReceivedByAccountCmd returns a new instance which can be used to issue // a listreceivedbyaccount JSON-RPC command. // // The parameters which are pointers indicate they are optional. Passing nil // for optional parameters will use the default value.
[ "NewListReceivedByAccountCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "listreceivedbyaccount", "JSON", "-", "RPC", "command", ".", "The", "parameters", "which", "are", "pointers", "indicate", "they", "are", "optional", ".", "Passing", "nil", "for", "optional", "parameters", "will", "use", "the", "default", "value", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/walletsvrcmds.go#L344-L350
train
btcsuite/btcd
btcjson/walletsvrcmds.go
NewListReceivedByAddressCmd
func NewListReceivedByAddressCmd(minConf *int, includeEmpty, includeWatchOnly *bool) *ListReceivedByAddressCmd { return &ListReceivedByAddressCmd{ MinConf: minConf, IncludeEmpty: includeEmpty, IncludeWatchOnly: includeWatchOnly, } }
go
func NewListReceivedByAddressCmd(minConf *int, includeEmpty, includeWatchOnly *bool) *ListReceivedByAddressCmd { return &ListReceivedByAddressCmd{ MinConf: minConf, IncludeEmpty: includeEmpty, IncludeWatchOnly: includeWatchOnly, } }
[ "func", "NewListReceivedByAddressCmd", "(", "minConf", "*", "int", ",", "includeEmpty", ",", "includeWatchOnly", "*", "bool", ")", "*", "ListReceivedByAddressCmd", "{", "return", "&", "ListReceivedByAddressCmd", "{", "MinConf", ":", "minConf", ",", "IncludeEmpty", ":", "includeEmpty", ",", "IncludeWatchOnly", ":", "includeWatchOnly", ",", "}", "\n", "}" ]
// NewListReceivedByAddressCmd returns a new instance which can be used to issue // a listreceivedbyaddress JSON-RPC command. // // The parameters which are pointers indicate they are optional. Passing nil // for optional parameters will use the default value.
[ "NewListReceivedByAddressCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "listreceivedbyaddress", "JSON", "-", "RPC", "command", ".", "The", "parameters", "which", "are", "pointers", "indicate", "they", "are", "optional", ".", "Passing", "nil", "for", "optional", "parameters", "will", "use", "the", "default", "value", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/walletsvrcmds.go#L364-L370
train
btcsuite/btcd
btcjson/walletsvrcmds.go
NewListSinceBlockCmd
func NewListSinceBlockCmd(blockHash *string, targetConfirms *int, includeWatchOnly *bool) *ListSinceBlockCmd { return &ListSinceBlockCmd{ BlockHash: blockHash, TargetConfirmations: targetConfirms, IncludeWatchOnly: includeWatchOnly, } }
go
func NewListSinceBlockCmd(blockHash *string, targetConfirms *int, includeWatchOnly *bool) *ListSinceBlockCmd { return &ListSinceBlockCmd{ BlockHash: blockHash, TargetConfirmations: targetConfirms, IncludeWatchOnly: includeWatchOnly, } }
[ "func", "NewListSinceBlockCmd", "(", "blockHash", "*", "string", ",", "targetConfirms", "*", "int", ",", "includeWatchOnly", "*", "bool", ")", "*", "ListSinceBlockCmd", "{", "return", "&", "ListSinceBlockCmd", "{", "BlockHash", ":", "blockHash", ",", "TargetConfirmations", ":", "targetConfirms", ",", "IncludeWatchOnly", ":", "includeWatchOnly", ",", "}", "\n", "}" ]
// NewListSinceBlockCmd returns a new instance which can be used to issue a // listsinceblock JSON-RPC command. // // The parameters which are pointers indicate they are optional. Passing nil // for optional parameters will use the default value.
[ "NewListSinceBlockCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "listsinceblock", "JSON", "-", "RPC", "command", ".", "The", "parameters", "which", "are", "pointers", "indicate", "they", "are", "optional", ".", "Passing", "nil", "for", "optional", "parameters", "will", "use", "the", "default", "value", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/walletsvrcmds.go#L384-L390
train
btcsuite/btcd
btcjson/walletsvrcmds.go
NewListTransactionsCmd
func NewListTransactionsCmd(account *string, count, from *int, includeWatchOnly *bool) *ListTransactionsCmd { return &ListTransactionsCmd{ Account: account, Count: count, From: from, IncludeWatchOnly: includeWatchOnly, } }
go
func NewListTransactionsCmd(account *string, count, from *int, includeWatchOnly *bool) *ListTransactionsCmd { return &ListTransactionsCmd{ Account: account, Count: count, From: from, IncludeWatchOnly: includeWatchOnly, } }
[ "func", "NewListTransactionsCmd", "(", "account", "*", "string", ",", "count", ",", "from", "*", "int", ",", "includeWatchOnly", "*", "bool", ")", "*", "ListTransactionsCmd", "{", "return", "&", "ListTransactionsCmd", "{", "Account", ":", "account", ",", "Count", ":", "count", ",", "From", ":", "from", ",", "IncludeWatchOnly", ":", "includeWatchOnly", ",", "}", "\n", "}" ]
// NewListTransactionsCmd returns a new instance which can be used to issue a // listtransactions JSON-RPC command. // // The parameters which are pointers indicate they are optional. Passing nil // for optional parameters will use the default value.
[ "NewListTransactionsCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "listtransactions", "JSON", "-", "RPC", "command", ".", "The", "parameters", "which", "are", "pointers", "indicate", "they", "are", "optional", ".", "Passing", "nil", "for", "optional", "parameters", "will", "use", "the", "default", "value", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/walletsvrcmds.go#L405-L412
train
btcsuite/btcd
btcjson/walletsvrcmds.go
NewListUnspentCmd
func NewListUnspentCmd(minConf, maxConf *int, addresses *[]string) *ListUnspentCmd { return &ListUnspentCmd{ MinConf: minConf, MaxConf: maxConf, Addresses: addresses, } }
go
func NewListUnspentCmd(minConf, maxConf *int, addresses *[]string) *ListUnspentCmd { return &ListUnspentCmd{ MinConf: minConf, MaxConf: maxConf, Addresses: addresses, } }
[ "func", "NewListUnspentCmd", "(", "minConf", ",", "maxConf", "*", "int", ",", "addresses", "*", "[", "]", "string", ")", "*", "ListUnspentCmd", "{", "return", "&", "ListUnspentCmd", "{", "MinConf", ":", "minConf", ",", "MaxConf", ":", "maxConf", ",", "Addresses", ":", "addresses", ",", "}", "\n", "}" ]
// NewListUnspentCmd returns a new instance which can be used to issue a // listunspent JSON-RPC command. // // The parameters which are pointers indicate they are optional. Passing nil // for optional parameters will use the default value.
[ "NewListUnspentCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "listunspent", "JSON", "-", "RPC", "command", ".", "The", "parameters", "which", "are", "pointers", "indicate", "they", "are", "optional", ".", "Passing", "nil", "for", "optional", "parameters", "will", "use", "the", "default", "value", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/walletsvrcmds.go#L426-L432
train
btcsuite/btcd
btcjson/walletsvrcmds.go
NewLockUnspentCmd
func NewLockUnspentCmd(unlock bool, transactions []TransactionInput) *LockUnspentCmd { return &LockUnspentCmd{ Unlock: unlock, Transactions: transactions, } }
go
func NewLockUnspentCmd(unlock bool, transactions []TransactionInput) *LockUnspentCmd { return &LockUnspentCmd{ Unlock: unlock, Transactions: transactions, } }
[ "func", "NewLockUnspentCmd", "(", "unlock", "bool", ",", "transactions", "[", "]", "TransactionInput", ")", "*", "LockUnspentCmd", "{", "return", "&", "LockUnspentCmd", "{", "Unlock", ":", "unlock", ",", "Transactions", ":", "transactions", ",", "}", "\n", "}" ]
// NewLockUnspentCmd returns a new instance which can be used to issue a // lockunspent JSON-RPC command.
[ "NewLockUnspentCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "lockunspent", "JSON", "-", "RPC", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/walletsvrcmds.go#L442-L447
train
btcsuite/btcd
btcjson/walletsvrcmds.go
NewMoveCmd
func NewMoveCmd(fromAccount, toAccount string, amount float64, minConf *int, comment *string) *MoveCmd { return &MoveCmd{ FromAccount: fromAccount, ToAccount: toAccount, Amount: amount, MinConf: minConf, Comment: comment, } }
go
func NewMoveCmd(fromAccount, toAccount string, amount float64, minConf *int, comment *string) *MoveCmd { return &MoveCmd{ FromAccount: fromAccount, ToAccount: toAccount, Amount: amount, MinConf: minConf, Comment: comment, } }
[ "func", "NewMoveCmd", "(", "fromAccount", ",", "toAccount", "string", ",", "amount", "float64", ",", "minConf", "*", "int", ",", "comment", "*", "string", ")", "*", "MoveCmd", "{", "return", "&", "MoveCmd", "{", "FromAccount", ":", "fromAccount", ",", "ToAccount", ":", "toAccount", ",", "Amount", ":", "amount", ",", "MinConf", ":", "minConf", ",", "Comment", ":", "comment", ",", "}", "\n", "}" ]
// NewMoveCmd returns a new instance which can be used to issue a move JSON-RPC // command. // // The parameters which are pointers indicate they are optional. Passing nil // for optional parameters will use the default value.
[ "NewMoveCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "move", "JSON", "-", "RPC", "command", ".", "The", "parameters", "which", "are", "pointers", "indicate", "they", "are", "optional", ".", "Passing", "nil", "for", "optional", "parameters", "will", "use", "the", "default", "value", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/walletsvrcmds.go#L463-L471
train
btcsuite/btcd
btcjson/walletsvrcmds.go
NewSendFromCmd
func NewSendFromCmd(fromAccount, toAddress string, amount float64, minConf *int, comment, commentTo *string) *SendFromCmd { return &SendFromCmd{ FromAccount: fromAccount, ToAddress: toAddress, Amount: amount, MinConf: minConf, Comment: comment, CommentTo: commentTo, } }
go
func NewSendFromCmd(fromAccount, toAddress string, amount float64, minConf *int, comment, commentTo *string) *SendFromCmd { return &SendFromCmd{ FromAccount: fromAccount, ToAddress: toAddress, Amount: amount, MinConf: minConf, Comment: comment, CommentTo: commentTo, } }
[ "func", "NewSendFromCmd", "(", "fromAccount", ",", "toAddress", "string", ",", "amount", "float64", ",", "minConf", "*", "int", ",", "comment", ",", "commentTo", "*", "string", ")", "*", "SendFromCmd", "{", "return", "&", "SendFromCmd", "{", "FromAccount", ":", "fromAccount", ",", "ToAddress", ":", "toAddress", ",", "Amount", ":", "amount", ",", "MinConf", ":", "minConf", ",", "Comment", ":", "comment", ",", "CommentTo", ":", "commentTo", ",", "}", "\n", "}" ]
// NewSendFromCmd returns a new instance which can be used to issue a sendfrom // JSON-RPC command. // // The parameters which are pointers indicate they are optional. Passing nil // for optional parameters will use the default value.
[ "NewSendFromCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "sendfrom", "JSON", "-", "RPC", "command", ".", "The", "parameters", "which", "are", "pointers", "indicate", "they", "are", "optional", ".", "Passing", "nil", "for", "optional", "parameters", "will", "use", "the", "default", "value", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/walletsvrcmds.go#L488-L497
train
btcsuite/btcd
btcjson/walletsvrcmds.go
NewSendManyCmd
func NewSendManyCmd(fromAccount string, amounts map[string]float64, minConf *int, comment *string) *SendManyCmd { return &SendManyCmd{ FromAccount: fromAccount, Amounts: amounts, MinConf: minConf, Comment: comment, } }
go
func NewSendManyCmd(fromAccount string, amounts map[string]float64, minConf *int, comment *string) *SendManyCmd { return &SendManyCmd{ FromAccount: fromAccount, Amounts: amounts, MinConf: minConf, Comment: comment, } }
[ "func", "NewSendManyCmd", "(", "fromAccount", "string", ",", "amounts", "map", "[", "string", "]", "float64", ",", "minConf", "*", "int", ",", "comment", "*", "string", ")", "*", "SendManyCmd", "{", "return", "&", "SendManyCmd", "{", "FromAccount", ":", "fromAccount", ",", "Amounts", ":", "amounts", ",", "MinConf", ":", "minConf", ",", "Comment", ":", "comment", ",", "}", "\n", "}" ]
// NewSendManyCmd returns a new instance which can be used to issue a sendmany // JSON-RPC command. // // The parameters which are pointers indicate they are optional. Passing nil // for optional parameters will use the default value.
[ "NewSendManyCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "sendmany", "JSON", "-", "RPC", "command", ".", "The", "parameters", "which", "are", "pointers", "indicate", "they", "are", "optional", ".", "Passing", "nil", "for", "optional", "parameters", "will", "use", "the", "default", "value", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/walletsvrcmds.go#L512-L519
train
btcsuite/btcd
btcjson/walletsvrcmds.go
NewSendToAddressCmd
func NewSendToAddressCmd(address string, amount float64, comment, commentTo *string) *SendToAddressCmd { return &SendToAddressCmd{ Address: address, Amount: amount, Comment: comment, CommentTo: commentTo, } }
go
func NewSendToAddressCmd(address string, amount float64, comment, commentTo *string) *SendToAddressCmd { return &SendToAddressCmd{ Address: address, Amount: amount, Comment: comment, CommentTo: commentTo, } }
[ "func", "NewSendToAddressCmd", "(", "address", "string", ",", "amount", "float64", ",", "comment", ",", "commentTo", "*", "string", ")", "*", "SendToAddressCmd", "{", "return", "&", "SendToAddressCmd", "{", "Address", ":", "address", ",", "Amount", ":", "amount", ",", "Comment", ":", "comment", ",", "CommentTo", ":", "commentTo", ",", "}", "\n", "}" ]
// NewSendToAddressCmd returns a new instance which can be used to issue a // sendtoaddress JSON-RPC command. // // The parameters which are pointers indicate they are optional. Passing nil // for optional parameters will use the default value.
[ "NewSendToAddressCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "sendtoaddress", "JSON", "-", "RPC", "command", ".", "The", "parameters", "which", "are", "pointers", "indicate", "they", "are", "optional", ".", "Passing", "nil", "for", "optional", "parameters", "will", "use", "the", "default", "value", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/walletsvrcmds.go#L534-L541
train
btcsuite/btcd
btcjson/walletsvrcmds.go
NewSetAccountCmd
func NewSetAccountCmd(address, account string) *SetAccountCmd { return &SetAccountCmd{ Address: address, Account: account, } }
go
func NewSetAccountCmd(address, account string) *SetAccountCmd { return &SetAccountCmd{ Address: address, Account: account, } }
[ "func", "NewSetAccountCmd", "(", "address", ",", "account", "string", ")", "*", "SetAccountCmd", "{", "return", "&", "SetAccountCmd", "{", "Address", ":", "address", ",", "Account", ":", "account", ",", "}", "\n", "}" ]
// NewSetAccountCmd returns a new instance which can be used to issue a // setaccount JSON-RPC command.
[ "NewSetAccountCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "setaccount", "JSON", "-", "RPC", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/walletsvrcmds.go#L551-L556
train
btcsuite/btcd
btcjson/walletsvrcmds.go
NewSignMessageCmd
func NewSignMessageCmd(address, message string) *SignMessageCmd { return &SignMessageCmd{ Address: address, Message: message, } }
go
func NewSignMessageCmd(address, message string) *SignMessageCmd { return &SignMessageCmd{ Address: address, Message: message, } }
[ "func", "NewSignMessageCmd", "(", "address", ",", "message", "string", ")", "*", "SignMessageCmd", "{", "return", "&", "SignMessageCmd", "{", "Address", ":", "address", ",", "Message", ":", "message", ",", "}", "\n", "}" ]
// NewSignMessageCmd returns a new instance which can be used to issue a // signmessage JSON-RPC command.
[ "NewSignMessageCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "signmessage", "JSON", "-", "RPC", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/walletsvrcmds.go#L579-L584
train
btcsuite/btcd
btcjson/walletsvrcmds.go
NewSignRawTransactionCmd
func NewSignRawTransactionCmd(hexEncodedTx string, inputs *[]RawTxInput, privKeys *[]string, flags *string) *SignRawTransactionCmd { return &SignRawTransactionCmd{ RawTx: hexEncodedTx, Inputs: inputs, PrivKeys: privKeys, Flags: flags, } }
go
func NewSignRawTransactionCmd(hexEncodedTx string, inputs *[]RawTxInput, privKeys *[]string, flags *string) *SignRawTransactionCmd { return &SignRawTransactionCmd{ RawTx: hexEncodedTx, Inputs: inputs, PrivKeys: privKeys, Flags: flags, } }
[ "func", "NewSignRawTransactionCmd", "(", "hexEncodedTx", "string", ",", "inputs", "*", "[", "]", "RawTxInput", ",", "privKeys", "*", "[", "]", "string", ",", "flags", "*", "string", ")", "*", "SignRawTransactionCmd", "{", "return", "&", "SignRawTransactionCmd", "{", "RawTx", ":", "hexEncodedTx", ",", "Inputs", ":", "inputs", ",", "PrivKeys", ":", "privKeys", ",", "Flags", ":", "flags", ",", "}", "\n", "}" ]
// NewSignRawTransactionCmd returns a new instance which can be used to issue a // signrawtransaction JSON-RPC command. // // The parameters which are pointers indicate they are optional. Passing nil // for optional parameters will use the default value.
[ "NewSignRawTransactionCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "signrawtransaction", "JSON", "-", "RPC", "command", ".", "The", "parameters", "which", "are", "pointers", "indicate", "they", "are", "optional", ".", "Passing", "nil", "for", "optional", "parameters", "will", "use", "the", "default", "value", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/walletsvrcmds.go#L608-L615
train
btcsuite/btcd
btcjson/walletsvrcmds.go
NewWalletPassphraseCmd
func NewWalletPassphraseCmd(passphrase string, timeout int64) *WalletPassphraseCmd { return &WalletPassphraseCmd{ Passphrase: passphrase, Timeout: timeout, } }
go
func NewWalletPassphraseCmd(passphrase string, timeout int64) *WalletPassphraseCmd { return &WalletPassphraseCmd{ Passphrase: passphrase, Timeout: timeout, } }
[ "func", "NewWalletPassphraseCmd", "(", "passphrase", "string", ",", "timeout", "int64", ")", "*", "WalletPassphraseCmd", "{", "return", "&", "WalletPassphraseCmd", "{", "Passphrase", ":", "passphrase", ",", "Timeout", ":", "timeout", ",", "}", "\n", "}" ]
// NewWalletPassphraseCmd returns a new instance which can be used to issue a // walletpassphrase JSON-RPC command.
[ "NewWalletPassphraseCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "walletpassphrase", "JSON", "-", "RPC", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/walletsvrcmds.go#L634-L639
train
btcsuite/btcd
btcjson/walletsvrcmds.go
NewWalletPassphraseChangeCmd
func NewWalletPassphraseChangeCmd(oldPassphrase, newPassphrase string) *WalletPassphraseChangeCmd { return &WalletPassphraseChangeCmd{ OldPassphrase: oldPassphrase, NewPassphrase: newPassphrase, } }
go
func NewWalletPassphraseChangeCmd(oldPassphrase, newPassphrase string) *WalletPassphraseChangeCmd { return &WalletPassphraseChangeCmd{ OldPassphrase: oldPassphrase, NewPassphrase: newPassphrase, } }
[ "func", "NewWalletPassphraseChangeCmd", "(", "oldPassphrase", ",", "newPassphrase", "string", ")", "*", "WalletPassphraseChangeCmd", "{", "return", "&", "WalletPassphraseChangeCmd", "{", "OldPassphrase", ":", "oldPassphrase", ",", "NewPassphrase", ":", "newPassphrase", ",", "}", "\n", "}" ]
// NewWalletPassphraseChangeCmd returns a new instance which can be used to // issue a walletpassphrasechange JSON-RPC command.
[ "NewWalletPassphraseChangeCmd", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "walletpassphrasechange", "JSON", "-", "RPC", "command", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/walletsvrcmds.go#L649-L654
train
btcsuite/btcd
blockchain/utxoviewpoint.go
Clone
func (entry *UtxoEntry) Clone() *UtxoEntry { if entry == nil { return nil } return &UtxoEntry{ amount: entry.amount, pkScript: entry.pkScript, blockHeight: entry.blockHeight, packedFlags: entry.packedFlags, } }
go
func (entry *UtxoEntry) Clone() *UtxoEntry { if entry == nil { return nil } return &UtxoEntry{ amount: entry.amount, pkScript: entry.pkScript, blockHeight: entry.blockHeight, packedFlags: entry.packedFlags, } }
[ "func", "(", "entry", "*", "UtxoEntry", ")", "Clone", "(", ")", "*", "UtxoEntry", "{", "if", "entry", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "return", "&", "UtxoEntry", "{", "amount", ":", "entry", ".", "amount", ",", "pkScript", ":", "entry", ".", "pkScript", ",", "blockHeight", ":", "entry", ".", "blockHeight", ",", "packedFlags", ":", "entry", ".", "packedFlags", ",", "}", "\n", "}" ]
// Clone returns a shallow copy of the utxo entry.
[ "Clone", "returns", "a", "shallow", "copy", "of", "the", "utxo", "entry", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/utxoviewpoint.go#L101-L112
train
btcsuite/btcd
blockchain/utxoviewpoint.go
LookupEntry
func (view *UtxoViewpoint) LookupEntry(outpoint wire.OutPoint) *UtxoEntry { return view.entries[outpoint] }
go
func (view *UtxoViewpoint) LookupEntry(outpoint wire.OutPoint) *UtxoEntry { return view.entries[outpoint] }
[ "func", "(", "view", "*", "UtxoViewpoint", ")", "LookupEntry", "(", "outpoint", "wire", ".", "OutPoint", ")", "*", "UtxoEntry", "{", "return", "view", ".", "entries", "[", "outpoint", "]", "\n", "}" ]
// LookupEntry returns information about a given transaction output according to // the current state of the view. It will return nil if the passed output does // not exist in the view or is otherwise not available such as when it has been // disconnected during a reorg.
[ "LookupEntry", "returns", "information", "about", "a", "given", "transaction", "output", "according", "to", "the", "current", "state", "of", "the", "view", ".", "It", "will", "return", "nil", "if", "the", "passed", "output", "does", "not", "exist", "in", "the", "view", "or", "is", "otherwise", "not", "available", "such", "as", "when", "it", "has", "been", "disconnected", "during", "a", "reorg", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/utxoviewpoint.go#L142-L144
train
btcsuite/btcd
blockchain/utxoviewpoint.go
addTxOut
func (view *UtxoViewpoint) addTxOut(outpoint wire.OutPoint, txOut *wire.TxOut, isCoinBase bool, blockHeight int32) { // Don't add provably unspendable outputs. if txscript.IsUnspendable(txOut.PkScript) { return } // Update existing entries. All fields are updated because it's // possible (although extremely unlikely) that the existing entry is // being replaced by a different transaction with the same hash. This // is allowed so long as the previous transaction is fully spent. entry := view.LookupEntry(outpoint) if entry == nil { entry = new(UtxoEntry) view.entries[outpoint] = entry } entry.amount = txOut.Value entry.pkScript = txOut.PkScript entry.blockHeight = blockHeight entry.packedFlags = tfModified if isCoinBase { entry.packedFlags |= tfCoinBase } }
go
func (view *UtxoViewpoint) addTxOut(outpoint wire.OutPoint, txOut *wire.TxOut, isCoinBase bool, blockHeight int32) { // Don't add provably unspendable outputs. if txscript.IsUnspendable(txOut.PkScript) { return } // Update existing entries. All fields are updated because it's // possible (although extremely unlikely) that the existing entry is // being replaced by a different transaction with the same hash. This // is allowed so long as the previous transaction is fully spent. entry := view.LookupEntry(outpoint) if entry == nil { entry = new(UtxoEntry) view.entries[outpoint] = entry } entry.amount = txOut.Value entry.pkScript = txOut.PkScript entry.blockHeight = blockHeight entry.packedFlags = tfModified if isCoinBase { entry.packedFlags |= tfCoinBase } }
[ "func", "(", "view", "*", "UtxoViewpoint", ")", "addTxOut", "(", "outpoint", "wire", ".", "OutPoint", ",", "txOut", "*", "wire", ".", "TxOut", ",", "isCoinBase", "bool", ",", "blockHeight", "int32", ")", "{", "// Don't add provably unspendable outputs.", "if", "txscript", ".", "IsUnspendable", "(", "txOut", ".", "PkScript", ")", "{", "return", "\n", "}", "\n\n", "// Update existing entries. All fields are updated because it's", "// possible (although extremely unlikely) that the existing entry is", "// being replaced by a different transaction with the same hash. This", "// is allowed so long as the previous transaction is fully spent.", "entry", ":=", "view", ".", "LookupEntry", "(", "outpoint", ")", "\n", "if", "entry", "==", "nil", "{", "entry", "=", "new", "(", "UtxoEntry", ")", "\n", "view", ".", "entries", "[", "outpoint", "]", "=", "entry", "\n", "}", "\n\n", "entry", ".", "amount", "=", "txOut", ".", "Value", "\n", "entry", ".", "pkScript", "=", "txOut", ".", "PkScript", "\n", "entry", ".", "blockHeight", "=", "blockHeight", "\n", "entry", ".", "packedFlags", "=", "tfModified", "\n", "if", "isCoinBase", "{", "entry", ".", "packedFlags", "|=", "tfCoinBase", "\n", "}", "\n", "}" ]
// addTxOut adds the specified output to the view if it is not provably // unspendable. When the view already has an entry for the output, it will be // marked unspent. All fields will be updated for existing entries since it's // possible it has changed during a reorg.
[ "addTxOut", "adds", "the", "specified", "output", "to", "the", "view", "if", "it", "is", "not", "provably", "unspendable", ".", "When", "the", "view", "already", "has", "an", "entry", "for", "the", "output", "it", "will", "be", "marked", "unspent", ".", "All", "fields", "will", "be", "updated", "for", "existing", "entries", "since", "it", "s", "possible", "it", "has", "changed", "during", "a", "reorg", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/utxoviewpoint.go#L150-L173
train
btcsuite/btcd
blockchain/utxoviewpoint.go
AddTxOut
func (view *UtxoViewpoint) AddTxOut(tx *btcutil.Tx, txOutIdx uint32, blockHeight int32) { // Can't add an output for an out of bounds index. if txOutIdx >= uint32(len(tx.MsgTx().TxOut)) { return } // Update existing entries. All fields are updated because it's // possible (although extremely unlikely) that the existing entry is // being replaced by a different transaction with the same hash. This // is allowed so long as the previous transaction is fully spent. prevOut := wire.OutPoint{Hash: *tx.Hash(), Index: txOutIdx} txOut := tx.MsgTx().TxOut[txOutIdx] view.addTxOut(prevOut, txOut, IsCoinBase(tx), blockHeight) }
go
func (view *UtxoViewpoint) AddTxOut(tx *btcutil.Tx, txOutIdx uint32, blockHeight int32) { // Can't add an output for an out of bounds index. if txOutIdx >= uint32(len(tx.MsgTx().TxOut)) { return } // Update existing entries. All fields are updated because it's // possible (although extremely unlikely) that the existing entry is // being replaced by a different transaction with the same hash. This // is allowed so long as the previous transaction is fully spent. prevOut := wire.OutPoint{Hash: *tx.Hash(), Index: txOutIdx} txOut := tx.MsgTx().TxOut[txOutIdx] view.addTxOut(prevOut, txOut, IsCoinBase(tx), blockHeight) }
[ "func", "(", "view", "*", "UtxoViewpoint", ")", "AddTxOut", "(", "tx", "*", "btcutil", ".", "Tx", ",", "txOutIdx", "uint32", ",", "blockHeight", "int32", ")", "{", "// Can't add an output for an out of bounds index.", "if", "txOutIdx", ">=", "uint32", "(", "len", "(", "tx", ".", "MsgTx", "(", ")", ".", "TxOut", ")", ")", "{", "return", "\n", "}", "\n\n", "// Update existing entries. All fields are updated because it's", "// possible (although extremely unlikely) that the existing entry is", "// being replaced by a different transaction with the same hash. This", "// is allowed so long as the previous transaction is fully spent.", "prevOut", ":=", "wire", ".", "OutPoint", "{", "Hash", ":", "*", "tx", ".", "Hash", "(", ")", ",", "Index", ":", "txOutIdx", "}", "\n", "txOut", ":=", "tx", ".", "MsgTx", "(", ")", ".", "TxOut", "[", "txOutIdx", "]", "\n", "view", ".", "addTxOut", "(", "prevOut", ",", "txOut", ",", "IsCoinBase", "(", "tx", ")", ",", "blockHeight", ")", "\n", "}" ]
// AddTxOut adds the specified output of the passed transaction to the view if // it exists and is not provably unspendable. When the view already has an // entry for the output, it will be marked unspent. All fields will be updated // for existing entries since it's possible it has changed during a reorg.
[ "AddTxOut", "adds", "the", "specified", "output", "of", "the", "passed", "transaction", "to", "the", "view", "if", "it", "exists", "and", "is", "not", "provably", "unspendable", ".", "When", "the", "view", "already", "has", "an", "entry", "for", "the", "output", "it", "will", "be", "marked", "unspent", ".", "All", "fields", "will", "be", "updated", "for", "existing", "entries", "since", "it", "s", "possible", "it", "has", "changed", "during", "a", "reorg", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/utxoviewpoint.go#L179-L192
train
btcsuite/btcd
blockchain/utxoviewpoint.go
connectTransaction
func (view *UtxoViewpoint) connectTransaction(tx *btcutil.Tx, blockHeight int32, stxos *[]SpentTxOut) error { // Coinbase transactions don't have any inputs to spend. if IsCoinBase(tx) { // Add the transaction's outputs as available utxos. view.AddTxOuts(tx, blockHeight) return nil } // Spend the referenced utxos by marking them spent in the view and, // if a slice was provided for the spent txout details, append an entry // to it. for _, txIn := range tx.MsgTx().TxIn { // Ensure the referenced utxo exists in the view. This should // never happen unless there is a bug is introduced in the code. entry := view.entries[txIn.PreviousOutPoint] if entry == nil { return AssertError(fmt.Sprintf("view missing input %v", txIn.PreviousOutPoint)) } // Only create the stxo details if requested. if stxos != nil { // Populate the stxo details using the utxo entry. var stxo = SpentTxOut{ Amount: entry.Amount(), PkScript: entry.PkScript(), Height: entry.BlockHeight(), IsCoinBase: entry.IsCoinBase(), } *stxos = append(*stxos, stxo) } // Mark the entry as spent. This is not done until after the // relevant details have been accessed since spending it might // clear the fields from memory in the future. entry.Spend() } // Add the transaction's outputs as available utxos. view.AddTxOuts(tx, blockHeight) return nil }
go
func (view *UtxoViewpoint) connectTransaction(tx *btcutil.Tx, blockHeight int32, stxos *[]SpentTxOut) error { // Coinbase transactions don't have any inputs to spend. if IsCoinBase(tx) { // Add the transaction's outputs as available utxos. view.AddTxOuts(tx, blockHeight) return nil } // Spend the referenced utxos by marking them spent in the view and, // if a slice was provided for the spent txout details, append an entry // to it. for _, txIn := range tx.MsgTx().TxIn { // Ensure the referenced utxo exists in the view. This should // never happen unless there is a bug is introduced in the code. entry := view.entries[txIn.PreviousOutPoint] if entry == nil { return AssertError(fmt.Sprintf("view missing input %v", txIn.PreviousOutPoint)) } // Only create the stxo details if requested. if stxos != nil { // Populate the stxo details using the utxo entry. var stxo = SpentTxOut{ Amount: entry.Amount(), PkScript: entry.PkScript(), Height: entry.BlockHeight(), IsCoinBase: entry.IsCoinBase(), } *stxos = append(*stxos, stxo) } // Mark the entry as spent. This is not done until after the // relevant details have been accessed since spending it might // clear the fields from memory in the future. entry.Spend() } // Add the transaction's outputs as available utxos. view.AddTxOuts(tx, blockHeight) return nil }
[ "func", "(", "view", "*", "UtxoViewpoint", ")", "connectTransaction", "(", "tx", "*", "btcutil", ".", "Tx", ",", "blockHeight", "int32", ",", "stxos", "*", "[", "]", "SpentTxOut", ")", "error", "{", "// Coinbase transactions don't have any inputs to spend.", "if", "IsCoinBase", "(", "tx", ")", "{", "// Add the transaction's outputs as available utxos.", "view", ".", "AddTxOuts", "(", "tx", ",", "blockHeight", ")", "\n", "return", "nil", "\n", "}", "\n\n", "// Spend the referenced utxos by marking them spent in the view and,", "// if a slice was provided for the spent txout details, append an entry", "// to it.", "for", "_", ",", "txIn", ":=", "range", "tx", ".", "MsgTx", "(", ")", ".", "TxIn", "{", "// Ensure the referenced utxo exists in the view. This should", "// never happen unless there is a bug is introduced in the code.", "entry", ":=", "view", ".", "entries", "[", "txIn", ".", "PreviousOutPoint", "]", "\n", "if", "entry", "==", "nil", "{", "return", "AssertError", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "txIn", ".", "PreviousOutPoint", ")", ")", "\n", "}", "\n\n", "// Only create the stxo details if requested.", "if", "stxos", "!=", "nil", "{", "// Populate the stxo details using the utxo entry.", "var", "stxo", "=", "SpentTxOut", "{", "Amount", ":", "entry", ".", "Amount", "(", ")", ",", "PkScript", ":", "entry", ".", "PkScript", "(", ")", ",", "Height", ":", "entry", ".", "BlockHeight", "(", ")", ",", "IsCoinBase", ":", "entry", ".", "IsCoinBase", "(", ")", ",", "}", "\n", "*", "stxos", "=", "append", "(", "*", "stxos", ",", "stxo", ")", "\n", "}", "\n\n", "// Mark the entry as spent. This is not done until after the", "// relevant details have been accessed since spending it might", "// clear the fields from memory in the future.", "entry", ".", "Spend", "(", ")", "\n", "}", "\n\n", "// Add the transaction's outputs as available utxos.", "view", ".", "AddTxOuts", "(", "tx", ",", "blockHeight", ")", "\n", "return", "nil", "\n", "}" ]
// connectTransaction updates the view by adding all new utxos created by the // passed transaction and marking all utxos that the transactions spend as // spent. In addition, when the 'stxos' argument is not nil, it will be updated // to append an entry for each spent txout. An error will be returned if the // view does not contain the required utxos.
[ "connectTransaction", "updates", "the", "view", "by", "adding", "all", "new", "utxos", "created", "by", "the", "passed", "transaction", "and", "marking", "all", "utxos", "that", "the", "transactions", "spend", "as", "spent", ".", "In", "addition", "when", "the", "stxos", "argument", "is", "not", "nil", "it", "will", "be", "updated", "to", "append", "an", "entry", "for", "each", "spent", "txout", ".", "An", "error", "will", "be", "returned", "if", "the", "view", "does", "not", "contain", "the", "required", "utxos", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/utxoviewpoint.go#L219-L260
train
btcsuite/btcd
blockchain/utxoviewpoint.go
connectTransactions
func (view *UtxoViewpoint) connectTransactions(block *btcutil.Block, stxos *[]SpentTxOut) error { for _, tx := range block.Transactions() { err := view.connectTransaction(tx, block.Height(), stxos) if err != nil { return err } } // Update the best hash for view to include this block since all of its // transactions have been connected. view.SetBestHash(block.Hash()) return nil }
go
func (view *UtxoViewpoint) connectTransactions(block *btcutil.Block, stxos *[]SpentTxOut) error { for _, tx := range block.Transactions() { err := view.connectTransaction(tx, block.Height(), stxos) if err != nil { return err } } // Update the best hash for view to include this block since all of its // transactions have been connected. view.SetBestHash(block.Hash()) return nil }
[ "func", "(", "view", "*", "UtxoViewpoint", ")", "connectTransactions", "(", "block", "*", "btcutil", ".", "Block", ",", "stxos", "*", "[", "]", "SpentTxOut", ")", "error", "{", "for", "_", ",", "tx", ":=", "range", "block", ".", "Transactions", "(", ")", "{", "err", ":=", "view", ".", "connectTransaction", "(", "tx", ",", "block", ".", "Height", "(", ")", ",", "stxos", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "// Update the best hash for view to include this block since all of its", "// transactions have been connected.", "view", ".", "SetBestHash", "(", "block", ".", "Hash", "(", ")", ")", "\n", "return", "nil", "\n", "}" ]
// connectTransactions updates the view by adding all new utxos created by all // of the transactions in the passed block, marking all utxos the transactions // spend as spent, and setting the best hash for the view to the passed block. // In addition, when the 'stxos' argument is not nil, it will be updated to // append an entry for each spent txout.
[ "connectTransactions", "updates", "the", "view", "by", "adding", "all", "new", "utxos", "created", "by", "all", "of", "the", "transactions", "in", "the", "passed", "block", "marking", "all", "utxos", "the", "transactions", "spend", "as", "spent", "and", "setting", "the", "best", "hash", "for", "the", "view", "to", "the", "passed", "block", ".", "In", "addition", "when", "the", "stxos", "argument", "is", "not", "nil", "it", "will", "be", "updated", "to", "append", "an", "entry", "for", "each", "spent", "txout", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/utxoviewpoint.go#L267-L279
train
btcsuite/btcd
blockchain/utxoviewpoint.go
fetchEntryByHash
func (view *UtxoViewpoint) fetchEntryByHash(db database.DB, hash *chainhash.Hash) (*UtxoEntry, error) { // First attempt to find a utxo with the provided hash in the view. prevOut := wire.OutPoint{Hash: *hash} for idx := uint32(0); idx < MaxOutputsPerBlock; idx++ { prevOut.Index = idx entry := view.LookupEntry(prevOut) if entry != nil { return entry, nil } } // Check the database since it doesn't exist in the view. This will // often by the case since only specifically referenced utxos are loaded // into the view. var entry *UtxoEntry err := db.View(func(dbTx database.Tx) error { var err error entry, err = dbFetchUtxoEntryByHash(dbTx, hash) return err }) return entry, err }
go
func (view *UtxoViewpoint) fetchEntryByHash(db database.DB, hash *chainhash.Hash) (*UtxoEntry, error) { // First attempt to find a utxo with the provided hash in the view. prevOut := wire.OutPoint{Hash: *hash} for idx := uint32(0); idx < MaxOutputsPerBlock; idx++ { prevOut.Index = idx entry := view.LookupEntry(prevOut) if entry != nil { return entry, nil } } // Check the database since it doesn't exist in the view. This will // often by the case since only specifically referenced utxos are loaded // into the view. var entry *UtxoEntry err := db.View(func(dbTx database.Tx) error { var err error entry, err = dbFetchUtxoEntryByHash(dbTx, hash) return err }) return entry, err }
[ "func", "(", "view", "*", "UtxoViewpoint", ")", "fetchEntryByHash", "(", "db", "database", ".", "DB", ",", "hash", "*", "chainhash", ".", "Hash", ")", "(", "*", "UtxoEntry", ",", "error", ")", "{", "// First attempt to find a utxo with the provided hash in the view.", "prevOut", ":=", "wire", ".", "OutPoint", "{", "Hash", ":", "*", "hash", "}", "\n", "for", "idx", ":=", "uint32", "(", "0", ")", ";", "idx", "<", "MaxOutputsPerBlock", ";", "idx", "++", "{", "prevOut", ".", "Index", "=", "idx", "\n", "entry", ":=", "view", ".", "LookupEntry", "(", "prevOut", ")", "\n", "if", "entry", "!=", "nil", "{", "return", "entry", ",", "nil", "\n", "}", "\n", "}", "\n\n", "// Check the database since it doesn't exist in the view. This will", "// often by the case since only specifically referenced utxos are loaded", "// into the view.", "var", "entry", "*", "UtxoEntry", "\n", "err", ":=", "db", ".", "View", "(", "func", "(", "dbTx", "database", ".", "Tx", ")", "error", "{", "var", "err", "error", "\n", "entry", ",", "err", "=", "dbFetchUtxoEntryByHash", "(", "dbTx", ",", "hash", ")", "\n", "return", "err", "\n", "}", ")", "\n", "return", "entry", ",", "err", "\n", "}" ]
// fetchEntryByHash attempts to find any available utxo for the given hash by // searching the entire set of possible outputs for the given hash. It checks // the view first and then falls back to the database if needed.
[ "fetchEntryByHash", "attempts", "to", "find", "any", "available", "utxo", "for", "the", "given", "hash", "by", "searching", "the", "entire", "set", "of", "possible", "outputs", "for", "the", "given", "hash", ".", "It", "checks", "the", "view", "first", "and", "then", "falls", "back", "to", "the", "database", "if", "needed", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/utxoviewpoint.go#L284-L305
train
btcsuite/btcd
blockchain/utxoviewpoint.go
disconnectTransactions
func (view *UtxoViewpoint) disconnectTransactions(db database.DB, block *btcutil.Block, stxos []SpentTxOut) error { // Sanity check the correct number of stxos are provided. if len(stxos) != countSpentOutputs(block) { return AssertError("disconnectTransactions called with bad " + "spent transaction out information") } // Loop backwards through all transactions so everything is unspent in // reverse order. This is necessary since transactions later in a block // can spend from previous ones. stxoIdx := len(stxos) - 1 transactions := block.Transactions() for txIdx := len(transactions) - 1; txIdx > -1; txIdx-- { tx := transactions[txIdx] // All entries will need to potentially be marked as a coinbase. var packedFlags txoFlags isCoinBase := txIdx == 0 if isCoinBase { packedFlags |= tfCoinBase } // Mark all of the spendable outputs originally created by the // transaction as spent. It is instructive to note that while // the outputs aren't actually being spent here, rather they no // longer exist, since a pruned utxo set is used, there is no // practical difference between a utxo that does not exist and // one that has been spent. // // When the utxo does not already exist in the view, add an // entry for it and then mark it spent. This is done because // the code relies on its existence in the view in order to // signal modifications have happened. txHash := tx.Hash() prevOut := wire.OutPoint{Hash: *txHash} for txOutIdx, txOut := range tx.MsgTx().TxOut { if txscript.IsUnspendable(txOut.PkScript) { continue } prevOut.Index = uint32(txOutIdx) entry := view.entries[prevOut] if entry == nil { entry = &UtxoEntry{ amount: txOut.Value, pkScript: txOut.PkScript, blockHeight: block.Height(), packedFlags: packedFlags, } view.entries[prevOut] = entry } entry.Spend() } // Loop backwards through all of the transaction inputs (except // for the coinbase which has no inputs) and unspend the // referenced txos. This is necessary to match the order of the // spent txout entries. if isCoinBase { continue } for txInIdx := len(tx.MsgTx().TxIn) - 1; txInIdx > -1; txInIdx-- { // Ensure the spent txout index is decremented to stay // in sync with the transaction input. stxo := &stxos[stxoIdx] stxoIdx-- // When there is not already an entry for the referenced // output in the view, it means it was previously spent, // so create a new utxo entry in order to resurrect it. originOut := &tx.MsgTx().TxIn[txInIdx].PreviousOutPoint entry := view.entries[*originOut] if entry == nil { entry = new(UtxoEntry) view.entries[*originOut] = entry } // The legacy v1 spend journal format only stored the // coinbase flag and height when the output was the last // unspent output of the transaction. As a result, when // the information is missing, search for it by scanning // all possible outputs of the transaction since it must // be in one of them. // // It should be noted that this is quite inefficient, // but it realistically will almost never run since all // new entries include the information for all outputs // and thus the only way this will be hit is if a long // enough reorg happens such that a block with the old // spend data is being disconnected. The probability of // that in practice is extremely low to begin with and // becomes vanishingly small the more new blocks are // connected. In the case of a fresh database that has // only ever run with the new v2 format, this code path // will never run. if stxo.Height == 0 { utxo, err := view.fetchEntryByHash(db, txHash) if err != nil { return err } if utxo == nil { return AssertError(fmt.Sprintf("unable "+ "to resurrect legacy stxo %v", *originOut)) } stxo.Height = utxo.BlockHeight() stxo.IsCoinBase = utxo.IsCoinBase() } // Restore the utxo using the stxo data from the spend // journal and mark it as modified. entry.amount = stxo.Amount entry.pkScript = stxo.PkScript entry.blockHeight = stxo.Height entry.packedFlags = tfModified if stxo.IsCoinBase { entry.packedFlags |= tfCoinBase } } } // Update the best hash for view to the previous block since all of the // transactions for the current block have been disconnected. view.SetBestHash(&block.MsgBlock().Header.PrevBlock) return nil }
go
func (view *UtxoViewpoint) disconnectTransactions(db database.DB, block *btcutil.Block, stxos []SpentTxOut) error { // Sanity check the correct number of stxos are provided. if len(stxos) != countSpentOutputs(block) { return AssertError("disconnectTransactions called with bad " + "spent transaction out information") } // Loop backwards through all transactions so everything is unspent in // reverse order. This is necessary since transactions later in a block // can spend from previous ones. stxoIdx := len(stxos) - 1 transactions := block.Transactions() for txIdx := len(transactions) - 1; txIdx > -1; txIdx-- { tx := transactions[txIdx] // All entries will need to potentially be marked as a coinbase. var packedFlags txoFlags isCoinBase := txIdx == 0 if isCoinBase { packedFlags |= tfCoinBase } // Mark all of the spendable outputs originally created by the // transaction as spent. It is instructive to note that while // the outputs aren't actually being spent here, rather they no // longer exist, since a pruned utxo set is used, there is no // practical difference between a utxo that does not exist and // one that has been spent. // // When the utxo does not already exist in the view, add an // entry for it and then mark it spent. This is done because // the code relies on its existence in the view in order to // signal modifications have happened. txHash := tx.Hash() prevOut := wire.OutPoint{Hash: *txHash} for txOutIdx, txOut := range tx.MsgTx().TxOut { if txscript.IsUnspendable(txOut.PkScript) { continue } prevOut.Index = uint32(txOutIdx) entry := view.entries[prevOut] if entry == nil { entry = &UtxoEntry{ amount: txOut.Value, pkScript: txOut.PkScript, blockHeight: block.Height(), packedFlags: packedFlags, } view.entries[prevOut] = entry } entry.Spend() } // Loop backwards through all of the transaction inputs (except // for the coinbase which has no inputs) and unspend the // referenced txos. This is necessary to match the order of the // spent txout entries. if isCoinBase { continue } for txInIdx := len(tx.MsgTx().TxIn) - 1; txInIdx > -1; txInIdx-- { // Ensure the spent txout index is decremented to stay // in sync with the transaction input. stxo := &stxos[stxoIdx] stxoIdx-- // When there is not already an entry for the referenced // output in the view, it means it was previously spent, // so create a new utxo entry in order to resurrect it. originOut := &tx.MsgTx().TxIn[txInIdx].PreviousOutPoint entry := view.entries[*originOut] if entry == nil { entry = new(UtxoEntry) view.entries[*originOut] = entry } // The legacy v1 spend journal format only stored the // coinbase flag and height when the output was the last // unspent output of the transaction. As a result, when // the information is missing, search for it by scanning // all possible outputs of the transaction since it must // be in one of them. // // It should be noted that this is quite inefficient, // but it realistically will almost never run since all // new entries include the information for all outputs // and thus the only way this will be hit is if a long // enough reorg happens such that a block with the old // spend data is being disconnected. The probability of // that in practice is extremely low to begin with and // becomes vanishingly small the more new blocks are // connected. In the case of a fresh database that has // only ever run with the new v2 format, this code path // will never run. if stxo.Height == 0 { utxo, err := view.fetchEntryByHash(db, txHash) if err != nil { return err } if utxo == nil { return AssertError(fmt.Sprintf("unable "+ "to resurrect legacy stxo %v", *originOut)) } stxo.Height = utxo.BlockHeight() stxo.IsCoinBase = utxo.IsCoinBase() } // Restore the utxo using the stxo data from the spend // journal and mark it as modified. entry.amount = stxo.Amount entry.pkScript = stxo.PkScript entry.blockHeight = stxo.Height entry.packedFlags = tfModified if stxo.IsCoinBase { entry.packedFlags |= tfCoinBase } } } // Update the best hash for view to the previous block since all of the // transactions for the current block have been disconnected. view.SetBestHash(&block.MsgBlock().Header.PrevBlock) return nil }
[ "func", "(", "view", "*", "UtxoViewpoint", ")", "disconnectTransactions", "(", "db", "database", ".", "DB", ",", "block", "*", "btcutil", ".", "Block", ",", "stxos", "[", "]", "SpentTxOut", ")", "error", "{", "// Sanity check the correct number of stxos are provided.", "if", "len", "(", "stxos", ")", "!=", "countSpentOutputs", "(", "block", ")", "{", "return", "AssertError", "(", "\"", "\"", "+", "\"", "\"", ")", "\n", "}", "\n\n", "// Loop backwards through all transactions so everything is unspent in", "// reverse order. This is necessary since transactions later in a block", "// can spend from previous ones.", "stxoIdx", ":=", "len", "(", "stxos", ")", "-", "1", "\n", "transactions", ":=", "block", ".", "Transactions", "(", ")", "\n", "for", "txIdx", ":=", "len", "(", "transactions", ")", "-", "1", ";", "txIdx", ">", "-", "1", ";", "txIdx", "--", "{", "tx", ":=", "transactions", "[", "txIdx", "]", "\n\n", "// All entries will need to potentially be marked as a coinbase.", "var", "packedFlags", "txoFlags", "\n", "isCoinBase", ":=", "txIdx", "==", "0", "\n", "if", "isCoinBase", "{", "packedFlags", "|=", "tfCoinBase", "\n", "}", "\n\n", "// Mark all of the spendable outputs originally created by the", "// transaction as spent. It is instructive to note that while", "// the outputs aren't actually being spent here, rather they no", "// longer exist, since a pruned utxo set is used, there is no", "// practical difference between a utxo that does not exist and", "// one that has been spent.", "//", "// When the utxo does not already exist in the view, add an", "// entry for it and then mark it spent. This is done because", "// the code relies on its existence in the view in order to", "// signal modifications have happened.", "txHash", ":=", "tx", ".", "Hash", "(", ")", "\n", "prevOut", ":=", "wire", ".", "OutPoint", "{", "Hash", ":", "*", "txHash", "}", "\n", "for", "txOutIdx", ",", "txOut", ":=", "range", "tx", ".", "MsgTx", "(", ")", ".", "TxOut", "{", "if", "txscript", ".", "IsUnspendable", "(", "txOut", ".", "PkScript", ")", "{", "continue", "\n", "}", "\n\n", "prevOut", ".", "Index", "=", "uint32", "(", "txOutIdx", ")", "\n", "entry", ":=", "view", ".", "entries", "[", "prevOut", "]", "\n", "if", "entry", "==", "nil", "{", "entry", "=", "&", "UtxoEntry", "{", "amount", ":", "txOut", ".", "Value", ",", "pkScript", ":", "txOut", ".", "PkScript", ",", "blockHeight", ":", "block", ".", "Height", "(", ")", ",", "packedFlags", ":", "packedFlags", ",", "}", "\n\n", "view", ".", "entries", "[", "prevOut", "]", "=", "entry", "\n", "}", "\n\n", "entry", ".", "Spend", "(", ")", "\n", "}", "\n\n", "// Loop backwards through all of the transaction inputs (except", "// for the coinbase which has no inputs) and unspend the", "// referenced txos. This is necessary to match the order of the", "// spent txout entries.", "if", "isCoinBase", "{", "continue", "\n", "}", "\n", "for", "txInIdx", ":=", "len", "(", "tx", ".", "MsgTx", "(", ")", ".", "TxIn", ")", "-", "1", ";", "txInIdx", ">", "-", "1", ";", "txInIdx", "--", "{", "// Ensure the spent txout index is decremented to stay", "// in sync with the transaction input.", "stxo", ":=", "&", "stxos", "[", "stxoIdx", "]", "\n", "stxoIdx", "--", "\n\n", "// When there is not already an entry for the referenced", "// output in the view, it means it was previously spent,", "// so create a new utxo entry in order to resurrect it.", "originOut", ":=", "&", "tx", ".", "MsgTx", "(", ")", ".", "TxIn", "[", "txInIdx", "]", ".", "PreviousOutPoint", "\n", "entry", ":=", "view", ".", "entries", "[", "*", "originOut", "]", "\n", "if", "entry", "==", "nil", "{", "entry", "=", "new", "(", "UtxoEntry", ")", "\n", "view", ".", "entries", "[", "*", "originOut", "]", "=", "entry", "\n", "}", "\n\n", "// The legacy v1 spend journal format only stored the", "// coinbase flag and height when the output was the last", "// unspent output of the transaction. As a result, when", "// the information is missing, search for it by scanning", "// all possible outputs of the transaction since it must", "// be in one of them.", "//", "// It should be noted that this is quite inefficient,", "// but it realistically will almost never run since all", "// new entries include the information for all outputs", "// and thus the only way this will be hit is if a long", "// enough reorg happens such that a block with the old", "// spend data is being disconnected. The probability of", "// that in practice is extremely low to begin with and", "// becomes vanishingly small the more new blocks are", "// connected. In the case of a fresh database that has", "// only ever run with the new v2 format, this code path", "// will never run.", "if", "stxo", ".", "Height", "==", "0", "{", "utxo", ",", "err", ":=", "view", ".", "fetchEntryByHash", "(", "db", ",", "txHash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "utxo", "==", "nil", "{", "return", "AssertError", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "*", "originOut", ")", ")", "\n", "}", "\n\n", "stxo", ".", "Height", "=", "utxo", ".", "BlockHeight", "(", ")", "\n", "stxo", ".", "IsCoinBase", "=", "utxo", ".", "IsCoinBase", "(", ")", "\n", "}", "\n\n", "// Restore the utxo using the stxo data from the spend", "// journal and mark it as modified.", "entry", ".", "amount", "=", "stxo", ".", "Amount", "\n", "entry", ".", "pkScript", "=", "stxo", ".", "PkScript", "\n", "entry", ".", "blockHeight", "=", "stxo", ".", "Height", "\n", "entry", ".", "packedFlags", "=", "tfModified", "\n", "if", "stxo", ".", "IsCoinBase", "{", "entry", ".", "packedFlags", "|=", "tfCoinBase", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Update the best hash for view to the previous block since all of the", "// transactions for the current block have been disconnected.", "view", ".", "SetBestHash", "(", "&", "block", ".", "MsgBlock", "(", ")", ".", "Header", ".", "PrevBlock", ")", "\n", "return", "nil", "\n", "}" ]
// disconnectTransactions updates the view by removing all of the transactions // created by the passed block, restoring all utxos the transactions spent by // using the provided spent txo information, and setting the best hash for the // view to the block before the passed block.
[ "disconnectTransactions", "updates", "the", "view", "by", "removing", "all", "of", "the", "transactions", "created", "by", "the", "passed", "block", "restoring", "all", "utxos", "the", "transactions", "spent", "by", "using", "the", "provided", "spent", "txo", "information", "and", "setting", "the", "best", "hash", "for", "the", "view", "to", "the", "block", "before", "the", "passed", "block", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/utxoviewpoint.go#L311-L439
train
btcsuite/btcd
blockchain/utxoviewpoint.go
RemoveEntry
func (view *UtxoViewpoint) RemoveEntry(outpoint wire.OutPoint) { delete(view.entries, outpoint) }
go
func (view *UtxoViewpoint) RemoveEntry(outpoint wire.OutPoint) { delete(view.entries, outpoint) }
[ "func", "(", "view", "*", "UtxoViewpoint", ")", "RemoveEntry", "(", "outpoint", "wire", ".", "OutPoint", ")", "{", "delete", "(", "view", ".", "entries", ",", "outpoint", ")", "\n", "}" ]
// RemoveEntry removes the given transaction output from the current state of // the view. It will have no effect if the passed output does not exist in the // view.
[ "RemoveEntry", "removes", "the", "given", "transaction", "output", "from", "the", "current", "state", "of", "the", "view", ".", "It", "will", "have", "no", "effect", "if", "the", "passed", "output", "does", "not", "exist", "in", "the", "view", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/utxoviewpoint.go#L444-L446
train
btcsuite/btcd
blockchain/utxoviewpoint.go
commit
func (view *UtxoViewpoint) commit() { for outpoint, entry := range view.entries { if entry == nil || (entry.isModified() && entry.IsSpent()) { delete(view.entries, outpoint) continue } entry.packedFlags ^= tfModified } }
go
func (view *UtxoViewpoint) commit() { for outpoint, entry := range view.entries { if entry == nil || (entry.isModified() && entry.IsSpent()) { delete(view.entries, outpoint) continue } entry.packedFlags ^= tfModified } }
[ "func", "(", "view", "*", "UtxoViewpoint", ")", "commit", "(", ")", "{", "for", "outpoint", ",", "entry", ":=", "range", "view", ".", "entries", "{", "if", "entry", "==", "nil", "||", "(", "entry", ".", "isModified", "(", ")", "&&", "entry", ".", "IsSpent", "(", ")", ")", "{", "delete", "(", "view", ".", "entries", ",", "outpoint", ")", "\n", "continue", "\n", "}", "\n\n", "entry", ".", "packedFlags", "^=", "tfModified", "\n", "}", "\n", "}" ]
// commit prunes all entries marked modified that are now fully spent and marks // all entries as unmodified.
[ "commit", "prunes", "all", "entries", "marked", "modified", "that", "are", "now", "fully", "spent", "and", "marks", "all", "entries", "as", "unmodified", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/utxoviewpoint.go#L455-L464
train
btcsuite/btcd
blockchain/utxoviewpoint.go
fetchUtxosMain
func (view *UtxoViewpoint) fetchUtxosMain(db database.DB, outpoints map[wire.OutPoint]struct{}) error { // Nothing to do if there are no requested outputs. if len(outpoints) == 0 { return nil } // Load the requested set of unspent transaction outputs from the point // of view of the end of the main chain. // // NOTE: Missing entries are not considered an error here and instead // will result in nil entries in the view. This is intentionally done // so other code can use the presence of an entry in the store as a way // to unnecessarily avoid attempting to reload it from the database. return db.View(func(dbTx database.Tx) error { for outpoint := range outpoints { entry, err := dbFetchUtxoEntry(dbTx, outpoint) if err != nil { return err } view.entries[outpoint] = entry } return nil }) }
go
func (view *UtxoViewpoint) fetchUtxosMain(db database.DB, outpoints map[wire.OutPoint]struct{}) error { // Nothing to do if there are no requested outputs. if len(outpoints) == 0 { return nil } // Load the requested set of unspent transaction outputs from the point // of view of the end of the main chain. // // NOTE: Missing entries are not considered an error here and instead // will result in nil entries in the view. This is intentionally done // so other code can use the presence of an entry in the store as a way // to unnecessarily avoid attempting to reload it from the database. return db.View(func(dbTx database.Tx) error { for outpoint := range outpoints { entry, err := dbFetchUtxoEntry(dbTx, outpoint) if err != nil { return err } view.entries[outpoint] = entry } return nil }) }
[ "func", "(", "view", "*", "UtxoViewpoint", ")", "fetchUtxosMain", "(", "db", "database", ".", "DB", ",", "outpoints", "map", "[", "wire", ".", "OutPoint", "]", "struct", "{", "}", ")", "error", "{", "// Nothing to do if there are no requested outputs.", "if", "len", "(", "outpoints", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "// Load the requested set of unspent transaction outputs from the point", "// of view of the end of the main chain.", "//", "// NOTE: Missing entries are not considered an error here and instead", "// will result in nil entries in the view. This is intentionally done", "// so other code can use the presence of an entry in the store as a way", "// to unnecessarily avoid attempting to reload it from the database.", "return", "db", ".", "View", "(", "func", "(", "dbTx", "database", ".", "Tx", ")", "error", "{", "for", "outpoint", ":=", "range", "outpoints", "{", "entry", ",", "err", ":=", "dbFetchUtxoEntry", "(", "dbTx", ",", "outpoint", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "view", ".", "entries", "[", "outpoint", "]", "=", "entry", "\n", "}", "\n\n", "return", "nil", "\n", "}", ")", "\n", "}" ]
// fetchUtxosMain fetches unspent transaction output data about the provided // set of outpoints from the point of view of the end of the main chain at the // time of the call. // // Upon completion of this function, the view will contain an entry for each // requested outpoint. Spent outputs, or those which otherwise don't exist, // will result in a nil entry in the view.
[ "fetchUtxosMain", "fetches", "unspent", "transaction", "output", "data", "about", "the", "provided", "set", "of", "outpoints", "from", "the", "point", "of", "view", "of", "the", "end", "of", "the", "main", "chain", "at", "the", "time", "of", "the", "call", ".", "Upon", "completion", "of", "this", "function", "the", "view", "will", "contain", "an", "entry", "for", "each", "requested", "outpoint", ".", "Spent", "outputs", "or", "those", "which", "otherwise", "don", "t", "exist", "will", "result", "in", "a", "nil", "entry", "in", "the", "view", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/utxoviewpoint.go#L473-L498
train
btcsuite/btcd
blockchain/utxoviewpoint.go
fetchUtxos
func (view *UtxoViewpoint) fetchUtxos(db database.DB, outpoints map[wire.OutPoint]struct{}) error { // Nothing to do if there are no requested outputs. if len(outpoints) == 0 { return nil } // Filter entries that are already in the view. neededSet := make(map[wire.OutPoint]struct{}) for outpoint := range outpoints { // Already loaded into the current view. if _, ok := view.entries[outpoint]; ok { continue } neededSet[outpoint] = struct{}{} } // Request the input utxos from the database. return view.fetchUtxosMain(db, neededSet) }
go
func (view *UtxoViewpoint) fetchUtxos(db database.DB, outpoints map[wire.OutPoint]struct{}) error { // Nothing to do if there are no requested outputs. if len(outpoints) == 0 { return nil } // Filter entries that are already in the view. neededSet := make(map[wire.OutPoint]struct{}) for outpoint := range outpoints { // Already loaded into the current view. if _, ok := view.entries[outpoint]; ok { continue } neededSet[outpoint] = struct{}{} } // Request the input utxos from the database. return view.fetchUtxosMain(db, neededSet) }
[ "func", "(", "view", "*", "UtxoViewpoint", ")", "fetchUtxos", "(", "db", "database", ".", "DB", ",", "outpoints", "map", "[", "wire", ".", "OutPoint", "]", "struct", "{", "}", ")", "error", "{", "// Nothing to do if there are no requested outputs.", "if", "len", "(", "outpoints", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "// Filter entries that are already in the view.", "neededSet", ":=", "make", "(", "map", "[", "wire", ".", "OutPoint", "]", "struct", "{", "}", ")", "\n", "for", "outpoint", ":=", "range", "outpoints", "{", "// Already loaded into the current view.", "if", "_", ",", "ok", ":=", "view", ".", "entries", "[", "outpoint", "]", ";", "ok", "{", "continue", "\n", "}", "\n\n", "neededSet", "[", "outpoint", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n\n", "// Request the input utxos from the database.", "return", "view", ".", "fetchUtxosMain", "(", "db", ",", "neededSet", ")", "\n", "}" ]
// fetchUtxos loads the unspent transaction outputs for the provided set of // outputs into the view from the database as needed unless they already exist // in the view in which case they are ignored.
[ "fetchUtxos", "loads", "the", "unspent", "transaction", "outputs", "for", "the", "provided", "set", "of", "outputs", "into", "the", "view", "from", "the", "database", "as", "needed", "unless", "they", "already", "exist", "in", "the", "view", "in", "which", "case", "they", "are", "ignored", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/utxoviewpoint.go#L503-L522
train
btcsuite/btcd
blockchain/utxoviewpoint.go
fetchInputUtxos
func (view *UtxoViewpoint) fetchInputUtxos(db database.DB, block *btcutil.Block) error { // Build a map of in-flight transactions because some of the inputs in // this block could be referencing other transactions earlier in this // block which are not yet in the chain. txInFlight := map[chainhash.Hash]int{} transactions := block.Transactions() for i, tx := range transactions { txInFlight[*tx.Hash()] = i } // Loop through all of the transaction inputs (except for the coinbase // which has no inputs) collecting them into sets of what is needed and // what is already known (in-flight). neededSet := make(map[wire.OutPoint]struct{}) for i, tx := range transactions[1:] { for _, txIn := range tx.MsgTx().TxIn { // It is acceptable for a transaction input to reference // the output of another transaction in this block only // if the referenced transaction comes before the // current one in this block. Add the outputs of the // referenced transaction as available utxos when this // is the case. Otherwise, the utxo details are still // needed. // // NOTE: The >= is correct here because i is one less // than the actual position of the transaction within // the block due to skipping the coinbase. originHash := &txIn.PreviousOutPoint.Hash if inFlightIndex, ok := txInFlight[*originHash]; ok && i >= inFlightIndex { originTx := transactions[inFlightIndex] view.AddTxOuts(originTx, block.Height()) continue } // Don't request entries that are already in the view // from the database. if _, ok := view.entries[txIn.PreviousOutPoint]; ok { continue } neededSet[txIn.PreviousOutPoint] = struct{}{} } } // Request the input utxos from the database. return view.fetchUtxosMain(db, neededSet) }
go
func (view *UtxoViewpoint) fetchInputUtxos(db database.DB, block *btcutil.Block) error { // Build a map of in-flight transactions because some of the inputs in // this block could be referencing other transactions earlier in this // block which are not yet in the chain. txInFlight := map[chainhash.Hash]int{} transactions := block.Transactions() for i, tx := range transactions { txInFlight[*tx.Hash()] = i } // Loop through all of the transaction inputs (except for the coinbase // which has no inputs) collecting them into sets of what is needed and // what is already known (in-flight). neededSet := make(map[wire.OutPoint]struct{}) for i, tx := range transactions[1:] { for _, txIn := range tx.MsgTx().TxIn { // It is acceptable for a transaction input to reference // the output of another transaction in this block only // if the referenced transaction comes before the // current one in this block. Add the outputs of the // referenced transaction as available utxos when this // is the case. Otherwise, the utxo details are still // needed. // // NOTE: The >= is correct here because i is one less // than the actual position of the transaction within // the block due to skipping the coinbase. originHash := &txIn.PreviousOutPoint.Hash if inFlightIndex, ok := txInFlight[*originHash]; ok && i >= inFlightIndex { originTx := transactions[inFlightIndex] view.AddTxOuts(originTx, block.Height()) continue } // Don't request entries that are already in the view // from the database. if _, ok := view.entries[txIn.PreviousOutPoint]; ok { continue } neededSet[txIn.PreviousOutPoint] = struct{}{} } } // Request the input utxos from the database. return view.fetchUtxosMain(db, neededSet) }
[ "func", "(", "view", "*", "UtxoViewpoint", ")", "fetchInputUtxos", "(", "db", "database", ".", "DB", ",", "block", "*", "btcutil", ".", "Block", ")", "error", "{", "// Build a map of in-flight transactions because some of the inputs in", "// this block could be referencing other transactions earlier in this", "// block which are not yet in the chain.", "txInFlight", ":=", "map", "[", "chainhash", ".", "Hash", "]", "int", "{", "}", "\n", "transactions", ":=", "block", ".", "Transactions", "(", ")", "\n", "for", "i", ",", "tx", ":=", "range", "transactions", "{", "txInFlight", "[", "*", "tx", ".", "Hash", "(", ")", "]", "=", "i", "\n", "}", "\n\n", "// Loop through all of the transaction inputs (except for the coinbase", "// which has no inputs) collecting them into sets of what is needed and", "// what is already known (in-flight).", "neededSet", ":=", "make", "(", "map", "[", "wire", ".", "OutPoint", "]", "struct", "{", "}", ")", "\n", "for", "i", ",", "tx", ":=", "range", "transactions", "[", "1", ":", "]", "{", "for", "_", ",", "txIn", ":=", "range", "tx", ".", "MsgTx", "(", ")", ".", "TxIn", "{", "// It is acceptable for a transaction input to reference", "// the output of another transaction in this block only", "// if the referenced transaction comes before the", "// current one in this block. Add the outputs of the", "// referenced transaction as available utxos when this", "// is the case. Otherwise, the utxo details are still", "// needed.", "//", "// NOTE: The >= is correct here because i is one less", "// than the actual position of the transaction within", "// the block due to skipping the coinbase.", "originHash", ":=", "&", "txIn", ".", "PreviousOutPoint", ".", "Hash", "\n", "if", "inFlightIndex", ",", "ok", ":=", "txInFlight", "[", "*", "originHash", "]", ";", "ok", "&&", "i", ">=", "inFlightIndex", "{", "originTx", ":=", "transactions", "[", "inFlightIndex", "]", "\n", "view", ".", "AddTxOuts", "(", "originTx", ",", "block", ".", "Height", "(", ")", ")", "\n", "continue", "\n", "}", "\n\n", "// Don't request entries that are already in the view", "// from the database.", "if", "_", ",", "ok", ":=", "view", ".", "entries", "[", "txIn", ".", "PreviousOutPoint", "]", ";", "ok", "{", "continue", "\n", "}", "\n\n", "neededSet", "[", "txIn", ".", "PreviousOutPoint", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "}", "\n\n", "// Request the input utxos from the database.", "return", "view", ".", "fetchUtxosMain", "(", "db", ",", "neededSet", ")", "\n", "}" ]
// fetchInputUtxos loads the unspent transaction outputs for the inputs // referenced by the transactions in the given block into the view from the // database as needed. In particular, referenced entries that are earlier in // the block are added to the view and entries that are already in the view are // not modified.
[ "fetchInputUtxos", "loads", "the", "unspent", "transaction", "outputs", "for", "the", "inputs", "referenced", "by", "the", "transactions", "in", "the", "given", "block", "into", "the", "view", "from", "the", "database", "as", "needed", ".", "In", "particular", "referenced", "entries", "that", "are", "earlier", "in", "the", "block", "are", "added", "to", "the", "view", "and", "entries", "that", "are", "already", "in", "the", "view", "are", "not", "modified", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/utxoviewpoint.go#L529-L577
train
btcsuite/btcd
blockchain/utxoviewpoint.go
FetchUtxoView
func (b *BlockChain) FetchUtxoView(tx *btcutil.Tx) (*UtxoViewpoint, error) { // Create a set of needed outputs based on those referenced by the // inputs of the passed transaction and the outputs of the transaction // itself. neededSet := make(map[wire.OutPoint]struct{}) prevOut := wire.OutPoint{Hash: *tx.Hash()} for txOutIdx := range tx.MsgTx().TxOut { prevOut.Index = uint32(txOutIdx) neededSet[prevOut] = struct{}{} } if !IsCoinBase(tx) { for _, txIn := range tx.MsgTx().TxIn { neededSet[txIn.PreviousOutPoint] = struct{}{} } } // Request the utxos from the point of view of the end of the main // chain. view := NewUtxoViewpoint() b.chainLock.RLock() err := view.fetchUtxosMain(b.db, neededSet) b.chainLock.RUnlock() return view, err }
go
func (b *BlockChain) FetchUtxoView(tx *btcutil.Tx) (*UtxoViewpoint, error) { // Create a set of needed outputs based on those referenced by the // inputs of the passed transaction and the outputs of the transaction // itself. neededSet := make(map[wire.OutPoint]struct{}) prevOut := wire.OutPoint{Hash: *tx.Hash()} for txOutIdx := range tx.MsgTx().TxOut { prevOut.Index = uint32(txOutIdx) neededSet[prevOut] = struct{}{} } if !IsCoinBase(tx) { for _, txIn := range tx.MsgTx().TxIn { neededSet[txIn.PreviousOutPoint] = struct{}{} } } // Request the utxos from the point of view of the end of the main // chain. view := NewUtxoViewpoint() b.chainLock.RLock() err := view.fetchUtxosMain(b.db, neededSet) b.chainLock.RUnlock() return view, err }
[ "func", "(", "b", "*", "BlockChain", ")", "FetchUtxoView", "(", "tx", "*", "btcutil", ".", "Tx", ")", "(", "*", "UtxoViewpoint", ",", "error", ")", "{", "// Create a set of needed outputs based on those referenced by the", "// inputs of the passed transaction and the outputs of the transaction", "// itself.", "neededSet", ":=", "make", "(", "map", "[", "wire", ".", "OutPoint", "]", "struct", "{", "}", ")", "\n", "prevOut", ":=", "wire", ".", "OutPoint", "{", "Hash", ":", "*", "tx", ".", "Hash", "(", ")", "}", "\n", "for", "txOutIdx", ":=", "range", "tx", ".", "MsgTx", "(", ")", ".", "TxOut", "{", "prevOut", ".", "Index", "=", "uint32", "(", "txOutIdx", ")", "\n", "neededSet", "[", "prevOut", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "if", "!", "IsCoinBase", "(", "tx", ")", "{", "for", "_", ",", "txIn", ":=", "range", "tx", ".", "MsgTx", "(", ")", ".", "TxIn", "{", "neededSet", "[", "txIn", ".", "PreviousOutPoint", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "}", "\n\n", "// Request the utxos from the point of view of the end of the main", "// chain.", "view", ":=", "NewUtxoViewpoint", "(", ")", "\n", "b", ".", "chainLock", ".", "RLock", "(", ")", "\n", "err", ":=", "view", ".", "fetchUtxosMain", "(", "b", ".", "db", ",", "neededSet", ")", "\n", "b", ".", "chainLock", ".", "RUnlock", "(", ")", "\n", "return", "view", ",", "err", "\n", "}" ]
// FetchUtxoView loads unspent transaction outputs for the inputs referenced by // the passed transaction from the point of view of the end of the main chain. // It also attempts to fetch the utxos for the outputs of the transaction itself // so the returned view can be examined for duplicate transactions. // // This function is safe for concurrent access however the returned view is NOT.
[ "FetchUtxoView", "loads", "unspent", "transaction", "outputs", "for", "the", "inputs", "referenced", "by", "the", "passed", "transaction", "from", "the", "point", "of", "view", "of", "the", "end", "of", "the", "main", "chain", ".", "It", "also", "attempts", "to", "fetch", "the", "utxos", "for", "the", "outputs", "of", "the", "transaction", "itself", "so", "the", "returned", "view", "can", "be", "examined", "for", "duplicate", "transactions", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "however", "the", "returned", "view", "is", "NOT", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/utxoviewpoint.go#L592-L615
train
btcsuite/btcd
wire/msgalert.go
Serialize
func (alert *Alert) Serialize(w io.Writer, pver uint32) error { err := writeElements(w, alert.Version, alert.RelayUntil, alert.Expiration, alert.ID, alert.Cancel) if err != nil { return err } count := len(alert.SetCancel) if count > maxCountSetCancel { str := fmt.Sprintf("too many cancel alert IDs for alert "+ "[count %v, max %v]", count, maxCountSetCancel) return messageError("Alert.Serialize", str) } err = WriteVarInt(w, pver, uint64(count)) if err != nil { return err } for i := 0; i < count; i++ { err = writeElement(w, alert.SetCancel[i]) if err != nil { return err } } err = writeElements(w, alert.MinVer, alert.MaxVer) if err != nil { return err } count = len(alert.SetSubVer) if count > maxCountSetSubVer { str := fmt.Sprintf("too many sub versions for alert "+ "[count %v, max %v]", count, maxCountSetSubVer) return messageError("Alert.Serialize", str) } err = WriteVarInt(w, pver, uint64(count)) if err != nil { return err } for i := 0; i < count; i++ { err = WriteVarString(w, pver, alert.SetSubVer[i]) if err != nil { return err } } err = writeElement(w, alert.Priority) if err != nil { return err } err = WriteVarString(w, pver, alert.Comment) if err != nil { return err } err = WriteVarString(w, pver, alert.StatusBar) if err != nil { return err } return WriteVarString(w, pver, alert.Reserved) }
go
func (alert *Alert) Serialize(w io.Writer, pver uint32) error { err := writeElements(w, alert.Version, alert.RelayUntil, alert.Expiration, alert.ID, alert.Cancel) if err != nil { return err } count := len(alert.SetCancel) if count > maxCountSetCancel { str := fmt.Sprintf("too many cancel alert IDs for alert "+ "[count %v, max %v]", count, maxCountSetCancel) return messageError("Alert.Serialize", str) } err = WriteVarInt(w, pver, uint64(count)) if err != nil { return err } for i := 0; i < count; i++ { err = writeElement(w, alert.SetCancel[i]) if err != nil { return err } } err = writeElements(w, alert.MinVer, alert.MaxVer) if err != nil { return err } count = len(alert.SetSubVer) if count > maxCountSetSubVer { str := fmt.Sprintf("too many sub versions for alert "+ "[count %v, max %v]", count, maxCountSetSubVer) return messageError("Alert.Serialize", str) } err = WriteVarInt(w, pver, uint64(count)) if err != nil { return err } for i := 0; i < count; i++ { err = WriteVarString(w, pver, alert.SetSubVer[i]) if err != nil { return err } } err = writeElement(w, alert.Priority) if err != nil { return err } err = WriteVarString(w, pver, alert.Comment) if err != nil { return err } err = WriteVarString(w, pver, alert.StatusBar) if err != nil { return err } return WriteVarString(w, pver, alert.Reserved) }
[ "func", "(", "alert", "*", "Alert", ")", "Serialize", "(", "w", "io", ".", "Writer", ",", "pver", "uint32", ")", "error", "{", "err", ":=", "writeElements", "(", "w", ",", "alert", ".", "Version", ",", "alert", ".", "RelayUntil", ",", "alert", ".", "Expiration", ",", "alert", ".", "ID", ",", "alert", ".", "Cancel", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "count", ":=", "len", "(", "alert", ".", "SetCancel", ")", "\n", "if", "count", ">", "maxCountSetCancel", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "count", ",", "maxCountSetCancel", ")", "\n", "return", "messageError", "(", "\"", "\"", ",", "str", ")", "\n", "}", "\n", "err", "=", "WriteVarInt", "(", "w", ",", "pver", ",", "uint64", "(", "count", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "count", ";", "i", "++", "{", "err", "=", "writeElement", "(", "w", ",", "alert", ".", "SetCancel", "[", "i", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "err", "=", "writeElements", "(", "w", ",", "alert", ".", "MinVer", ",", "alert", ".", "MaxVer", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "count", "=", "len", "(", "alert", ".", "SetSubVer", ")", "\n", "if", "count", ">", "maxCountSetSubVer", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "count", ",", "maxCountSetSubVer", ")", "\n", "return", "messageError", "(", "\"", "\"", ",", "str", ")", "\n", "}", "\n", "err", "=", "WriteVarInt", "(", "w", ",", "pver", ",", "uint64", "(", "count", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "count", ";", "i", "++", "{", "err", "=", "WriteVarString", "(", "w", ",", "pver", ",", "alert", ".", "SetSubVer", "[", "i", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "err", "=", "writeElement", "(", "w", ",", "alert", ".", "Priority", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "WriteVarString", "(", "w", ",", "pver", ",", "alert", ".", "Comment", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "WriteVarString", "(", "w", ",", "pver", ",", "alert", ".", "StatusBar", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "WriteVarString", "(", "w", ",", "pver", ",", "alert", ".", "Reserved", ")", "\n", "}" ]
// Serialize encodes the alert to w using the alert protocol encoding format.
[ "Serialize", "encodes", "the", "alert", "to", "w", "using", "the", "alert", "protocol", "encoding", "format", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgalert.go#L151-L210
train
btcsuite/btcd
wire/msgalert.go
Deserialize
func (alert *Alert) Deserialize(r io.Reader, pver uint32) error { err := readElements(r, &alert.Version, &alert.RelayUntil, &alert.Expiration, &alert.ID, &alert.Cancel) if err != nil { return err } // SetCancel: first read a VarInt that contains // count - the number of Cancel IDs, then // iterate count times and read them count, err := ReadVarInt(r, pver) if err != nil { return err } if count > maxCountSetCancel { str := fmt.Sprintf("too many cancel alert IDs for alert "+ "[count %v, max %v]", count, maxCountSetCancel) return messageError("Alert.Deserialize", str) } alert.SetCancel = make([]int32, count) for i := 0; i < int(count); i++ { err := readElement(r, &alert.SetCancel[i]) if err != nil { return err } } err = readElements(r, &alert.MinVer, &alert.MaxVer) if err != nil { return err } // SetSubVer: similar to SetCancel // but read count number of sub-version strings count, err = ReadVarInt(r, pver) if err != nil { return err } if count > maxCountSetSubVer { str := fmt.Sprintf("too many sub versions for alert "+ "[count %v, max %v]", count, maxCountSetSubVer) return messageError("Alert.Deserialize", str) } alert.SetSubVer = make([]string, count) for i := 0; i < int(count); i++ { alert.SetSubVer[i], err = ReadVarString(r, pver) if err != nil { return err } } err = readElement(r, &alert.Priority) if err != nil { return err } alert.Comment, err = ReadVarString(r, pver) if err != nil { return err } alert.StatusBar, err = ReadVarString(r, pver) if err != nil { return err } alert.Reserved, err = ReadVarString(r, pver) return err }
go
func (alert *Alert) Deserialize(r io.Reader, pver uint32) error { err := readElements(r, &alert.Version, &alert.RelayUntil, &alert.Expiration, &alert.ID, &alert.Cancel) if err != nil { return err } // SetCancel: first read a VarInt that contains // count - the number of Cancel IDs, then // iterate count times and read them count, err := ReadVarInt(r, pver) if err != nil { return err } if count > maxCountSetCancel { str := fmt.Sprintf("too many cancel alert IDs for alert "+ "[count %v, max %v]", count, maxCountSetCancel) return messageError("Alert.Deserialize", str) } alert.SetCancel = make([]int32, count) for i := 0; i < int(count); i++ { err := readElement(r, &alert.SetCancel[i]) if err != nil { return err } } err = readElements(r, &alert.MinVer, &alert.MaxVer) if err != nil { return err } // SetSubVer: similar to SetCancel // but read count number of sub-version strings count, err = ReadVarInt(r, pver) if err != nil { return err } if count > maxCountSetSubVer { str := fmt.Sprintf("too many sub versions for alert "+ "[count %v, max %v]", count, maxCountSetSubVer) return messageError("Alert.Deserialize", str) } alert.SetSubVer = make([]string, count) for i := 0; i < int(count); i++ { alert.SetSubVer[i], err = ReadVarString(r, pver) if err != nil { return err } } err = readElement(r, &alert.Priority) if err != nil { return err } alert.Comment, err = ReadVarString(r, pver) if err != nil { return err } alert.StatusBar, err = ReadVarString(r, pver) if err != nil { return err } alert.Reserved, err = ReadVarString(r, pver) return err }
[ "func", "(", "alert", "*", "Alert", ")", "Deserialize", "(", "r", "io", ".", "Reader", ",", "pver", "uint32", ")", "error", "{", "err", ":=", "readElements", "(", "r", ",", "&", "alert", ".", "Version", ",", "&", "alert", ".", "RelayUntil", ",", "&", "alert", ".", "Expiration", ",", "&", "alert", ".", "ID", ",", "&", "alert", ".", "Cancel", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// SetCancel: first read a VarInt that contains", "// count - the number of Cancel IDs, then", "// iterate count times and read them", "count", ",", "err", ":=", "ReadVarInt", "(", "r", ",", "pver", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "count", ">", "maxCountSetCancel", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "count", ",", "maxCountSetCancel", ")", "\n", "return", "messageError", "(", "\"", "\"", ",", "str", ")", "\n", "}", "\n", "alert", ".", "SetCancel", "=", "make", "(", "[", "]", "int32", ",", "count", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "int", "(", "count", ")", ";", "i", "++", "{", "err", ":=", "readElement", "(", "r", ",", "&", "alert", ".", "SetCancel", "[", "i", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "err", "=", "readElements", "(", "r", ",", "&", "alert", ".", "MinVer", ",", "&", "alert", ".", "MaxVer", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// SetSubVer: similar to SetCancel", "// but read count number of sub-version strings", "count", ",", "err", "=", "ReadVarInt", "(", "r", ",", "pver", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "count", ">", "maxCountSetSubVer", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "count", ",", "maxCountSetSubVer", ")", "\n", "return", "messageError", "(", "\"", "\"", ",", "str", ")", "\n", "}", "\n", "alert", ".", "SetSubVer", "=", "make", "(", "[", "]", "string", ",", "count", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "int", "(", "count", ")", ";", "i", "++", "{", "alert", ".", "SetSubVer", "[", "i", "]", ",", "err", "=", "ReadVarString", "(", "r", ",", "pver", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "err", "=", "readElement", "(", "r", ",", "&", "alert", ".", "Priority", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "alert", ".", "Comment", ",", "err", "=", "ReadVarString", "(", "r", ",", "pver", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "alert", ".", "StatusBar", ",", "err", "=", "ReadVarString", "(", "r", ",", "pver", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "alert", ".", "Reserved", ",", "err", "=", "ReadVarString", "(", "r", ",", "pver", ")", "\n", "return", "err", "\n", "}" ]
// Deserialize decodes from r into the receiver using the alert protocol // encoding format.
[ "Deserialize", "decodes", "from", "r", "into", "the", "receiver", "using", "the", "alert", "protocol", "encoding", "format", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgalert.go#L214-L279
train
btcsuite/btcd
wire/msgalert.go
NewAlert
func NewAlert(version int32, relayUntil int64, expiration int64, id int32, cancel int32, setCancel []int32, minVer int32, maxVer int32, setSubVer []string, priority int32, comment string, statusBar string) *Alert { return &Alert{ Version: version, RelayUntil: relayUntil, Expiration: expiration, ID: id, Cancel: cancel, SetCancel: setCancel, MinVer: minVer, MaxVer: maxVer, SetSubVer: setSubVer, Priority: priority, Comment: comment, StatusBar: statusBar, Reserved: "", } }
go
func NewAlert(version int32, relayUntil int64, expiration int64, id int32, cancel int32, setCancel []int32, minVer int32, maxVer int32, setSubVer []string, priority int32, comment string, statusBar string) *Alert { return &Alert{ Version: version, RelayUntil: relayUntil, Expiration: expiration, ID: id, Cancel: cancel, SetCancel: setCancel, MinVer: minVer, MaxVer: maxVer, SetSubVer: setSubVer, Priority: priority, Comment: comment, StatusBar: statusBar, Reserved: "", } }
[ "func", "NewAlert", "(", "version", "int32", ",", "relayUntil", "int64", ",", "expiration", "int64", ",", "id", "int32", ",", "cancel", "int32", ",", "setCancel", "[", "]", "int32", ",", "minVer", "int32", ",", "maxVer", "int32", ",", "setSubVer", "[", "]", "string", ",", "priority", "int32", ",", "comment", "string", ",", "statusBar", "string", ")", "*", "Alert", "{", "return", "&", "Alert", "{", "Version", ":", "version", ",", "RelayUntil", ":", "relayUntil", ",", "Expiration", ":", "expiration", ",", "ID", ":", "id", ",", "Cancel", ":", "cancel", ",", "SetCancel", ":", "setCancel", ",", "MinVer", ":", "minVer", ",", "MaxVer", ":", "maxVer", ",", "SetSubVer", ":", "setSubVer", ",", "Priority", ":", "priority", ",", "Comment", ":", "comment", ",", "StatusBar", ":", "statusBar", ",", "Reserved", ":", "\"", "\"", ",", "}", "\n", "}" ]
// NewAlert returns an new Alert with values provided.
[ "NewAlert", "returns", "an", "new", "Alert", "with", "values", "provided", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgalert.go#L282-L301
train
btcsuite/btcd
wire/msgalert.go
NewAlertFromPayload
func NewAlertFromPayload(serializedPayload []byte, pver uint32) (*Alert, error) { var alert Alert r := bytes.NewReader(serializedPayload) err := alert.Deserialize(r, pver) if err != nil { return nil, err } return &alert, nil }
go
func NewAlertFromPayload(serializedPayload []byte, pver uint32) (*Alert, error) { var alert Alert r := bytes.NewReader(serializedPayload) err := alert.Deserialize(r, pver) if err != nil { return nil, err } return &alert, nil }
[ "func", "NewAlertFromPayload", "(", "serializedPayload", "[", "]", "byte", ",", "pver", "uint32", ")", "(", "*", "Alert", ",", "error", ")", "{", "var", "alert", "Alert", "\n", "r", ":=", "bytes", ".", "NewReader", "(", "serializedPayload", ")", "\n", "err", ":=", "alert", ".", "Deserialize", "(", "r", ",", "pver", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "alert", ",", "nil", "\n", "}" ]
// NewAlertFromPayload returns an Alert with values deserialized from the // serialized payload.
[ "NewAlertFromPayload", "returns", "an", "Alert", "with", "values", "deserialized", "from", "the", "serialized", "payload", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgalert.go#L305-L313
train
btcsuite/btcd
wire/msgalert.go
NewMsgAlert
func NewMsgAlert(serializedPayload []byte, signature []byte) *MsgAlert { return &MsgAlert{ SerializedPayload: serializedPayload, Signature: signature, Payload: nil, } }
go
func NewMsgAlert(serializedPayload []byte, signature []byte) *MsgAlert { return &MsgAlert{ SerializedPayload: serializedPayload, Signature: signature, Payload: nil, } }
[ "func", "NewMsgAlert", "(", "serializedPayload", "[", "]", "byte", ",", "signature", "[", "]", "byte", ")", "*", "MsgAlert", "{", "return", "&", "MsgAlert", "{", "SerializedPayload", ":", "serializedPayload", ",", "Signature", ":", "signature", ",", "Payload", ":", "nil", ",", "}", "\n", "}" ]
// NewMsgAlert returns a new bitcoin alert message that conforms to the Message // interface. See MsgAlert for details.
[ "NewMsgAlert", "returns", "a", "new", "bitcoin", "alert", "message", "that", "conforms", "to", "the", "Message", "interface", ".", "See", "MsgAlert", "for", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/wire/msgalert.go#L401-L407
train
btcsuite/btcd
blockchain/weight.go
GetBlockWeight
func GetBlockWeight(blk *btcutil.Block) int64 { msgBlock := blk.MsgBlock() baseSize := msgBlock.SerializeSizeStripped() totalSize := msgBlock.SerializeSize() // (baseSize * 3) + totalSize return int64((baseSize * (WitnessScaleFactor - 1)) + totalSize) }
go
func GetBlockWeight(blk *btcutil.Block) int64 { msgBlock := blk.MsgBlock() baseSize := msgBlock.SerializeSizeStripped() totalSize := msgBlock.SerializeSize() // (baseSize * 3) + totalSize return int64((baseSize * (WitnessScaleFactor - 1)) + totalSize) }
[ "func", "GetBlockWeight", "(", "blk", "*", "btcutil", ".", "Block", ")", "int64", "{", "msgBlock", ":=", "blk", ".", "MsgBlock", "(", ")", "\n\n", "baseSize", ":=", "msgBlock", ".", "SerializeSizeStripped", "(", ")", "\n", "totalSize", ":=", "msgBlock", ".", "SerializeSize", "(", ")", "\n\n", "// (baseSize * 3) + totalSize", "return", "int64", "(", "(", "baseSize", "*", "(", "WitnessScaleFactor", "-", "1", ")", ")", "+", "totalSize", ")", "\n", "}" ]
// GetBlockWeight computes the value of the weight metric for a given block. // Currently the weight metric is simply the sum of the block's serialized size // without any witness data scaled proportionally by the WitnessScaleFactor, // and the block's serialized size including any witness data.
[ "GetBlockWeight", "computes", "the", "value", "of", "the", "weight", "metric", "for", "a", "given", "block", ".", "Currently", "the", "weight", "metric", "is", "simply", "the", "sum", "of", "the", "block", "s", "serialized", "size", "without", "any", "witness", "data", "scaled", "proportionally", "by", "the", "WitnessScaleFactor", "and", "the", "block", "s", "serialized", "size", "including", "any", "witness", "data", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/weight.go#L52-L60
train
btcsuite/btcd
blockchain/weight.go
GetTransactionWeight
func GetTransactionWeight(tx *btcutil.Tx) int64 { msgTx := tx.MsgTx() baseSize := msgTx.SerializeSizeStripped() totalSize := msgTx.SerializeSize() // (baseSize * 3) + totalSize return int64((baseSize * (WitnessScaleFactor - 1)) + totalSize) }
go
func GetTransactionWeight(tx *btcutil.Tx) int64 { msgTx := tx.MsgTx() baseSize := msgTx.SerializeSizeStripped() totalSize := msgTx.SerializeSize() // (baseSize * 3) + totalSize return int64((baseSize * (WitnessScaleFactor - 1)) + totalSize) }
[ "func", "GetTransactionWeight", "(", "tx", "*", "btcutil", ".", "Tx", ")", "int64", "{", "msgTx", ":=", "tx", ".", "MsgTx", "(", ")", "\n\n", "baseSize", ":=", "msgTx", ".", "SerializeSizeStripped", "(", ")", "\n", "totalSize", ":=", "msgTx", ".", "SerializeSize", "(", ")", "\n\n", "// (baseSize * 3) + totalSize", "return", "int64", "(", "(", "baseSize", "*", "(", "WitnessScaleFactor", "-", "1", ")", ")", "+", "totalSize", ")", "\n", "}" ]
// GetTransactionWeight computes the value of the weight metric for a given // transaction. Currently the weight metric is simply the sum of the // transactions's serialized size without any witness data scaled // proportionally by the WitnessScaleFactor, and the transaction's serialized // size including any witness data.
[ "GetTransactionWeight", "computes", "the", "value", "of", "the", "weight", "metric", "for", "a", "given", "transaction", ".", "Currently", "the", "weight", "metric", "is", "simply", "the", "sum", "of", "the", "transactions", "s", "serialized", "size", "without", "any", "witness", "data", "scaled", "proportionally", "by", "the", "WitnessScaleFactor", "and", "the", "transaction", "s", "serialized", "size", "including", "any", "witness", "data", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/weight.go#L67-L75
train
btcsuite/btcd
cmd/btcctl/config.go
listCommands
func listCommands() { const ( categoryChain uint8 = iota categoryWallet numCategories ) // Get a list of registered commands and categorize and filter them. cmdMethods := btcjson.RegisteredCmdMethods() categorized := make([][]string, numCategories) for _, method := range cmdMethods { flags, err := btcjson.MethodUsageFlags(method) if err != nil { // This should never happen since the method was just // returned from the package, but be safe. continue } // Skip the commands that aren't usable from this utility. if flags&unusableFlags != 0 { continue } usage, err := btcjson.MethodUsageText(method) if err != nil { // This should never happen since the method was just // returned from the package, but be safe. continue } // Categorize the command based on the usage flags. category := categoryChain if flags&btcjson.UFWalletOnly != 0 { category = categoryWallet } categorized[category] = append(categorized[category], usage) } // Display the command according to their categories. categoryTitles := make([]string, numCategories) categoryTitles[categoryChain] = "Chain Server Commands:" categoryTitles[categoryWallet] = "Wallet Server Commands (--wallet):" for category := uint8(0); category < numCategories; category++ { fmt.Println(categoryTitles[category]) for _, usage := range categorized[category] { fmt.Println(usage) } fmt.Println() } }
go
func listCommands() { const ( categoryChain uint8 = iota categoryWallet numCategories ) // Get a list of registered commands and categorize and filter them. cmdMethods := btcjson.RegisteredCmdMethods() categorized := make([][]string, numCategories) for _, method := range cmdMethods { flags, err := btcjson.MethodUsageFlags(method) if err != nil { // This should never happen since the method was just // returned from the package, but be safe. continue } // Skip the commands that aren't usable from this utility. if flags&unusableFlags != 0 { continue } usage, err := btcjson.MethodUsageText(method) if err != nil { // This should never happen since the method was just // returned from the package, but be safe. continue } // Categorize the command based on the usage flags. category := categoryChain if flags&btcjson.UFWalletOnly != 0 { category = categoryWallet } categorized[category] = append(categorized[category], usage) } // Display the command according to their categories. categoryTitles := make([]string, numCategories) categoryTitles[categoryChain] = "Chain Server Commands:" categoryTitles[categoryWallet] = "Wallet Server Commands (--wallet):" for category := uint8(0); category < numCategories; category++ { fmt.Println(categoryTitles[category]) for _, usage := range categorized[category] { fmt.Println(usage) } fmt.Println() } }
[ "func", "listCommands", "(", ")", "{", "const", "(", "categoryChain", "uint8", "=", "iota", "\n", "categoryWallet", "\n", "numCategories", "\n", ")", "\n\n", "// Get a list of registered commands and categorize and filter them.", "cmdMethods", ":=", "btcjson", ".", "RegisteredCmdMethods", "(", ")", "\n", "categorized", ":=", "make", "(", "[", "]", "[", "]", "string", ",", "numCategories", ")", "\n", "for", "_", ",", "method", ":=", "range", "cmdMethods", "{", "flags", ",", "err", ":=", "btcjson", ".", "MethodUsageFlags", "(", "method", ")", "\n", "if", "err", "!=", "nil", "{", "// This should never happen since the method was just", "// returned from the package, but be safe.", "continue", "\n", "}", "\n\n", "// Skip the commands that aren't usable from this utility.", "if", "flags", "&", "unusableFlags", "!=", "0", "{", "continue", "\n", "}", "\n\n", "usage", ",", "err", ":=", "btcjson", ".", "MethodUsageText", "(", "method", ")", "\n", "if", "err", "!=", "nil", "{", "// This should never happen since the method was just", "// returned from the package, but be safe.", "continue", "\n", "}", "\n\n", "// Categorize the command based on the usage flags.", "category", ":=", "categoryChain", "\n", "if", "flags", "&", "btcjson", ".", "UFWalletOnly", "!=", "0", "{", "category", "=", "categoryWallet", "\n", "}", "\n", "categorized", "[", "category", "]", "=", "append", "(", "categorized", "[", "category", "]", ",", "usage", ")", "\n", "}", "\n\n", "// Display the command according to their categories.", "categoryTitles", ":=", "make", "(", "[", "]", "string", ",", "numCategories", ")", "\n", "categoryTitles", "[", "categoryChain", "]", "=", "\"", "\"", "\n", "categoryTitles", "[", "categoryWallet", "]", "=", "\"", "\"", "\n", "for", "category", ":=", "uint8", "(", "0", ")", ";", "category", "<", "numCategories", ";", "category", "++", "{", "fmt", ".", "Println", "(", "categoryTitles", "[", "category", "]", ")", "\n", "for", "_", ",", "usage", ":=", "range", "categorized", "[", "category", "]", "{", "fmt", ".", "Println", "(", "usage", ")", "\n", "}", "\n", "fmt", ".", "Println", "(", ")", "\n", "}", "\n", "}" ]
// listCommands categorizes and lists all of the usable commands along with // their one-line usage.
[ "listCommands", "categorizes", "and", "lists", "all", "of", "the", "usable", "commands", "along", "with", "their", "one", "-", "line", "usage", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/cmd/btcctl/config.go#L40-L89
train
btcsuite/btcd
limits/limits_unix.go
SetLimits
func SetLimits() error { var rLimit syscall.Rlimit err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit) if err != nil { return err } if rLimit.Cur > fileLimitWant { return nil } if rLimit.Max < fileLimitMin { err = fmt.Errorf("need at least %v file descriptors", fileLimitMin) return err } if rLimit.Max < fileLimitWant { rLimit.Cur = rLimit.Max } else { rLimit.Cur = fileLimitWant } err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit) if err != nil { // try min value rLimit.Cur = fileLimitMin err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit) if err != nil { return err } } return nil }
go
func SetLimits() error { var rLimit syscall.Rlimit err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit) if err != nil { return err } if rLimit.Cur > fileLimitWant { return nil } if rLimit.Max < fileLimitMin { err = fmt.Errorf("need at least %v file descriptors", fileLimitMin) return err } if rLimit.Max < fileLimitWant { rLimit.Cur = rLimit.Max } else { rLimit.Cur = fileLimitWant } err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit) if err != nil { // try min value rLimit.Cur = fileLimitMin err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit) if err != nil { return err } } return nil }
[ "func", "SetLimits", "(", ")", "error", "{", "var", "rLimit", "syscall", ".", "Rlimit", "\n\n", "err", ":=", "syscall", ".", "Getrlimit", "(", "syscall", ".", "RLIMIT_NOFILE", ",", "&", "rLimit", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "rLimit", ".", "Cur", ">", "fileLimitWant", "{", "return", "nil", "\n", "}", "\n", "if", "rLimit", ".", "Max", "<", "fileLimitMin", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "fileLimitMin", ")", "\n", "return", "err", "\n", "}", "\n", "if", "rLimit", ".", "Max", "<", "fileLimitWant", "{", "rLimit", ".", "Cur", "=", "rLimit", ".", "Max", "\n", "}", "else", "{", "rLimit", ".", "Cur", "=", "fileLimitWant", "\n", "}", "\n", "err", "=", "syscall", ".", "Setrlimit", "(", "syscall", ".", "RLIMIT_NOFILE", ",", "&", "rLimit", ")", "\n", "if", "err", "!=", "nil", "{", "// try min value", "rLimit", ".", "Cur", "=", "fileLimitMin", "\n", "err", "=", "syscall", ".", "Setrlimit", "(", "syscall", ".", "RLIMIT_NOFILE", ",", "&", "rLimit", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// SetLimits raises some process limits to values which allow btcd and // associated utilities to run.
[ "SetLimits", "raises", "some", "process", "limits", "to", "values", "which", "allow", "btcd", "and", "associated", "utilities", "to", "run", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/limits/limits_unix.go#L21-L52
train
btcsuite/btcd
blockchain/thresholdstate.go
String
func (t ThresholdState) String() string { if s := thresholdStateStrings[t]; s != "" { return s } return fmt.Sprintf("Unknown ThresholdState (%d)", int(t)) }
go
func (t ThresholdState) String() string { if s := thresholdStateStrings[t]; s != "" { return s } return fmt.Sprintf("Unknown ThresholdState (%d)", int(t)) }
[ "func", "(", "t", "ThresholdState", ")", "String", "(", ")", "string", "{", "if", "s", ":=", "thresholdStateStrings", "[", "t", "]", ";", "s", "!=", "\"", "\"", "{", "return", "s", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "int", "(", "t", ")", ")", "\n", "}" ]
// String returns the ThresholdState as a human-readable name.
[ "String", "returns", "the", "ThresholdState", "as", "a", "human", "-", "readable", "name", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/thresholdstate.go#L59-L64
train
btcsuite/btcd
blockchain/thresholdstate.go
Lookup
func (c *thresholdStateCache) Lookup(hash *chainhash.Hash) (ThresholdState, bool) { state, ok := c.entries[*hash] return state, ok }
go
func (c *thresholdStateCache) Lookup(hash *chainhash.Hash) (ThresholdState, bool) { state, ok := c.entries[*hash] return state, ok }
[ "func", "(", "c", "*", "thresholdStateCache", ")", "Lookup", "(", "hash", "*", "chainhash", ".", "Hash", ")", "(", "ThresholdState", ",", "bool", ")", "{", "state", ",", "ok", ":=", "c", ".", "entries", "[", "*", "hash", "]", "\n", "return", "state", ",", "ok", "\n", "}" ]
// Lookup returns the threshold state associated with the given hash along with // a boolean that indicates whether or not it is valid.
[ "Lookup", "returns", "the", "threshold", "state", "associated", "with", "the", "given", "hash", "along", "with", "a", "boolean", "that", "indicates", "whether", "or", "not", "it", "is", "valid", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/thresholdstate.go#L101-L104
train
btcsuite/btcd
blockchain/thresholdstate.go
Update
func (c *thresholdStateCache) Update(hash *chainhash.Hash, state ThresholdState) { c.entries[*hash] = state }
go
func (c *thresholdStateCache) Update(hash *chainhash.Hash, state ThresholdState) { c.entries[*hash] = state }
[ "func", "(", "c", "*", "thresholdStateCache", ")", "Update", "(", "hash", "*", "chainhash", ".", "Hash", ",", "state", "ThresholdState", ")", "{", "c", ".", "entries", "[", "*", "hash", "]", "=", "state", "\n", "}" ]
// Update updates the cache to contain the provided hash to threshold state // mapping.
[ "Update", "updates", "the", "cache", "to", "contain", "the", "provided", "hash", "to", "threshold", "state", "mapping", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/thresholdstate.go#L108-L110
train
btcsuite/btcd
blockchain/thresholdstate.go
newThresholdCaches
func newThresholdCaches(numCaches uint32) []thresholdStateCache { caches := make([]thresholdStateCache, numCaches) for i := 0; i < len(caches); i++ { caches[i] = thresholdStateCache{ entries: make(map[chainhash.Hash]ThresholdState), } } return caches }
go
func newThresholdCaches(numCaches uint32) []thresholdStateCache { caches := make([]thresholdStateCache, numCaches) for i := 0; i < len(caches); i++ { caches[i] = thresholdStateCache{ entries: make(map[chainhash.Hash]ThresholdState), } } return caches }
[ "func", "newThresholdCaches", "(", "numCaches", "uint32", ")", "[", "]", "thresholdStateCache", "{", "caches", ":=", "make", "(", "[", "]", "thresholdStateCache", ",", "numCaches", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "caches", ")", ";", "i", "++", "{", "caches", "[", "i", "]", "=", "thresholdStateCache", "{", "entries", ":", "make", "(", "map", "[", "chainhash", ".", "Hash", "]", "ThresholdState", ")", ",", "}", "\n", "}", "\n", "return", "caches", "\n", "}" ]
// newThresholdCaches returns a new array of caches to be used when calculating // threshold states.
[ "newThresholdCaches", "returns", "a", "new", "array", "of", "caches", "to", "be", "used", "when", "calculating", "threshold", "states", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/thresholdstate.go#L114-L122
train
btcsuite/btcd
blockchain/thresholdstate.go
ThresholdState
func (b *BlockChain) ThresholdState(deploymentID uint32) (ThresholdState, error) { b.chainLock.Lock() state, err := b.deploymentState(b.bestChain.Tip(), deploymentID) b.chainLock.Unlock() return state, err }
go
func (b *BlockChain) ThresholdState(deploymentID uint32) (ThresholdState, error) { b.chainLock.Lock() state, err := b.deploymentState(b.bestChain.Tip(), deploymentID) b.chainLock.Unlock() return state, err }
[ "func", "(", "b", "*", "BlockChain", ")", "ThresholdState", "(", "deploymentID", "uint32", ")", "(", "ThresholdState", ",", "error", ")", "{", "b", ".", "chainLock", ".", "Lock", "(", ")", "\n", "state", ",", "err", ":=", "b", ".", "deploymentState", "(", "b", ".", "bestChain", ".", "Tip", "(", ")", ",", "deploymentID", ")", "\n", "b", ".", "chainLock", ".", "Unlock", "(", ")", "\n\n", "return", "state", ",", "err", "\n", "}" ]
// ThresholdState returns the current rule change threshold state of the given // deployment ID for the block AFTER the end of the current best chain. // // This function is safe for concurrent access.
[ "ThresholdState", "returns", "the", "current", "rule", "change", "threshold", "state", "of", "the", "given", "deployment", "ID", "for", "the", "block", "AFTER", "the", "end", "of", "the", "current", "best", "chain", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/thresholdstate.go#L266-L272
train
btcsuite/btcd
blockchain/thresholdstate.go
IsDeploymentActive
func (b *BlockChain) IsDeploymentActive(deploymentID uint32) (bool, error) { b.chainLock.Lock() state, err := b.deploymentState(b.bestChain.Tip(), deploymentID) b.chainLock.Unlock() if err != nil { return false, err } return state == ThresholdActive, nil }
go
func (b *BlockChain) IsDeploymentActive(deploymentID uint32) (bool, error) { b.chainLock.Lock() state, err := b.deploymentState(b.bestChain.Tip(), deploymentID) b.chainLock.Unlock() if err != nil { return false, err } return state == ThresholdActive, nil }
[ "func", "(", "b", "*", "BlockChain", ")", "IsDeploymentActive", "(", "deploymentID", "uint32", ")", "(", "bool", ",", "error", ")", "{", "b", ".", "chainLock", ".", "Lock", "(", ")", "\n", "state", ",", "err", ":=", "b", ".", "deploymentState", "(", "b", ".", "bestChain", ".", "Tip", "(", ")", ",", "deploymentID", ")", "\n", "b", ".", "chainLock", ".", "Unlock", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n\n", "return", "state", "==", "ThresholdActive", ",", "nil", "\n", "}" ]
// IsDeploymentActive returns true if the target deploymentID is active, and // false otherwise. // // This function is safe for concurrent access.
[ "IsDeploymentActive", "returns", "true", "if", "the", "target", "deploymentID", "is", "active", "and", "false", "otherwise", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/thresholdstate.go#L278-L287
train
btcsuite/btcd
blockchain/thresholdstate.go
initThresholdCaches
func (b *BlockChain) initThresholdCaches() error { // Initialize the warning and deployment caches by calculating the // threshold state for each of them. This will ensure the caches are // populated and any states that needed to be recalculated due to // definition changes is done now. prevNode := b.bestChain.Tip().parent for bit := uint32(0); bit < vbNumBits; bit++ { checker := bitConditionChecker{bit: bit, chain: b} cache := &b.warningCaches[bit] _, err := b.thresholdState(prevNode, checker, cache) if err != nil { return err } } for id := 0; id < len(b.chainParams.Deployments); id++ { deployment := &b.chainParams.Deployments[id] cache := &b.deploymentCaches[id] checker := deploymentChecker{deployment: deployment, chain: b} _, err := b.thresholdState(prevNode, checker, cache) if err != nil { return err } } // No warnings about unknown rules or versions until the chain is // current. if b.isCurrent() { // Warn if a high enough percentage of the last blocks have // unexpected versions. bestNode := b.bestChain.Tip() if err := b.warnUnknownVersions(bestNode); err != nil { return err } // Warn if any unknown new rules are either about to activate or // have already been activated. if err := b.warnUnknownRuleActivations(bestNode); err != nil { return err } } return nil }
go
func (b *BlockChain) initThresholdCaches() error { // Initialize the warning and deployment caches by calculating the // threshold state for each of them. This will ensure the caches are // populated and any states that needed to be recalculated due to // definition changes is done now. prevNode := b.bestChain.Tip().parent for bit := uint32(0); bit < vbNumBits; bit++ { checker := bitConditionChecker{bit: bit, chain: b} cache := &b.warningCaches[bit] _, err := b.thresholdState(prevNode, checker, cache) if err != nil { return err } } for id := 0; id < len(b.chainParams.Deployments); id++ { deployment := &b.chainParams.Deployments[id] cache := &b.deploymentCaches[id] checker := deploymentChecker{deployment: deployment, chain: b} _, err := b.thresholdState(prevNode, checker, cache) if err != nil { return err } } // No warnings about unknown rules or versions until the chain is // current. if b.isCurrent() { // Warn if a high enough percentage of the last blocks have // unexpected versions. bestNode := b.bestChain.Tip() if err := b.warnUnknownVersions(bestNode); err != nil { return err } // Warn if any unknown new rules are either about to activate or // have already been activated. if err := b.warnUnknownRuleActivations(bestNode); err != nil { return err } } return nil }
[ "func", "(", "b", "*", "BlockChain", ")", "initThresholdCaches", "(", ")", "error", "{", "// Initialize the warning and deployment caches by calculating the", "// threshold state for each of them. This will ensure the caches are", "// populated and any states that needed to be recalculated due to", "// definition changes is done now.", "prevNode", ":=", "b", ".", "bestChain", ".", "Tip", "(", ")", ".", "parent", "\n", "for", "bit", ":=", "uint32", "(", "0", ")", ";", "bit", "<", "vbNumBits", ";", "bit", "++", "{", "checker", ":=", "bitConditionChecker", "{", "bit", ":", "bit", ",", "chain", ":", "b", "}", "\n", "cache", ":=", "&", "b", ".", "warningCaches", "[", "bit", "]", "\n", "_", ",", "err", ":=", "b", ".", "thresholdState", "(", "prevNode", ",", "checker", ",", "cache", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "for", "id", ":=", "0", ";", "id", "<", "len", "(", "b", ".", "chainParams", ".", "Deployments", ")", ";", "id", "++", "{", "deployment", ":=", "&", "b", ".", "chainParams", ".", "Deployments", "[", "id", "]", "\n", "cache", ":=", "&", "b", ".", "deploymentCaches", "[", "id", "]", "\n", "checker", ":=", "deploymentChecker", "{", "deployment", ":", "deployment", ",", "chain", ":", "b", "}", "\n", "_", ",", "err", ":=", "b", ".", "thresholdState", "(", "prevNode", ",", "checker", ",", "cache", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "// No warnings about unknown rules or versions until the chain is", "// current.", "if", "b", ".", "isCurrent", "(", ")", "{", "// Warn if a high enough percentage of the last blocks have", "// unexpected versions.", "bestNode", ":=", "b", ".", "bestChain", ".", "Tip", "(", ")", "\n", "if", "err", ":=", "b", ".", "warnUnknownVersions", "(", "bestNode", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Warn if any unknown new rules are either about to activate or", "// have already been activated.", "if", "err", ":=", "b", ".", "warnUnknownRuleActivations", "(", "bestNode", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// initThresholdCaches initializes the threshold state caches for each warning // bit and defined deployment and provides warnings if the chain is current per // the warnUnknownVersions and warnUnknownRuleActivations functions.
[ "initThresholdCaches", "initializes", "the", "threshold", "state", "caches", "for", "each", "warning", "bit", "and", "defined", "deployment", "and", "provides", "warnings", "if", "the", "chain", "is", "current", "per", "the", "warnUnknownVersions", "and", "warnUnknownRuleActivations", "functions", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/thresholdstate.go#L314-L356
train
btcsuite/btcd
btcec/pubkey.go
decompressPoint
func decompressPoint(curve *KoblitzCurve, x *big.Int, ybit bool) (*big.Int, error) { // TODO: This will probably only work for secp256k1 due to // optimizations. // Y = +-sqrt(x^3 + B) x3 := new(big.Int).Mul(x, x) x3.Mul(x3, x) x3.Add(x3, curve.Params().B) x3.Mod(x3, curve.Params().P) // Now calculate sqrt mod p of x^3 + B // This code used to do a full sqrt based on tonelli/shanks, // but this was replaced by the algorithms referenced in // https://bitcointalk.org/index.php?topic=162805.msg1712294#msg1712294 y := new(big.Int).Exp(x3, curve.QPlus1Div4(), curve.Params().P) if ybit != isOdd(y) { y.Sub(curve.Params().P, y) } // Check that y is a square root of x^3 + B. y2 := new(big.Int).Mul(y, y) y2.Mod(y2, curve.Params().P) if y2.Cmp(x3) != 0 { return nil, fmt.Errorf("invalid square root") } // Verify that y-coord has expected parity. if ybit != isOdd(y) { return nil, fmt.Errorf("ybit doesn't match oddness") } return y, nil }
go
func decompressPoint(curve *KoblitzCurve, x *big.Int, ybit bool) (*big.Int, error) { // TODO: This will probably only work for secp256k1 due to // optimizations. // Y = +-sqrt(x^3 + B) x3 := new(big.Int).Mul(x, x) x3.Mul(x3, x) x3.Add(x3, curve.Params().B) x3.Mod(x3, curve.Params().P) // Now calculate sqrt mod p of x^3 + B // This code used to do a full sqrt based on tonelli/shanks, // but this was replaced by the algorithms referenced in // https://bitcointalk.org/index.php?topic=162805.msg1712294#msg1712294 y := new(big.Int).Exp(x3, curve.QPlus1Div4(), curve.Params().P) if ybit != isOdd(y) { y.Sub(curve.Params().P, y) } // Check that y is a square root of x^3 + B. y2 := new(big.Int).Mul(y, y) y2.Mod(y2, curve.Params().P) if y2.Cmp(x3) != 0 { return nil, fmt.Errorf("invalid square root") } // Verify that y-coord has expected parity. if ybit != isOdd(y) { return nil, fmt.Errorf("ybit doesn't match oddness") } return y, nil }
[ "func", "decompressPoint", "(", "curve", "*", "KoblitzCurve", ",", "x", "*", "big", ".", "Int", ",", "ybit", "bool", ")", "(", "*", "big", ".", "Int", ",", "error", ")", "{", "// TODO: This will probably only work for secp256k1 due to", "// optimizations.", "// Y = +-sqrt(x^3 + B)", "x3", ":=", "new", "(", "big", ".", "Int", ")", ".", "Mul", "(", "x", ",", "x", ")", "\n", "x3", ".", "Mul", "(", "x3", ",", "x", ")", "\n", "x3", ".", "Add", "(", "x3", ",", "curve", ".", "Params", "(", ")", ".", "B", ")", "\n", "x3", ".", "Mod", "(", "x3", ",", "curve", ".", "Params", "(", ")", ".", "P", ")", "\n\n", "// Now calculate sqrt mod p of x^3 + B", "// This code used to do a full sqrt based on tonelli/shanks,", "// but this was replaced by the algorithms referenced in", "// https://bitcointalk.org/index.php?topic=162805.msg1712294#msg1712294", "y", ":=", "new", "(", "big", ".", "Int", ")", ".", "Exp", "(", "x3", ",", "curve", ".", "QPlus1Div4", "(", ")", ",", "curve", ".", "Params", "(", ")", ".", "P", ")", "\n\n", "if", "ybit", "!=", "isOdd", "(", "y", ")", "{", "y", ".", "Sub", "(", "curve", ".", "Params", "(", ")", ".", "P", ",", "y", ")", "\n", "}", "\n\n", "// Check that y is a square root of x^3 + B.", "y2", ":=", "new", "(", "big", ".", "Int", ")", ".", "Mul", "(", "y", ",", "y", ")", "\n", "y2", ".", "Mod", "(", "y2", ",", "curve", ".", "Params", "(", ")", ".", "P", ")", "\n", "if", "y2", ".", "Cmp", "(", "x3", ")", "!=", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Verify that y-coord has expected parity.", "if", "ybit", "!=", "isOdd", "(", "y", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "y", ",", "nil", "\n", "}" ]
// decompressPoint decompresses a point on the given curve given the X point and // the solution to use.
[ "decompressPoint", "decompresses", "a", "point", "on", "the", "given", "curve", "given", "the", "X", "point", "and", "the", "solution", "to", "use", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/pubkey.go#L27-L60
train
btcsuite/btcd
btcec/pubkey.go
IsCompressedPubKey
func IsCompressedPubKey(pubKey []byte) bool { // The public key is only compressed if it is the correct length and // the format (first byte) is one of the compressed pubkey values. return len(pubKey) == PubKeyBytesLenCompressed && (pubKey[0]&^byte(0x1) == pubkeyCompressed) }
go
func IsCompressedPubKey(pubKey []byte) bool { // The public key is only compressed if it is the correct length and // the format (first byte) is one of the compressed pubkey values. return len(pubKey) == PubKeyBytesLenCompressed && (pubKey[0]&^byte(0x1) == pubkeyCompressed) }
[ "func", "IsCompressedPubKey", "(", "pubKey", "[", "]", "byte", ")", "bool", "{", "// The public key is only compressed if it is the correct length and", "// the format (first byte) is one of the compressed pubkey values.", "return", "len", "(", "pubKey", ")", "==", "PubKeyBytesLenCompressed", "&&", "(", "pubKey", "[", "0", "]", "&^", "byte", "(", "0x1", ")", "==", "pubkeyCompressed", ")", "\n", "}" ]
// IsCompressedPubKey returns true the the passed serialized public key has // been encoded in compressed format, and false otherwise.
[ "IsCompressedPubKey", "returns", "true", "the", "the", "passed", "serialized", "public", "key", "has", "been", "encoded", "in", "compressed", "format", "and", "false", "otherwise", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/pubkey.go#L70-L75
train
btcsuite/btcd
btcec/pubkey.go
ParsePubKey
func ParsePubKey(pubKeyStr []byte, curve *KoblitzCurve) (key *PublicKey, err error) { pubkey := PublicKey{} pubkey.Curve = curve if len(pubKeyStr) == 0 { return nil, errors.New("pubkey string is empty") } format := pubKeyStr[0] ybit := (format & 0x1) == 0x1 format &= ^byte(0x1) switch len(pubKeyStr) { case PubKeyBytesLenUncompressed: if format != pubkeyUncompressed && format != pubkeyHybrid { return nil, fmt.Errorf("invalid magic in pubkey str: "+ "%d", pubKeyStr[0]) } pubkey.X = new(big.Int).SetBytes(pubKeyStr[1:33]) pubkey.Y = new(big.Int).SetBytes(pubKeyStr[33:]) // hybrid keys have extra information, make use of it. if format == pubkeyHybrid && ybit != isOdd(pubkey.Y) { return nil, fmt.Errorf("ybit doesn't match oddness") } case PubKeyBytesLenCompressed: // format is 0x2 | solution, <X coordinate> // solution determines which solution of the curve we use. /// y^2 = x^3 + Curve.B if format != pubkeyCompressed { return nil, fmt.Errorf("invalid magic in compressed "+ "pubkey string: %d", pubKeyStr[0]) } pubkey.X = new(big.Int).SetBytes(pubKeyStr[1:33]) pubkey.Y, err = decompressPoint(curve, pubkey.X, ybit) if err != nil { return nil, err } default: // wrong! return nil, fmt.Errorf("invalid pub key length %d", len(pubKeyStr)) } if pubkey.X.Cmp(pubkey.Curve.Params().P) >= 0 { return nil, fmt.Errorf("pubkey X parameter is >= to P") } if pubkey.Y.Cmp(pubkey.Curve.Params().P) >= 0 { return nil, fmt.Errorf("pubkey Y parameter is >= to P") } if !pubkey.Curve.IsOnCurve(pubkey.X, pubkey.Y) { return nil, fmt.Errorf("pubkey isn't on secp256k1 curve") } return &pubkey, nil }
go
func ParsePubKey(pubKeyStr []byte, curve *KoblitzCurve) (key *PublicKey, err error) { pubkey := PublicKey{} pubkey.Curve = curve if len(pubKeyStr) == 0 { return nil, errors.New("pubkey string is empty") } format := pubKeyStr[0] ybit := (format & 0x1) == 0x1 format &= ^byte(0x1) switch len(pubKeyStr) { case PubKeyBytesLenUncompressed: if format != pubkeyUncompressed && format != pubkeyHybrid { return nil, fmt.Errorf("invalid magic in pubkey str: "+ "%d", pubKeyStr[0]) } pubkey.X = new(big.Int).SetBytes(pubKeyStr[1:33]) pubkey.Y = new(big.Int).SetBytes(pubKeyStr[33:]) // hybrid keys have extra information, make use of it. if format == pubkeyHybrid && ybit != isOdd(pubkey.Y) { return nil, fmt.Errorf("ybit doesn't match oddness") } case PubKeyBytesLenCompressed: // format is 0x2 | solution, <X coordinate> // solution determines which solution of the curve we use. /// y^2 = x^3 + Curve.B if format != pubkeyCompressed { return nil, fmt.Errorf("invalid magic in compressed "+ "pubkey string: %d", pubKeyStr[0]) } pubkey.X = new(big.Int).SetBytes(pubKeyStr[1:33]) pubkey.Y, err = decompressPoint(curve, pubkey.X, ybit) if err != nil { return nil, err } default: // wrong! return nil, fmt.Errorf("invalid pub key length %d", len(pubKeyStr)) } if pubkey.X.Cmp(pubkey.Curve.Params().P) >= 0 { return nil, fmt.Errorf("pubkey X parameter is >= to P") } if pubkey.Y.Cmp(pubkey.Curve.Params().P) >= 0 { return nil, fmt.Errorf("pubkey Y parameter is >= to P") } if !pubkey.Curve.IsOnCurve(pubkey.X, pubkey.Y) { return nil, fmt.Errorf("pubkey isn't on secp256k1 curve") } return &pubkey, nil }
[ "func", "ParsePubKey", "(", "pubKeyStr", "[", "]", "byte", ",", "curve", "*", "KoblitzCurve", ")", "(", "key", "*", "PublicKey", ",", "err", "error", ")", "{", "pubkey", ":=", "PublicKey", "{", "}", "\n", "pubkey", ".", "Curve", "=", "curve", "\n\n", "if", "len", "(", "pubKeyStr", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "format", ":=", "pubKeyStr", "[", "0", "]", "\n", "ybit", ":=", "(", "format", "&", "0x1", ")", "==", "0x1", "\n", "format", "&=", "^", "byte", "(", "0x1", ")", "\n\n", "switch", "len", "(", "pubKeyStr", ")", "{", "case", "PubKeyBytesLenUncompressed", ":", "if", "format", "!=", "pubkeyUncompressed", "&&", "format", "!=", "pubkeyHybrid", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "pubKeyStr", "[", "0", "]", ")", "\n", "}", "\n\n", "pubkey", ".", "X", "=", "new", "(", "big", ".", "Int", ")", ".", "SetBytes", "(", "pubKeyStr", "[", "1", ":", "33", "]", ")", "\n", "pubkey", ".", "Y", "=", "new", "(", "big", ".", "Int", ")", ".", "SetBytes", "(", "pubKeyStr", "[", "33", ":", "]", ")", "\n", "// hybrid keys have extra information, make use of it.", "if", "format", "==", "pubkeyHybrid", "&&", "ybit", "!=", "isOdd", "(", "pubkey", ".", "Y", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "case", "PubKeyBytesLenCompressed", ":", "// format is 0x2 | solution, <X coordinate>", "// solution determines which solution of the curve we use.", "/// y^2 = x^3 + Curve.B", "if", "format", "!=", "pubkeyCompressed", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "pubKeyStr", "[", "0", "]", ")", "\n", "}", "\n", "pubkey", ".", "X", "=", "new", "(", "big", ".", "Int", ")", ".", "SetBytes", "(", "pubKeyStr", "[", "1", ":", "33", "]", ")", "\n", "pubkey", ".", "Y", ",", "err", "=", "decompressPoint", "(", "curve", ",", "pubkey", ".", "X", ",", "ybit", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "default", ":", "// wrong!", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "pubKeyStr", ")", ")", "\n", "}", "\n\n", "if", "pubkey", ".", "X", ".", "Cmp", "(", "pubkey", ".", "Curve", ".", "Params", "(", ")", ".", "P", ")", ">=", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "pubkey", ".", "Y", ".", "Cmp", "(", "pubkey", ".", "Curve", ".", "Params", "(", ")", ".", "P", ")", ">=", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "!", "pubkey", ".", "Curve", ".", "IsOnCurve", "(", "pubkey", ".", "X", ",", "pubkey", ".", "Y", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "&", "pubkey", ",", "nil", "\n", "}" ]
// ParsePubKey parses a public key for a koblitz curve from a bytestring into a // ecdsa.Publickey, verifying that it is valid. It supports compressed, // uncompressed and hybrid signature formats.
[ "ParsePubKey", "parses", "a", "public", "key", "for", "a", "koblitz", "curve", "from", "a", "bytestring", "into", "a", "ecdsa", ".", "Publickey", "verifying", "that", "it", "is", "valid", ".", "It", "supports", "compressed", "uncompressed", "and", "hybrid", "signature", "formats", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/pubkey.go#L80-L133
train
btcsuite/btcd
btcec/pubkey.go
SerializeUncompressed
func (p *PublicKey) SerializeUncompressed() []byte { b := make([]byte, 0, PubKeyBytesLenUncompressed) b = append(b, pubkeyUncompressed) b = paddedAppend(32, b, p.X.Bytes()) return paddedAppend(32, b, p.Y.Bytes()) }
go
func (p *PublicKey) SerializeUncompressed() []byte { b := make([]byte, 0, PubKeyBytesLenUncompressed) b = append(b, pubkeyUncompressed) b = paddedAppend(32, b, p.X.Bytes()) return paddedAppend(32, b, p.Y.Bytes()) }
[ "func", "(", "p", "*", "PublicKey", ")", "SerializeUncompressed", "(", ")", "[", "]", "byte", "{", "b", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "PubKeyBytesLenUncompressed", ")", "\n", "b", "=", "append", "(", "b", ",", "pubkeyUncompressed", ")", "\n", "b", "=", "paddedAppend", "(", "32", ",", "b", ",", "p", ".", "X", ".", "Bytes", "(", ")", ")", "\n", "return", "paddedAppend", "(", "32", ",", "b", ",", "p", ".", "Y", ".", "Bytes", "(", ")", ")", "\n", "}" ]
// SerializeUncompressed serializes a public key in a 65-byte uncompressed // format.
[ "SerializeUncompressed", "serializes", "a", "public", "key", "in", "a", "65", "-", "byte", "uncompressed", "format", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/pubkey.go#L146-L151
train
btcsuite/btcd
btcec/pubkey.go
SerializeCompressed
func (p *PublicKey) SerializeCompressed() []byte { b := make([]byte, 0, PubKeyBytesLenCompressed) format := pubkeyCompressed if isOdd(p.Y) { format |= 0x1 } b = append(b, format) return paddedAppend(32, b, p.X.Bytes()) }
go
func (p *PublicKey) SerializeCompressed() []byte { b := make([]byte, 0, PubKeyBytesLenCompressed) format := pubkeyCompressed if isOdd(p.Y) { format |= 0x1 } b = append(b, format) return paddedAppend(32, b, p.X.Bytes()) }
[ "func", "(", "p", "*", "PublicKey", ")", "SerializeCompressed", "(", ")", "[", "]", "byte", "{", "b", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "PubKeyBytesLenCompressed", ")", "\n", "format", ":=", "pubkeyCompressed", "\n", "if", "isOdd", "(", "p", ".", "Y", ")", "{", "format", "|=", "0x1", "\n", "}", "\n", "b", "=", "append", "(", "b", ",", "format", ")", "\n", "return", "paddedAppend", "(", "32", ",", "b", ",", "p", ".", "X", ".", "Bytes", "(", ")", ")", "\n", "}" ]
// SerializeCompressed serializes a public key in a 33-byte compressed format.
[ "SerializeCompressed", "serializes", "a", "public", "key", "in", "a", "33", "-", "byte", "compressed", "format", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/pubkey.go#L154-L162
train
btcsuite/btcd
btcec/pubkey.go
SerializeHybrid
func (p *PublicKey) SerializeHybrid() []byte { b := make([]byte, 0, PubKeyBytesLenHybrid) format := pubkeyHybrid if isOdd(p.Y) { format |= 0x1 } b = append(b, format) b = paddedAppend(32, b, p.X.Bytes()) return paddedAppend(32, b, p.Y.Bytes()) }
go
func (p *PublicKey) SerializeHybrid() []byte { b := make([]byte, 0, PubKeyBytesLenHybrid) format := pubkeyHybrid if isOdd(p.Y) { format |= 0x1 } b = append(b, format) b = paddedAppend(32, b, p.X.Bytes()) return paddedAppend(32, b, p.Y.Bytes()) }
[ "func", "(", "p", "*", "PublicKey", ")", "SerializeHybrid", "(", ")", "[", "]", "byte", "{", "b", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "PubKeyBytesLenHybrid", ")", "\n", "format", ":=", "pubkeyHybrid", "\n", "if", "isOdd", "(", "p", ".", "Y", ")", "{", "format", "|=", "0x1", "\n", "}", "\n", "b", "=", "append", "(", "b", ",", "format", ")", "\n", "b", "=", "paddedAppend", "(", "32", ",", "b", ",", "p", ".", "X", ".", "Bytes", "(", ")", ")", "\n", "return", "paddedAppend", "(", "32", ",", "b", ",", "p", ".", "Y", ".", "Bytes", "(", ")", ")", "\n", "}" ]
// SerializeHybrid serializes a public key in a 65-byte hybrid format.
[ "SerializeHybrid", "serializes", "a", "public", "key", "in", "a", "65", "-", "byte", "hybrid", "format", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/pubkey.go#L165-L174
train
btcsuite/btcd
btcec/pubkey.go
IsEqual
func (p *PublicKey) IsEqual(otherPubKey *PublicKey) bool { return p.X.Cmp(otherPubKey.X) == 0 && p.Y.Cmp(otherPubKey.Y) == 0 }
go
func (p *PublicKey) IsEqual(otherPubKey *PublicKey) bool { return p.X.Cmp(otherPubKey.X) == 0 && p.Y.Cmp(otherPubKey.Y) == 0 }
[ "func", "(", "p", "*", "PublicKey", ")", "IsEqual", "(", "otherPubKey", "*", "PublicKey", ")", "bool", "{", "return", "p", ".", "X", ".", "Cmp", "(", "otherPubKey", ".", "X", ")", "==", "0", "&&", "p", ".", "Y", ".", "Cmp", "(", "otherPubKey", ".", "Y", ")", "==", "0", "\n", "}" ]
// IsEqual compares this PublicKey instance to the one passed, returning true if // both PublicKeys are equivalent. A PublicKey is equivalent to another, if they // both have the same X and Y coordinate.
[ "IsEqual", "compares", "this", "PublicKey", "instance", "to", "the", "one", "passed", "returning", "true", "if", "both", "PublicKeys", "are", "equivalent", ".", "A", "PublicKey", "is", "equivalent", "to", "another", "if", "they", "both", "have", "the", "same", "X", "and", "Y", "coordinate", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/pubkey.go#L179-L182
train
btcsuite/btcd
btcec/pubkey.go
paddedAppend
func paddedAppend(size uint, dst, src []byte) []byte { for i := 0; i < int(size)-len(src); i++ { dst = append(dst, 0) } return append(dst, src...) }
go
func paddedAppend(size uint, dst, src []byte) []byte { for i := 0; i < int(size)-len(src); i++ { dst = append(dst, 0) } return append(dst, src...) }
[ "func", "paddedAppend", "(", "size", "uint", ",", "dst", ",", "src", "[", "]", "byte", ")", "[", "]", "byte", "{", "for", "i", ":=", "0", ";", "i", "<", "int", "(", "size", ")", "-", "len", "(", "src", ")", ";", "i", "++", "{", "dst", "=", "append", "(", "dst", ",", "0", ")", "\n", "}", "\n", "return", "append", "(", "dst", ",", "src", "...", ")", "\n", "}" ]
// paddedAppend appends the src byte slice to dst, returning the new slice. // If the length of the source is smaller than the passed size, leading zero // bytes are appended to the dst slice before appending src.
[ "paddedAppend", "appends", "the", "src", "byte", "slice", "to", "dst", "returning", "the", "new", "slice", ".", "If", "the", "length", "of", "the", "source", "is", "smaller", "than", "the", "passed", "size", "leading", "zero", "bytes", "are", "appended", "to", "the", "dst", "slice", "before", "appending", "src", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/pubkey.go#L187-L192
train
btcsuite/btcd
btcjson/helpers.go
Bool
func Bool(v bool) *bool { p := new(bool) *p = v return p }
go
func Bool(v bool) *bool { p := new(bool) *p = v return p }
[ "func", "Bool", "(", "v", "bool", ")", "*", "bool", "{", "p", ":=", "new", "(", "bool", ")", "\n", "*", "p", "=", "v", "\n", "return", "p", "\n", "}" ]
// Bool is a helper routine that allocates a new bool value to store v and // returns a pointer to it. This is useful when assigning optional parameters.
[ "Bool", "is", "a", "helper", "routine", "that", "allocates", "a", "new", "bool", "value", "to", "store", "v", "and", "returns", "a", "pointer", "to", "it", ".", "This", "is", "useful", "when", "assigning", "optional", "parameters", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/helpers.go#L9-L13
train
btcsuite/btcd
btcjson/helpers.go
Int
func Int(v int) *int { p := new(int) *p = v return p }
go
func Int(v int) *int { p := new(int) *p = v return p }
[ "func", "Int", "(", "v", "int", ")", "*", "int", "{", "p", ":=", "new", "(", "int", ")", "\n", "*", "p", "=", "v", "\n", "return", "p", "\n", "}" ]
// Int is a helper routine that allocates a new int value to store v and // returns a pointer to it. This is useful when assigning optional parameters.
[ "Int", "is", "a", "helper", "routine", "that", "allocates", "a", "new", "int", "value", "to", "store", "v", "and", "returns", "a", "pointer", "to", "it", ".", "This", "is", "useful", "when", "assigning", "optional", "parameters", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/helpers.go#L17-L21
train
btcsuite/btcd
btcjson/helpers.go
Uint
func Uint(v uint) *uint { p := new(uint) *p = v return p }
go
func Uint(v uint) *uint { p := new(uint) *p = v return p }
[ "func", "Uint", "(", "v", "uint", ")", "*", "uint", "{", "p", ":=", "new", "(", "uint", ")", "\n", "*", "p", "=", "v", "\n", "return", "p", "\n", "}" ]
// Uint is a helper routine that allocates a new uint value to store v and // returns a pointer to it. This is useful when assigning optional parameters.
[ "Uint", "is", "a", "helper", "routine", "that", "allocates", "a", "new", "uint", "value", "to", "store", "v", "and", "returns", "a", "pointer", "to", "it", ".", "This", "is", "useful", "when", "assigning", "optional", "parameters", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/helpers.go#L25-L29
train
btcsuite/btcd
btcjson/helpers.go
Int32
func Int32(v int32) *int32 { p := new(int32) *p = v return p }
go
func Int32(v int32) *int32 { p := new(int32) *p = v return p }
[ "func", "Int32", "(", "v", "int32", ")", "*", "int32", "{", "p", ":=", "new", "(", "int32", ")", "\n", "*", "p", "=", "v", "\n", "return", "p", "\n", "}" ]
// Int32 is a helper routine that allocates a new int32 value to store v and // returns a pointer to it. This is useful when assigning optional parameters.
[ "Int32", "is", "a", "helper", "routine", "that", "allocates", "a", "new", "int32", "value", "to", "store", "v", "and", "returns", "a", "pointer", "to", "it", ".", "This", "is", "useful", "when", "assigning", "optional", "parameters", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/helpers.go#L33-L37
train
btcsuite/btcd
btcjson/helpers.go
Uint32
func Uint32(v uint32) *uint32 { p := new(uint32) *p = v return p }
go
func Uint32(v uint32) *uint32 { p := new(uint32) *p = v return p }
[ "func", "Uint32", "(", "v", "uint32", ")", "*", "uint32", "{", "p", ":=", "new", "(", "uint32", ")", "\n", "*", "p", "=", "v", "\n", "return", "p", "\n", "}" ]
// Uint32 is a helper routine that allocates a new uint32 value to store v and // returns a pointer to it. This is useful when assigning optional parameters.
[ "Uint32", "is", "a", "helper", "routine", "that", "allocates", "a", "new", "uint32", "value", "to", "store", "v", "and", "returns", "a", "pointer", "to", "it", ".", "This", "is", "useful", "when", "assigning", "optional", "parameters", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/helpers.go#L41-L45
train
btcsuite/btcd
btcjson/helpers.go
Int64
func Int64(v int64) *int64 { p := new(int64) *p = v return p }
go
func Int64(v int64) *int64 { p := new(int64) *p = v return p }
[ "func", "Int64", "(", "v", "int64", ")", "*", "int64", "{", "p", ":=", "new", "(", "int64", ")", "\n", "*", "p", "=", "v", "\n", "return", "p", "\n", "}" ]
// Int64 is a helper routine that allocates a new int64 value to store v and // returns a pointer to it. This is useful when assigning optional parameters.
[ "Int64", "is", "a", "helper", "routine", "that", "allocates", "a", "new", "int64", "value", "to", "store", "v", "and", "returns", "a", "pointer", "to", "it", ".", "This", "is", "useful", "when", "assigning", "optional", "parameters", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/helpers.go#L49-L53
train
btcsuite/btcd
btcjson/helpers.go
Uint64
func Uint64(v uint64) *uint64 { p := new(uint64) *p = v return p }
go
func Uint64(v uint64) *uint64 { p := new(uint64) *p = v return p }
[ "func", "Uint64", "(", "v", "uint64", ")", "*", "uint64", "{", "p", ":=", "new", "(", "uint64", ")", "\n", "*", "p", "=", "v", "\n", "return", "p", "\n", "}" ]
// Uint64 is a helper routine that allocates a new uint64 value to store v and // returns a pointer to it. This is useful when assigning optional parameters.
[ "Uint64", "is", "a", "helper", "routine", "that", "allocates", "a", "new", "uint64", "value", "to", "store", "v", "and", "returns", "a", "pointer", "to", "it", ".", "This", "is", "useful", "when", "assigning", "optional", "parameters", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/helpers.go#L57-L61
train
btcsuite/btcd
btcjson/helpers.go
Float64
func Float64(v float64) *float64 { p := new(float64) *p = v return p }
go
func Float64(v float64) *float64 { p := new(float64) *p = v return p }
[ "func", "Float64", "(", "v", "float64", ")", "*", "float64", "{", "p", ":=", "new", "(", "float64", ")", "\n", "*", "p", "=", "v", "\n", "return", "p", "\n", "}" ]
// Float64 is a helper routine that allocates a new float64 value to store v and // returns a pointer to it. This is useful when assigning optional parameters.
[ "Float64", "is", "a", "helper", "routine", "that", "allocates", "a", "new", "float64", "value", "to", "store", "v", "and", "returns", "a", "pointer", "to", "it", ".", "This", "is", "useful", "when", "assigning", "optional", "parameters", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/helpers.go#L65-L69
train
btcsuite/btcd
btcjson/helpers.go
String
func String(v string) *string { p := new(string) *p = v return p }
go
func String(v string) *string { p := new(string) *p = v return p }
[ "func", "String", "(", "v", "string", ")", "*", "string", "{", "p", ":=", "new", "(", "string", ")", "\n", "*", "p", "=", "v", "\n", "return", "p", "\n", "}" ]
// String is a helper routine that allocates a new string value to store v and // returns a pointer to it. This is useful when assigning optional parameters.
[ "String", "is", "a", "helper", "routine", "that", "allocates", "a", "new", "string", "value", "to", "store", "v", "and", "returns", "a", "pointer", "to", "it", ".", "This", "is", "useful", "when", "assigning", "optional", "parameters", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/helpers.go#L73-L77
train
btcsuite/btcd
database/internal/treap/mutable.go
get
func (t *Mutable) get(key []byte) (*treapNode, *treapNode) { var parent *treapNode for node := t.root; node != nil; { // Traverse left or right depending on the result of the // comparison. compareResult := bytes.Compare(key, node.key) if compareResult < 0 { parent = node node = node.left continue } if compareResult > 0 { parent = node node = node.right continue } // The key exists. return node, parent } // A nil node was reached which means the key does not exist. return nil, nil }
go
func (t *Mutable) get(key []byte) (*treapNode, *treapNode) { var parent *treapNode for node := t.root; node != nil; { // Traverse left or right depending on the result of the // comparison. compareResult := bytes.Compare(key, node.key) if compareResult < 0 { parent = node node = node.left continue } if compareResult > 0 { parent = node node = node.right continue } // The key exists. return node, parent } // A nil node was reached which means the key does not exist. return nil, nil }
[ "func", "(", "t", "*", "Mutable", ")", "get", "(", "key", "[", "]", "byte", ")", "(", "*", "treapNode", ",", "*", "treapNode", ")", "{", "var", "parent", "*", "treapNode", "\n", "for", "node", ":=", "t", ".", "root", ";", "node", "!=", "nil", ";", "{", "// Traverse left or right depending on the result of the", "// comparison.", "compareResult", ":=", "bytes", ".", "Compare", "(", "key", ",", "node", ".", "key", ")", "\n", "if", "compareResult", "<", "0", "{", "parent", "=", "node", "\n", "node", "=", "node", ".", "left", "\n", "continue", "\n", "}", "\n", "if", "compareResult", ">", "0", "{", "parent", "=", "node", "\n", "node", "=", "node", ".", "right", "\n", "continue", "\n", "}", "\n\n", "// The key exists.", "return", "node", ",", "parent", "\n", "}", "\n\n", "// A nil node was reached which means the key does not exist.", "return", "nil", ",", "nil", "\n", "}" ]
// get returns the treap node that contains the passed key and its parent. When // the found node is the root of the tree, the parent will be nil. When the key // does not exist, both the node and the parent will be nil.
[ "get", "returns", "the", "treap", "node", "that", "contains", "the", "passed", "key", "and", "its", "parent", ".", "When", "the", "found", "node", "is", "the", "root", "of", "the", "tree", "the", "parent", "will", "be", "nil", ".", "When", "the", "key", "does", "not", "exist", "both", "the", "node", "and", "the", "parent", "will", "be", "nil", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/internal/treap/mutable.go#L42-L65
train
btcsuite/btcd
database/internal/treap/mutable.go
relinkGrandparent
func (t *Mutable) relinkGrandparent(node, parent, grandparent *treapNode) { // The node is now the root of the tree when there is no grandparent. if grandparent == nil { t.root = node return } // Relink the grandparent's left or right pointer based on which side // the old parent was. if grandparent.left == parent { grandparent.left = node } else { grandparent.right = node } }
go
func (t *Mutable) relinkGrandparent(node, parent, grandparent *treapNode) { // The node is now the root of the tree when there is no grandparent. if grandparent == nil { t.root = node return } // Relink the grandparent's left or right pointer based on which side // the old parent was. if grandparent.left == parent { grandparent.left = node } else { grandparent.right = node } }
[ "func", "(", "t", "*", "Mutable", ")", "relinkGrandparent", "(", "node", ",", "parent", ",", "grandparent", "*", "treapNode", ")", "{", "// The node is now the root of the tree when there is no grandparent.", "if", "grandparent", "==", "nil", "{", "t", ".", "root", "=", "node", "\n", "return", "\n", "}", "\n\n", "// Relink the grandparent's left or right pointer based on which side", "// the old parent was.", "if", "grandparent", ".", "left", "==", "parent", "{", "grandparent", ".", "left", "=", "node", "\n", "}", "else", "{", "grandparent", ".", "right", "=", "node", "\n", "}", "\n", "}" ]
// relinkGrandparent relinks the node into the treap after it has been rotated // by changing the passed grandparent's left or right pointer, depending on // where the old parent was, to point at the passed node. Otherwise, when there // is no grandparent, it means the node is now the root of the tree, so update // it accordingly.
[ "relinkGrandparent", "relinks", "the", "node", "into", "the", "treap", "after", "it", "has", "been", "rotated", "by", "changing", "the", "passed", "grandparent", "s", "left", "or", "right", "pointer", "depending", "on", "where", "the", "old", "parent", "was", "to", "point", "at", "the", "passed", "node", ".", "Otherwise", "when", "there", "is", "no", "grandparent", "it", "means", "the", "node", "is", "now", "the", "root", "of", "the", "tree", "so", "update", "it", "accordingly", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/internal/treap/mutable.go#L89-L103
train
btcsuite/btcd
database/internal/treap/mutable.go
Delete
func (t *Mutable) Delete(key []byte) { // Find the node for the key along with its parent. There is nothing to // do if the key does not exist. node, parent := t.get(key) if node == nil { return } // When the only node in the tree is the root node and it is the one // being deleted, there is nothing else to do besides removing it. if parent == nil && node.left == nil && node.right == nil { t.root = nil t.count = 0 t.totalSize = 0 return } // Perform rotations to move the node to delete to a leaf position while // maintaining the min-heap. var isLeft bool var child *treapNode for node.left != nil || node.right != nil { // Choose the child with the higher priority. if node.left == nil { child = node.right isLeft = false } else if node.right == nil { child = node.left isLeft = true } else if node.left.priority >= node.right.priority { child = node.left isLeft = true } else { child = node.right isLeft = false } // Rotate left or right depending on which side the child node // is on. This has the effect of moving the node to delete // towards the bottom of the tree while maintaining the // min-heap. if isLeft { child.right, node.left = node, child.right } else { child.left, node.right = node, child.left } t.relinkGrandparent(child, node, parent) // The parent for the node to delete is now what was previously // its child. parent = child } // Delete the node, which is now a leaf node, by disconnecting it from // its parent. if parent.right == node { parent.right = nil } else { parent.left = nil } t.count-- t.totalSize -= nodeSize(node) }
go
func (t *Mutable) Delete(key []byte) { // Find the node for the key along with its parent. There is nothing to // do if the key does not exist. node, parent := t.get(key) if node == nil { return } // When the only node in the tree is the root node and it is the one // being deleted, there is nothing else to do besides removing it. if parent == nil && node.left == nil && node.right == nil { t.root = nil t.count = 0 t.totalSize = 0 return } // Perform rotations to move the node to delete to a leaf position while // maintaining the min-heap. var isLeft bool var child *treapNode for node.left != nil || node.right != nil { // Choose the child with the higher priority. if node.left == nil { child = node.right isLeft = false } else if node.right == nil { child = node.left isLeft = true } else if node.left.priority >= node.right.priority { child = node.left isLeft = true } else { child = node.right isLeft = false } // Rotate left or right depending on which side the child node // is on. This has the effect of moving the node to delete // towards the bottom of the tree while maintaining the // min-heap. if isLeft { child.right, node.left = node, child.right } else { child.left, node.right = node, child.left } t.relinkGrandparent(child, node, parent) // The parent for the node to delete is now what was previously // its child. parent = child } // Delete the node, which is now a leaf node, by disconnecting it from // its parent. if parent.right == node { parent.right = nil } else { parent.left = nil } t.count-- t.totalSize -= nodeSize(node) }
[ "func", "(", "t", "*", "Mutable", ")", "Delete", "(", "key", "[", "]", "byte", ")", "{", "// Find the node for the key along with its parent. There is nothing to", "// do if the key does not exist.", "node", ",", "parent", ":=", "t", ".", "get", "(", "key", ")", "\n", "if", "node", "==", "nil", "{", "return", "\n", "}", "\n\n", "// When the only node in the tree is the root node and it is the one", "// being deleted, there is nothing else to do besides removing it.", "if", "parent", "==", "nil", "&&", "node", ".", "left", "==", "nil", "&&", "node", ".", "right", "==", "nil", "{", "t", ".", "root", "=", "nil", "\n", "t", ".", "count", "=", "0", "\n", "t", ".", "totalSize", "=", "0", "\n", "return", "\n", "}", "\n\n", "// Perform rotations to move the node to delete to a leaf position while", "// maintaining the min-heap.", "var", "isLeft", "bool", "\n", "var", "child", "*", "treapNode", "\n", "for", "node", ".", "left", "!=", "nil", "||", "node", ".", "right", "!=", "nil", "{", "// Choose the child with the higher priority.", "if", "node", ".", "left", "==", "nil", "{", "child", "=", "node", ".", "right", "\n", "isLeft", "=", "false", "\n", "}", "else", "if", "node", ".", "right", "==", "nil", "{", "child", "=", "node", ".", "left", "\n", "isLeft", "=", "true", "\n", "}", "else", "if", "node", ".", "left", ".", "priority", ">=", "node", ".", "right", ".", "priority", "{", "child", "=", "node", ".", "left", "\n", "isLeft", "=", "true", "\n", "}", "else", "{", "child", "=", "node", ".", "right", "\n", "isLeft", "=", "false", "\n", "}", "\n\n", "// Rotate left or right depending on which side the child node", "// is on. This has the effect of moving the node to delete", "// towards the bottom of the tree while maintaining the", "// min-heap.", "if", "isLeft", "{", "child", ".", "right", ",", "node", ".", "left", "=", "node", ",", "child", ".", "right", "\n", "}", "else", "{", "child", ".", "left", ",", "node", ".", "right", "=", "node", ",", "child", ".", "left", "\n", "}", "\n", "t", ".", "relinkGrandparent", "(", "child", ",", "node", ",", "parent", ")", "\n\n", "// The parent for the node to delete is now what was previously", "// its child.", "parent", "=", "child", "\n", "}", "\n\n", "// Delete the node, which is now a leaf node, by disconnecting it from", "// its parent.", "if", "parent", ".", "right", "==", "node", "{", "parent", ".", "right", "=", "nil", "\n", "}", "else", "{", "parent", ".", "left", "=", "nil", "\n", "}", "\n", "t", ".", "count", "--", "\n", "t", ".", "totalSize", "-=", "nodeSize", "(", "node", ")", "\n", "}" ]
// Delete removes the passed key if it exists.
[ "Delete", "removes", "the", "passed", "key", "if", "it", "exists", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/internal/treap/mutable.go#L179-L241
train
btcsuite/btcd
database/internal/treap/mutable.go
Reset
func (t *Mutable) Reset() { t.count = 0 t.totalSize = 0 t.root = nil }
go
func (t *Mutable) Reset() { t.count = 0 t.totalSize = 0 t.root = nil }
[ "func", "(", "t", "*", "Mutable", ")", "Reset", "(", ")", "{", "t", ".", "count", "=", "0", "\n", "t", ".", "totalSize", "=", "0", "\n", "t", ".", "root", "=", "nil", "\n", "}" ]
// Reset efficiently removes all items in the treap.
[ "Reset", "efficiently", "removes", "all", "items", "in", "the", "treap", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/internal/treap/mutable.go#L268-L272
train
btcsuite/btcd
database/internal/treap/immutable.go
cloneTreapNode
func cloneTreapNode(node *treapNode) *treapNode { return &treapNode{ key: node.key, value: node.value, priority: node.priority, left: node.left, right: node.right, } }
go
func cloneTreapNode(node *treapNode) *treapNode { return &treapNode{ key: node.key, value: node.value, priority: node.priority, left: node.left, right: node.right, } }
[ "func", "cloneTreapNode", "(", "node", "*", "treapNode", ")", "*", "treapNode", "{", "return", "&", "treapNode", "{", "key", ":", "node", ".", "key", ",", "value", ":", "node", ".", "value", ",", "priority", ":", "node", ".", "priority", ",", "left", ":", "node", ".", "left", ",", "right", ":", "node", ".", "right", ",", "}", "\n", "}" ]
// cloneTreapNode returns a shallow copy of the passed node.
[ "cloneTreapNode", "returns", "a", "shallow", "copy", "of", "the", "passed", "node", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/internal/treap/immutable.go#L13-L21
train
btcsuite/btcd
database/internal/treap/immutable.go
newImmutable
func newImmutable(root *treapNode, count int, totalSize uint64) *Immutable { return &Immutable{root: root, count: count, totalSize: totalSize} }
go
func newImmutable(root *treapNode, count int, totalSize uint64) *Immutable { return &Immutable{root: root, count: count, totalSize: totalSize} }
[ "func", "newImmutable", "(", "root", "*", "treapNode", ",", "count", "int", ",", "totalSize", "uint64", ")", "*", "Immutable", "{", "return", "&", "Immutable", "{", "root", ":", "root", ",", "count", ":", "count", ",", "totalSize", ":", "totalSize", "}", "\n", "}" ]
// newImmutable returns a new immutable treap given the passed parameters.
[ "newImmutable", "returns", "a", "new", "immutable", "treap", "given", "the", "passed", "parameters", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/internal/treap/immutable.go#L49-L51
train
btcsuite/btcd
database/internal/treap/immutable.go
Delete
func (t *Immutable) Delete(key []byte) *Immutable { // Find the node for the key while constructing a list of parents while // doing so. var parents parentStack var delNode *treapNode for node := t.root; node != nil; { parents.Push(node) // Traverse left or right depending on the result of the // comparison. compareResult := bytes.Compare(key, node.key) if compareResult < 0 { node = node.left continue } if compareResult > 0 { node = node.right continue } // The key exists. delNode = node break } // There is nothing to do if the key does not exist. if delNode == nil { return t } // When the only node in the tree is the root node and it is the one // being deleted, there is nothing else to do besides removing it. parent := parents.At(1) if parent == nil && delNode.left == nil && delNode.right == nil { return newImmutable(nil, 0, 0) } // Construct a replaced list of parents and the node to delete itself. // This is done because this is an immutable data structure and // therefore all ancestors of the node that will be deleted, up to and // including the root, need to be replaced. var newParents parentStack for i := parents.Len(); i > 0; i-- { node := parents.At(i - 1) nodeCopy := cloneTreapNode(node) if oldParent := newParents.At(0); oldParent != nil { if oldParent.left == node { oldParent.left = nodeCopy } else { oldParent.right = nodeCopy } } newParents.Push(nodeCopy) } delNode = newParents.Pop() parent = newParents.At(0) // Perform rotations to move the node to delete to a leaf position while // maintaining the min-heap while replacing the modified children. var child *treapNode newRoot := newParents.At(newParents.Len() - 1) for delNode.left != nil || delNode.right != nil { // Choose the child with the higher priority. var isLeft bool if delNode.left == nil { child = delNode.right } else if delNode.right == nil { child = delNode.left isLeft = true } else if delNode.left.priority >= delNode.right.priority { child = delNode.left isLeft = true } else { child = delNode.right } // Rotate left or right depending on which side the child node // is on. This has the effect of moving the node to delete // towards the bottom of the tree while maintaining the // min-heap. child = cloneTreapNode(child) if isLeft { child.right, delNode.left = delNode, child.right } else { child.left, delNode.right = delNode, child.left } // Either set the new root of the tree when there is no // grandparent or relink the grandparent to the node based on // which side the old parent the node is replacing was on. // // Since the node to be deleted was just moved down a level, the // new grandparent is now the current parent and the new parent // is the current child. if parent == nil { newRoot = child } else if parent.left == delNode { parent.left = child } else { parent.right = child } // The parent for the node to delete is now what was previously // its child. parent = child } // Delete the node, which is now a leaf node, by disconnecting it from // its parent. if parent.right == delNode { parent.right = nil } else { parent.left = nil } return newImmutable(newRoot, t.count-1, t.totalSize-nodeSize(delNode)) }
go
func (t *Immutable) Delete(key []byte) *Immutable { // Find the node for the key while constructing a list of parents while // doing so. var parents parentStack var delNode *treapNode for node := t.root; node != nil; { parents.Push(node) // Traverse left or right depending on the result of the // comparison. compareResult := bytes.Compare(key, node.key) if compareResult < 0 { node = node.left continue } if compareResult > 0 { node = node.right continue } // The key exists. delNode = node break } // There is nothing to do if the key does not exist. if delNode == nil { return t } // When the only node in the tree is the root node and it is the one // being deleted, there is nothing else to do besides removing it. parent := parents.At(1) if parent == nil && delNode.left == nil && delNode.right == nil { return newImmutable(nil, 0, 0) } // Construct a replaced list of parents and the node to delete itself. // This is done because this is an immutable data structure and // therefore all ancestors of the node that will be deleted, up to and // including the root, need to be replaced. var newParents parentStack for i := parents.Len(); i > 0; i-- { node := parents.At(i - 1) nodeCopy := cloneTreapNode(node) if oldParent := newParents.At(0); oldParent != nil { if oldParent.left == node { oldParent.left = nodeCopy } else { oldParent.right = nodeCopy } } newParents.Push(nodeCopy) } delNode = newParents.Pop() parent = newParents.At(0) // Perform rotations to move the node to delete to a leaf position while // maintaining the min-heap while replacing the modified children. var child *treapNode newRoot := newParents.At(newParents.Len() - 1) for delNode.left != nil || delNode.right != nil { // Choose the child with the higher priority. var isLeft bool if delNode.left == nil { child = delNode.right } else if delNode.right == nil { child = delNode.left isLeft = true } else if delNode.left.priority >= delNode.right.priority { child = delNode.left isLeft = true } else { child = delNode.right } // Rotate left or right depending on which side the child node // is on. This has the effect of moving the node to delete // towards the bottom of the tree while maintaining the // min-heap. child = cloneTreapNode(child) if isLeft { child.right, delNode.left = delNode, child.right } else { child.left, delNode.right = delNode, child.left } // Either set the new root of the tree when there is no // grandparent or relink the grandparent to the node based on // which side the old parent the node is replacing was on. // // Since the node to be deleted was just moved down a level, the // new grandparent is now the current parent and the new parent // is the current child. if parent == nil { newRoot = child } else if parent.left == delNode { parent.left = child } else { parent.right = child } // The parent for the node to delete is now what was previously // its child. parent = child } // Delete the node, which is now a leaf node, by disconnecting it from // its parent. if parent.right == delNode { parent.right = nil } else { parent.left = nil } return newImmutable(newRoot, t.count-1, t.totalSize-nodeSize(delNode)) }
[ "func", "(", "t", "*", "Immutable", ")", "Delete", "(", "key", "[", "]", "byte", ")", "*", "Immutable", "{", "// Find the node for the key while constructing a list of parents while", "// doing so.", "var", "parents", "parentStack", "\n", "var", "delNode", "*", "treapNode", "\n", "for", "node", ":=", "t", ".", "root", ";", "node", "!=", "nil", ";", "{", "parents", ".", "Push", "(", "node", ")", "\n\n", "// Traverse left or right depending on the result of the", "// comparison.", "compareResult", ":=", "bytes", ".", "Compare", "(", "key", ",", "node", ".", "key", ")", "\n", "if", "compareResult", "<", "0", "{", "node", "=", "node", ".", "left", "\n", "continue", "\n", "}", "\n", "if", "compareResult", ">", "0", "{", "node", "=", "node", ".", "right", "\n", "continue", "\n", "}", "\n\n", "// The key exists.", "delNode", "=", "node", "\n", "break", "\n", "}", "\n\n", "// There is nothing to do if the key does not exist.", "if", "delNode", "==", "nil", "{", "return", "t", "\n", "}", "\n\n", "// When the only node in the tree is the root node and it is the one", "// being deleted, there is nothing else to do besides removing it.", "parent", ":=", "parents", ".", "At", "(", "1", ")", "\n", "if", "parent", "==", "nil", "&&", "delNode", ".", "left", "==", "nil", "&&", "delNode", ".", "right", "==", "nil", "{", "return", "newImmutable", "(", "nil", ",", "0", ",", "0", ")", "\n", "}", "\n\n", "// Construct a replaced list of parents and the node to delete itself.", "// This is done because this is an immutable data structure and", "// therefore all ancestors of the node that will be deleted, up to and", "// including the root, need to be replaced.", "var", "newParents", "parentStack", "\n", "for", "i", ":=", "parents", ".", "Len", "(", ")", ";", "i", ">", "0", ";", "i", "--", "{", "node", ":=", "parents", ".", "At", "(", "i", "-", "1", ")", "\n", "nodeCopy", ":=", "cloneTreapNode", "(", "node", ")", "\n", "if", "oldParent", ":=", "newParents", ".", "At", "(", "0", ")", ";", "oldParent", "!=", "nil", "{", "if", "oldParent", ".", "left", "==", "node", "{", "oldParent", ".", "left", "=", "nodeCopy", "\n", "}", "else", "{", "oldParent", ".", "right", "=", "nodeCopy", "\n", "}", "\n", "}", "\n", "newParents", ".", "Push", "(", "nodeCopy", ")", "\n", "}", "\n", "delNode", "=", "newParents", ".", "Pop", "(", ")", "\n", "parent", "=", "newParents", ".", "At", "(", "0", ")", "\n\n", "// Perform rotations to move the node to delete to a leaf position while", "// maintaining the min-heap while replacing the modified children.", "var", "child", "*", "treapNode", "\n", "newRoot", ":=", "newParents", ".", "At", "(", "newParents", ".", "Len", "(", ")", "-", "1", ")", "\n", "for", "delNode", ".", "left", "!=", "nil", "||", "delNode", ".", "right", "!=", "nil", "{", "// Choose the child with the higher priority.", "var", "isLeft", "bool", "\n", "if", "delNode", ".", "left", "==", "nil", "{", "child", "=", "delNode", ".", "right", "\n", "}", "else", "if", "delNode", ".", "right", "==", "nil", "{", "child", "=", "delNode", ".", "left", "\n", "isLeft", "=", "true", "\n", "}", "else", "if", "delNode", ".", "left", ".", "priority", ">=", "delNode", ".", "right", ".", "priority", "{", "child", "=", "delNode", ".", "left", "\n", "isLeft", "=", "true", "\n", "}", "else", "{", "child", "=", "delNode", ".", "right", "\n", "}", "\n\n", "// Rotate left or right depending on which side the child node", "// is on. This has the effect of moving the node to delete", "// towards the bottom of the tree while maintaining the", "// min-heap.", "child", "=", "cloneTreapNode", "(", "child", ")", "\n", "if", "isLeft", "{", "child", ".", "right", ",", "delNode", ".", "left", "=", "delNode", ",", "child", ".", "right", "\n", "}", "else", "{", "child", ".", "left", ",", "delNode", ".", "right", "=", "delNode", ",", "child", ".", "left", "\n", "}", "\n\n", "// Either set the new root of the tree when there is no", "// grandparent or relink the grandparent to the node based on", "// which side the old parent the node is replacing was on.", "//", "// Since the node to be deleted was just moved down a level, the", "// new grandparent is now the current parent and the new parent", "// is the current child.", "if", "parent", "==", "nil", "{", "newRoot", "=", "child", "\n", "}", "else", "if", "parent", ".", "left", "==", "delNode", "{", "parent", ".", "left", "=", "child", "\n", "}", "else", "{", "parent", ".", "right", "=", "child", "\n", "}", "\n\n", "// The parent for the node to delete is now what was previously", "// its child.", "parent", "=", "child", "\n", "}", "\n\n", "// Delete the node, which is now a leaf node, by disconnecting it from", "// its parent.", "if", "parent", ".", "right", "==", "delNode", "{", "parent", ".", "right", "=", "nil", "\n", "}", "else", "{", "parent", ".", "left", "=", "nil", "\n", "}", "\n\n", "return", "newImmutable", "(", "newRoot", ",", "t", ".", "count", "-", "1", ",", "t", ".", "totalSize", "-", "nodeSize", "(", "delNode", ")", ")", "\n", "}" ]
// Delete removes the passed key from the treap and returns the resulting treap // if it exists. The original immutable treap is returned if the key does not // exist.
[ "Delete", "removes", "the", "passed", "key", "from", "the", "treap", "and", "returns", "the", "resulting", "treap", "if", "it", "exists", ".", "The", "original", "immutable", "treap", "is", "returned", "if", "the", "key", "does", "not", "exist", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/internal/treap/immutable.go#L214-L330
train
btcsuite/btcd
peer/mruinvmap.go
Exists
func (m *mruInventoryMap) Exists(iv *wire.InvVect) bool { m.invMtx.Lock() _, exists := m.invMap[*iv] m.invMtx.Unlock() return exists }
go
func (m *mruInventoryMap) Exists(iv *wire.InvVect) bool { m.invMtx.Lock() _, exists := m.invMap[*iv] m.invMtx.Unlock() return exists }
[ "func", "(", "m", "*", "mruInventoryMap", ")", "Exists", "(", "iv", "*", "wire", ".", "InvVect", ")", "bool", "{", "m", ".", "invMtx", ".", "Lock", "(", ")", "\n", "_", ",", "exists", ":=", "m", ".", "invMap", "[", "*", "iv", "]", "\n", "m", ".", "invMtx", ".", "Unlock", "(", ")", "\n\n", "return", "exists", "\n", "}" ]
// Exists returns whether or not the passed inventory item is in the map. // // This function is safe for concurrent access.
[ "Exists", "returns", "whether", "or", "not", "the", "passed", "inventory", "item", "is", "in", "the", "map", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/mruinvmap.go#L51-L57
train
btcsuite/btcd
peer/mruinvmap.go
Add
func (m *mruInventoryMap) Add(iv *wire.InvVect) { m.invMtx.Lock() defer m.invMtx.Unlock() // When the limit is zero, nothing can be added to the map, so just // return. if m.limit == 0 { return } // When the entry already exists move it to the front of the list // thereby marking it most recently used. if node, exists := m.invMap[*iv]; exists { m.invList.MoveToFront(node) return } // Evict the least recently used entry (back of the list) if the the new // entry would exceed the size limit for the map. Also reuse the list // node so a new one doesn't have to be allocated. if uint(len(m.invMap))+1 > m.limit { node := m.invList.Back() lru := node.Value.(*wire.InvVect) // Evict least recently used item. delete(m.invMap, *lru) // Reuse the list node of the item that was just evicted for the // new item. node.Value = iv m.invList.MoveToFront(node) m.invMap[*iv] = node return } // The limit hasn't been reached yet, so just add the new item. node := m.invList.PushFront(iv) m.invMap[*iv] = node }
go
func (m *mruInventoryMap) Add(iv *wire.InvVect) { m.invMtx.Lock() defer m.invMtx.Unlock() // When the limit is zero, nothing can be added to the map, so just // return. if m.limit == 0 { return } // When the entry already exists move it to the front of the list // thereby marking it most recently used. if node, exists := m.invMap[*iv]; exists { m.invList.MoveToFront(node) return } // Evict the least recently used entry (back of the list) if the the new // entry would exceed the size limit for the map. Also reuse the list // node so a new one doesn't have to be allocated. if uint(len(m.invMap))+1 > m.limit { node := m.invList.Back() lru := node.Value.(*wire.InvVect) // Evict least recently used item. delete(m.invMap, *lru) // Reuse the list node of the item that was just evicted for the // new item. node.Value = iv m.invList.MoveToFront(node) m.invMap[*iv] = node return } // The limit hasn't been reached yet, so just add the new item. node := m.invList.PushFront(iv) m.invMap[*iv] = node }
[ "func", "(", "m", "*", "mruInventoryMap", ")", "Add", "(", "iv", "*", "wire", ".", "InvVect", ")", "{", "m", ".", "invMtx", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "invMtx", ".", "Unlock", "(", ")", "\n\n", "// When the limit is zero, nothing can be added to the map, so just", "// return.", "if", "m", ".", "limit", "==", "0", "{", "return", "\n", "}", "\n\n", "// When the entry already exists move it to the front of the list", "// thereby marking it most recently used.", "if", "node", ",", "exists", ":=", "m", ".", "invMap", "[", "*", "iv", "]", ";", "exists", "{", "m", ".", "invList", ".", "MoveToFront", "(", "node", ")", "\n", "return", "\n", "}", "\n\n", "// Evict the least recently used entry (back of the list) if the the new", "// entry would exceed the size limit for the map. Also reuse the list", "// node so a new one doesn't have to be allocated.", "if", "uint", "(", "len", "(", "m", ".", "invMap", ")", ")", "+", "1", ">", "m", ".", "limit", "{", "node", ":=", "m", ".", "invList", ".", "Back", "(", ")", "\n", "lru", ":=", "node", ".", "Value", ".", "(", "*", "wire", ".", "InvVect", ")", "\n\n", "// Evict least recently used item.", "delete", "(", "m", ".", "invMap", ",", "*", "lru", ")", "\n\n", "// Reuse the list node of the item that was just evicted for the", "// new item.", "node", ".", "Value", "=", "iv", "\n", "m", ".", "invList", ".", "MoveToFront", "(", "node", ")", "\n", "m", ".", "invMap", "[", "*", "iv", "]", "=", "node", "\n", "return", "\n", "}", "\n\n", "// The limit hasn't been reached yet, so just add the new item.", "node", ":=", "m", ".", "invList", ".", "PushFront", "(", "iv", ")", "\n", "m", ".", "invMap", "[", "*", "iv", "]", "=", "node", "\n", "}" ]
// Add adds the passed inventory to the map and handles eviction of the oldest // item if adding the new item would exceed the max limit. Adding an existing // item makes it the most recently used item. // // This function is safe for concurrent access.
[ "Add", "adds", "the", "passed", "inventory", "to", "the", "map", "and", "handles", "eviction", "of", "the", "oldest", "item", "if", "adding", "the", "new", "item", "would", "exceed", "the", "max", "limit", ".", "Adding", "an", "existing", "item", "makes", "it", "the", "most", "recently", "used", "item", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/peer/mruinvmap.go#L64-L102
train
btcsuite/btcd
mempool/estimatefee.go
ToBtcPerKb
func (rate SatoshiPerByte) ToBtcPerKb() BtcPerKilobyte { // If our rate is the error value, return that. if rate == SatoshiPerByte(-1.0) { return -1.0 } return BtcPerKilobyte(float64(rate) * bytePerKb * btcPerSatoshi) }
go
func (rate SatoshiPerByte) ToBtcPerKb() BtcPerKilobyte { // If our rate is the error value, return that. if rate == SatoshiPerByte(-1.0) { return -1.0 } return BtcPerKilobyte(float64(rate) * bytePerKb * btcPerSatoshi) }
[ "func", "(", "rate", "SatoshiPerByte", ")", "ToBtcPerKb", "(", ")", "BtcPerKilobyte", "{", "// If our rate is the error value, return that.", "if", "rate", "==", "SatoshiPerByte", "(", "-", "1.0", ")", "{", "return", "-", "1.0", "\n", "}", "\n\n", "return", "BtcPerKilobyte", "(", "float64", "(", "rate", ")", "*", "bytePerKb", "*", "btcPerSatoshi", ")", "\n", "}" ]
// ToBtcPerKb returns a float value that represents the given // SatoshiPerByte converted to satoshis per kb.
[ "ToBtcPerKb", "returns", "a", "float", "value", "that", "represents", "the", "given", "SatoshiPerByte", "converted", "to", "satoshis", "per", "kb", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/estimatefee.go#L67-L74
train
btcsuite/btcd
mempool/estimatefee.go
Fee
func (rate SatoshiPerByte) Fee(size uint32) btcutil.Amount { // If our rate is the error value, return that. if rate == SatoshiPerByte(-1) { return btcutil.Amount(-1) } return btcutil.Amount(float64(rate) * float64(size)) }
go
func (rate SatoshiPerByte) Fee(size uint32) btcutil.Amount { // If our rate is the error value, return that. if rate == SatoshiPerByte(-1) { return btcutil.Amount(-1) } return btcutil.Amount(float64(rate) * float64(size)) }
[ "func", "(", "rate", "SatoshiPerByte", ")", "Fee", "(", "size", "uint32", ")", "btcutil", ".", "Amount", "{", "// If our rate is the error value, return that.", "if", "rate", "==", "SatoshiPerByte", "(", "-", "1", ")", "{", "return", "btcutil", ".", "Amount", "(", "-", "1", ")", "\n", "}", "\n\n", "return", "btcutil", ".", "Amount", "(", "float64", "(", "rate", ")", "*", "float64", "(", "size", ")", ")", "\n", "}" ]
// Fee returns the fee for a transaction of a given size for // the given fee rate.
[ "Fee", "returns", "the", "fee", "for", "a", "transaction", "of", "a", "given", "size", "for", "the", "given", "fee", "rate", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/estimatefee.go#L78-L85
train
btcsuite/btcd
mempool/estimatefee.go
NewSatoshiPerByte
func NewSatoshiPerByte(fee btcutil.Amount, size uint32) SatoshiPerByte { return SatoshiPerByte(float64(fee) / float64(size)) }
go
func NewSatoshiPerByte(fee btcutil.Amount, size uint32) SatoshiPerByte { return SatoshiPerByte(float64(fee) / float64(size)) }
[ "func", "NewSatoshiPerByte", "(", "fee", "btcutil", ".", "Amount", ",", "size", "uint32", ")", "SatoshiPerByte", "{", "return", "SatoshiPerByte", "(", "float64", "(", "fee", ")", "/", "float64", "(", "size", ")", ")", "\n", "}" ]
// NewSatoshiPerByte creates a SatoshiPerByte from an Amount and a // size in bytes.
[ "NewSatoshiPerByte", "creates", "a", "SatoshiPerByte", "from", "an", "Amount", "and", "a", "size", "in", "bytes", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/estimatefee.go#L89-L91
train
btcsuite/btcd
mempool/estimatefee.go
NewFeeEstimator
func NewFeeEstimator(maxRollback, minRegisteredBlocks uint32) *FeeEstimator { return &FeeEstimator{ maxRollback: maxRollback, minRegisteredBlocks: minRegisteredBlocks, lastKnownHeight: mining.UnminedHeight, binSize: estimateFeeBinSize, maxReplacements: estimateFeeMaxReplacements, observed: make(map[chainhash.Hash]*observedTransaction), dropped: make([]*registeredBlock, 0, maxRollback), } }
go
func NewFeeEstimator(maxRollback, minRegisteredBlocks uint32) *FeeEstimator { return &FeeEstimator{ maxRollback: maxRollback, minRegisteredBlocks: minRegisteredBlocks, lastKnownHeight: mining.UnminedHeight, binSize: estimateFeeBinSize, maxReplacements: estimateFeeMaxReplacements, observed: make(map[chainhash.Hash]*observedTransaction), dropped: make([]*registeredBlock, 0, maxRollback), } }
[ "func", "NewFeeEstimator", "(", "maxRollback", ",", "minRegisteredBlocks", "uint32", ")", "*", "FeeEstimator", "{", "return", "&", "FeeEstimator", "{", "maxRollback", ":", "maxRollback", ",", "minRegisteredBlocks", ":", "minRegisteredBlocks", ",", "lastKnownHeight", ":", "mining", ".", "UnminedHeight", ",", "binSize", ":", "estimateFeeBinSize", ",", "maxReplacements", ":", "estimateFeeMaxReplacements", ",", "observed", ":", "make", "(", "map", "[", "chainhash", ".", "Hash", "]", "*", "observedTransaction", ")", ",", "dropped", ":", "make", "(", "[", "]", "*", "registeredBlock", ",", "0", ",", "maxRollback", ")", ",", "}", "\n", "}" ]
// NewFeeEstimator creates a FeeEstimator for which at most maxRollback blocks // can be unregistered and which returns an error unless minRegisteredBlocks // have been registered with it.
[ "NewFeeEstimator", "creates", "a", "FeeEstimator", "for", "which", "at", "most", "maxRollback", "blocks", "can", "be", "unregistered", "and", "which", "returns", "an", "error", "unless", "minRegisteredBlocks", "have", "been", "registered", "with", "it", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/estimatefee.go#L186-L196
train
btcsuite/btcd
mempool/estimatefee.go
ObserveTransaction
func (ef *FeeEstimator) ObserveTransaction(t *TxDesc) { ef.mtx.Lock() defer ef.mtx.Unlock() // If we haven't seen a block yet we don't know when this one arrived, // so we ignore it. if ef.lastKnownHeight == mining.UnminedHeight { return } hash := *t.Tx.Hash() if _, ok := ef.observed[hash]; !ok { size := uint32(GetTxVirtualSize(t.Tx)) ef.observed[hash] = &observedTransaction{ hash: hash, feeRate: NewSatoshiPerByte(btcutil.Amount(t.Fee), size), observed: t.Height, mined: mining.UnminedHeight, } } }
go
func (ef *FeeEstimator) ObserveTransaction(t *TxDesc) { ef.mtx.Lock() defer ef.mtx.Unlock() // If we haven't seen a block yet we don't know when this one arrived, // so we ignore it. if ef.lastKnownHeight == mining.UnminedHeight { return } hash := *t.Tx.Hash() if _, ok := ef.observed[hash]; !ok { size := uint32(GetTxVirtualSize(t.Tx)) ef.observed[hash] = &observedTransaction{ hash: hash, feeRate: NewSatoshiPerByte(btcutil.Amount(t.Fee), size), observed: t.Height, mined: mining.UnminedHeight, } } }
[ "func", "(", "ef", "*", "FeeEstimator", ")", "ObserveTransaction", "(", "t", "*", "TxDesc", ")", "{", "ef", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "ef", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "// If we haven't seen a block yet we don't know when this one arrived,", "// so we ignore it.", "if", "ef", ".", "lastKnownHeight", "==", "mining", ".", "UnminedHeight", "{", "return", "\n", "}", "\n\n", "hash", ":=", "*", "t", ".", "Tx", ".", "Hash", "(", ")", "\n", "if", "_", ",", "ok", ":=", "ef", ".", "observed", "[", "hash", "]", ";", "!", "ok", "{", "size", ":=", "uint32", "(", "GetTxVirtualSize", "(", "t", ".", "Tx", ")", ")", "\n\n", "ef", ".", "observed", "[", "hash", "]", "=", "&", "observedTransaction", "{", "hash", ":", "hash", ",", "feeRate", ":", "NewSatoshiPerByte", "(", "btcutil", ".", "Amount", "(", "t", ".", "Fee", ")", ",", "size", ")", ",", "observed", ":", "t", ".", "Height", ",", "mined", ":", "mining", ".", "UnminedHeight", ",", "}", "\n", "}", "\n", "}" ]
// ObserveTransaction is called when a new transaction is observed in the mempool.
[ "ObserveTransaction", "is", "called", "when", "a", "new", "transaction", "is", "observed", "in", "the", "mempool", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/estimatefee.go#L199-L220
train
btcsuite/btcd
mempool/estimatefee.go
RegisterBlock
func (ef *FeeEstimator) RegisterBlock(block *btcutil.Block) error { ef.mtx.Lock() defer ef.mtx.Unlock() // The previous sorted list is invalid, so delete it. ef.cached = nil height := block.Height() if height != ef.lastKnownHeight+1 && ef.lastKnownHeight != mining.UnminedHeight { return fmt.Errorf("intermediate block not recorded; current height is %d; new height is %d", ef.lastKnownHeight, height) } // Update the last known height. ef.lastKnownHeight = height ef.numBlocksRegistered++ // Randomly order txs in block. transactions := make(map[*btcutil.Tx]struct{}) for _, t := range block.Transactions() { transactions[t] = struct{}{} } // Count the number of replacements we make per bin so that we don't // replace too many. var replacementCounts [estimateFeeDepth]int // Keep track of which txs were dropped in case of an orphan block. dropped := &registeredBlock{ hash: *block.Hash(), transactions: make([]*observedTransaction, 0, 100), } // Go through the txs in the block. for t := range transactions { hash := *t.Hash() // Have we observed this tx in the mempool? o, ok := ef.observed[hash] if !ok { continue } // Put the observed tx in the oppropriate bin. blocksToConfirm := height - o.observed - 1 // This shouldn't happen if the fee estimator works correctly, // but return an error if it does. if o.mined != mining.UnminedHeight { log.Error("Estimate fee: transaction ", hash.String(), " has already been mined") return errors.New("Transaction has already been mined") } // This shouldn't happen but check just in case to avoid // an out-of-bounds array index later. if blocksToConfirm >= estimateFeeDepth { continue } // Make sure we do not replace too many transactions per min. if replacementCounts[blocksToConfirm] == int(ef.maxReplacements) { continue } o.mined = height replacementCounts[blocksToConfirm]++ bin := ef.bin[blocksToConfirm] // Remove a random element and replace it with this new tx. if len(bin) == int(ef.binSize) { // Don't drop transactions we have just added from this same block. l := int(ef.binSize) - replacementCounts[blocksToConfirm] drop := rand.Intn(l) dropped.transactions = append(dropped.transactions, bin[drop]) bin[drop] = bin[l-1] bin[l-1] = o } else { bin = append(bin, o) } ef.bin[blocksToConfirm] = bin } // Go through the mempool for txs that have been in too long. for hash, o := range ef.observed { if o.mined == mining.UnminedHeight && height-o.observed >= estimateFeeDepth { delete(ef.observed, hash) } } // Add dropped list to history. if ef.maxRollback == 0 { return nil } if uint32(len(ef.dropped)) == ef.maxRollback { ef.dropped = append(ef.dropped[1:], dropped) } else { ef.dropped = append(ef.dropped, dropped) } return nil }
go
func (ef *FeeEstimator) RegisterBlock(block *btcutil.Block) error { ef.mtx.Lock() defer ef.mtx.Unlock() // The previous sorted list is invalid, so delete it. ef.cached = nil height := block.Height() if height != ef.lastKnownHeight+1 && ef.lastKnownHeight != mining.UnminedHeight { return fmt.Errorf("intermediate block not recorded; current height is %d; new height is %d", ef.lastKnownHeight, height) } // Update the last known height. ef.lastKnownHeight = height ef.numBlocksRegistered++ // Randomly order txs in block. transactions := make(map[*btcutil.Tx]struct{}) for _, t := range block.Transactions() { transactions[t] = struct{}{} } // Count the number of replacements we make per bin so that we don't // replace too many. var replacementCounts [estimateFeeDepth]int // Keep track of which txs were dropped in case of an orphan block. dropped := &registeredBlock{ hash: *block.Hash(), transactions: make([]*observedTransaction, 0, 100), } // Go through the txs in the block. for t := range transactions { hash := *t.Hash() // Have we observed this tx in the mempool? o, ok := ef.observed[hash] if !ok { continue } // Put the observed tx in the oppropriate bin. blocksToConfirm := height - o.observed - 1 // This shouldn't happen if the fee estimator works correctly, // but return an error if it does. if o.mined != mining.UnminedHeight { log.Error("Estimate fee: transaction ", hash.String(), " has already been mined") return errors.New("Transaction has already been mined") } // This shouldn't happen but check just in case to avoid // an out-of-bounds array index later. if blocksToConfirm >= estimateFeeDepth { continue } // Make sure we do not replace too many transactions per min. if replacementCounts[blocksToConfirm] == int(ef.maxReplacements) { continue } o.mined = height replacementCounts[blocksToConfirm]++ bin := ef.bin[blocksToConfirm] // Remove a random element and replace it with this new tx. if len(bin) == int(ef.binSize) { // Don't drop transactions we have just added from this same block. l := int(ef.binSize) - replacementCounts[blocksToConfirm] drop := rand.Intn(l) dropped.transactions = append(dropped.transactions, bin[drop]) bin[drop] = bin[l-1] bin[l-1] = o } else { bin = append(bin, o) } ef.bin[blocksToConfirm] = bin } // Go through the mempool for txs that have been in too long. for hash, o := range ef.observed { if o.mined == mining.UnminedHeight && height-o.observed >= estimateFeeDepth { delete(ef.observed, hash) } } // Add dropped list to history. if ef.maxRollback == 0 { return nil } if uint32(len(ef.dropped)) == ef.maxRollback { ef.dropped = append(ef.dropped[1:], dropped) } else { ef.dropped = append(ef.dropped, dropped) } return nil }
[ "func", "(", "ef", "*", "FeeEstimator", ")", "RegisterBlock", "(", "block", "*", "btcutil", ".", "Block", ")", "error", "{", "ef", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "ef", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "// The previous sorted list is invalid, so delete it.", "ef", ".", "cached", "=", "nil", "\n\n", "height", ":=", "block", ".", "Height", "(", ")", "\n", "if", "height", "!=", "ef", ".", "lastKnownHeight", "+", "1", "&&", "ef", ".", "lastKnownHeight", "!=", "mining", ".", "UnminedHeight", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ef", ".", "lastKnownHeight", ",", "height", ")", "\n", "}", "\n\n", "// Update the last known height.", "ef", ".", "lastKnownHeight", "=", "height", "\n", "ef", ".", "numBlocksRegistered", "++", "\n\n", "// Randomly order txs in block.", "transactions", ":=", "make", "(", "map", "[", "*", "btcutil", ".", "Tx", "]", "struct", "{", "}", ")", "\n", "for", "_", ",", "t", ":=", "range", "block", ".", "Transactions", "(", ")", "{", "transactions", "[", "t", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n\n", "// Count the number of replacements we make per bin so that we don't", "// replace too many.", "var", "replacementCounts", "[", "estimateFeeDepth", "]", "int", "\n\n", "// Keep track of which txs were dropped in case of an orphan block.", "dropped", ":=", "&", "registeredBlock", "{", "hash", ":", "*", "block", ".", "Hash", "(", ")", ",", "transactions", ":", "make", "(", "[", "]", "*", "observedTransaction", ",", "0", ",", "100", ")", ",", "}", "\n\n", "// Go through the txs in the block.", "for", "t", ":=", "range", "transactions", "{", "hash", ":=", "*", "t", ".", "Hash", "(", ")", "\n\n", "// Have we observed this tx in the mempool?", "o", ",", "ok", ":=", "ef", ".", "observed", "[", "hash", "]", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n\n", "// Put the observed tx in the oppropriate bin.", "blocksToConfirm", ":=", "height", "-", "o", ".", "observed", "-", "1", "\n\n", "// This shouldn't happen if the fee estimator works correctly,", "// but return an error if it does.", "if", "o", ".", "mined", "!=", "mining", ".", "UnminedHeight", "{", "log", ".", "Error", "(", "\"", "\"", ",", "hash", ".", "String", "(", ")", ",", "\"", "\"", ")", "\n", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// This shouldn't happen but check just in case to avoid", "// an out-of-bounds array index later.", "if", "blocksToConfirm", ">=", "estimateFeeDepth", "{", "continue", "\n", "}", "\n\n", "// Make sure we do not replace too many transactions per min.", "if", "replacementCounts", "[", "blocksToConfirm", "]", "==", "int", "(", "ef", ".", "maxReplacements", ")", "{", "continue", "\n", "}", "\n\n", "o", ".", "mined", "=", "height", "\n\n", "replacementCounts", "[", "blocksToConfirm", "]", "++", "\n\n", "bin", ":=", "ef", ".", "bin", "[", "blocksToConfirm", "]", "\n\n", "// Remove a random element and replace it with this new tx.", "if", "len", "(", "bin", ")", "==", "int", "(", "ef", ".", "binSize", ")", "{", "// Don't drop transactions we have just added from this same block.", "l", ":=", "int", "(", "ef", ".", "binSize", ")", "-", "replacementCounts", "[", "blocksToConfirm", "]", "\n", "drop", ":=", "rand", ".", "Intn", "(", "l", ")", "\n", "dropped", ".", "transactions", "=", "append", "(", "dropped", ".", "transactions", ",", "bin", "[", "drop", "]", ")", "\n\n", "bin", "[", "drop", "]", "=", "bin", "[", "l", "-", "1", "]", "\n", "bin", "[", "l", "-", "1", "]", "=", "o", "\n", "}", "else", "{", "bin", "=", "append", "(", "bin", ",", "o", ")", "\n", "}", "\n", "ef", ".", "bin", "[", "blocksToConfirm", "]", "=", "bin", "\n", "}", "\n\n", "// Go through the mempool for txs that have been in too long.", "for", "hash", ",", "o", ":=", "range", "ef", ".", "observed", "{", "if", "o", ".", "mined", "==", "mining", ".", "UnminedHeight", "&&", "height", "-", "o", ".", "observed", ">=", "estimateFeeDepth", "{", "delete", "(", "ef", ".", "observed", ",", "hash", ")", "\n", "}", "\n", "}", "\n\n", "// Add dropped list to history.", "if", "ef", ".", "maxRollback", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "if", "uint32", "(", "len", "(", "ef", ".", "dropped", ")", ")", "==", "ef", ".", "maxRollback", "{", "ef", ".", "dropped", "=", "append", "(", "ef", ".", "dropped", "[", "1", ":", "]", ",", "dropped", ")", "\n", "}", "else", "{", "ef", ".", "dropped", "=", "append", "(", "ef", ".", "dropped", ",", "dropped", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// RegisterBlock informs the fee estimator of a new block to take into account.
[ "RegisterBlock", "informs", "the", "fee", "estimator", "of", "a", "new", "block", "to", "take", "into", "account", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/estimatefee.go#L223-L327
train
btcsuite/btcd
mempool/estimatefee.go
LastKnownHeight
func (ef *FeeEstimator) LastKnownHeight() int32 { ef.mtx.Lock() defer ef.mtx.Unlock() return ef.lastKnownHeight }
go
func (ef *FeeEstimator) LastKnownHeight() int32 { ef.mtx.Lock() defer ef.mtx.Unlock() return ef.lastKnownHeight }
[ "func", "(", "ef", "*", "FeeEstimator", ")", "LastKnownHeight", "(", ")", "int32", "{", "ef", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "ef", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "return", "ef", ".", "lastKnownHeight", "\n", "}" ]
// LastKnownHeight returns the height of the last block which was registered.
[ "LastKnownHeight", "returns", "the", "height", "of", "the", "last", "block", "which", "was", "registered", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/estimatefee.go#L330-L335
train
btcsuite/btcd
mempool/estimatefee.go
rollback
func (ef *FeeEstimator) rollback() { // The previous sorted list is invalid, so delete it. ef.cached = nil // pop the last list of dropped txs from the stack. last := len(ef.dropped) - 1 if last == -1 { // Cannot really happen because the exported calling function // only rolls back a block already known to be in the list // of dropped transactions. return } dropped := ef.dropped[last] // where we are in each bin as we replace txs? var replacementCounters [estimateFeeDepth]int // Go through the txs in the dropped block. for _, o := range dropped.transactions { // Which bin was this tx in? blocksToConfirm := o.mined - o.observed - 1 bin := ef.bin[blocksToConfirm] var counter = replacementCounters[blocksToConfirm] // Continue to go through that bin where we left off. for { if counter >= len(bin) { // Panic, as we have entered an unrecoverable invalid state. panic(errors.New("illegal state: cannot rollback dropped transaction")) } prev := bin[counter] if prev.mined == ef.lastKnownHeight { prev.mined = mining.UnminedHeight bin[counter] = o counter++ break } counter++ } replacementCounters[blocksToConfirm] = counter } // Continue going through bins to find other txs to remove // which did not replace any other when they were entered. for i, j := range replacementCounters { for { l := len(ef.bin[i]) if j >= l { break } prev := ef.bin[i][j] if prev.mined == ef.lastKnownHeight { prev.mined = mining.UnminedHeight newBin := append(ef.bin[i][0:j], ef.bin[i][j+1:l]...) // TODO This line should prevent an unintentional memory // leak but it causes a panic when it is uncommented. // ef.bin[i][j] = nil ef.bin[i] = newBin continue } j++ } } ef.dropped = ef.dropped[0:last] // The number of blocks the fee estimator has seen is decrimented. ef.numBlocksRegistered-- ef.lastKnownHeight-- }
go
func (ef *FeeEstimator) rollback() { // The previous sorted list is invalid, so delete it. ef.cached = nil // pop the last list of dropped txs from the stack. last := len(ef.dropped) - 1 if last == -1 { // Cannot really happen because the exported calling function // only rolls back a block already known to be in the list // of dropped transactions. return } dropped := ef.dropped[last] // where we are in each bin as we replace txs? var replacementCounters [estimateFeeDepth]int // Go through the txs in the dropped block. for _, o := range dropped.transactions { // Which bin was this tx in? blocksToConfirm := o.mined - o.observed - 1 bin := ef.bin[blocksToConfirm] var counter = replacementCounters[blocksToConfirm] // Continue to go through that bin where we left off. for { if counter >= len(bin) { // Panic, as we have entered an unrecoverable invalid state. panic(errors.New("illegal state: cannot rollback dropped transaction")) } prev := bin[counter] if prev.mined == ef.lastKnownHeight { prev.mined = mining.UnminedHeight bin[counter] = o counter++ break } counter++ } replacementCounters[blocksToConfirm] = counter } // Continue going through bins to find other txs to remove // which did not replace any other when they were entered. for i, j := range replacementCounters { for { l := len(ef.bin[i]) if j >= l { break } prev := ef.bin[i][j] if prev.mined == ef.lastKnownHeight { prev.mined = mining.UnminedHeight newBin := append(ef.bin[i][0:j], ef.bin[i][j+1:l]...) // TODO This line should prevent an unintentional memory // leak but it causes a panic when it is uncommented. // ef.bin[i][j] = nil ef.bin[i] = newBin continue } j++ } } ef.dropped = ef.dropped[0:last] // The number of blocks the fee estimator has seen is decrimented. ef.numBlocksRegistered-- ef.lastKnownHeight-- }
[ "func", "(", "ef", "*", "FeeEstimator", ")", "rollback", "(", ")", "{", "// The previous sorted list is invalid, so delete it.", "ef", ".", "cached", "=", "nil", "\n\n", "// pop the last list of dropped txs from the stack.", "last", ":=", "len", "(", "ef", ".", "dropped", ")", "-", "1", "\n", "if", "last", "==", "-", "1", "{", "// Cannot really happen because the exported calling function", "// only rolls back a block already known to be in the list", "// of dropped transactions.", "return", "\n", "}", "\n\n", "dropped", ":=", "ef", ".", "dropped", "[", "last", "]", "\n\n", "// where we are in each bin as we replace txs?", "var", "replacementCounters", "[", "estimateFeeDepth", "]", "int", "\n\n", "// Go through the txs in the dropped block.", "for", "_", ",", "o", ":=", "range", "dropped", ".", "transactions", "{", "// Which bin was this tx in?", "blocksToConfirm", ":=", "o", ".", "mined", "-", "o", ".", "observed", "-", "1", "\n\n", "bin", ":=", "ef", ".", "bin", "[", "blocksToConfirm", "]", "\n\n", "var", "counter", "=", "replacementCounters", "[", "blocksToConfirm", "]", "\n\n", "// Continue to go through that bin where we left off.", "for", "{", "if", "counter", ">=", "len", "(", "bin", ")", "{", "// Panic, as we have entered an unrecoverable invalid state.", "panic", "(", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n\n", "prev", ":=", "bin", "[", "counter", "]", "\n\n", "if", "prev", ".", "mined", "==", "ef", ".", "lastKnownHeight", "{", "prev", ".", "mined", "=", "mining", ".", "UnminedHeight", "\n\n", "bin", "[", "counter", "]", "=", "o", "\n\n", "counter", "++", "\n", "break", "\n", "}", "\n\n", "counter", "++", "\n", "}", "\n\n", "replacementCounters", "[", "blocksToConfirm", "]", "=", "counter", "\n", "}", "\n\n", "// Continue going through bins to find other txs to remove", "// which did not replace any other when they were entered.", "for", "i", ",", "j", ":=", "range", "replacementCounters", "{", "for", "{", "l", ":=", "len", "(", "ef", ".", "bin", "[", "i", "]", ")", "\n", "if", "j", ">=", "l", "{", "break", "\n", "}", "\n\n", "prev", ":=", "ef", ".", "bin", "[", "i", "]", "[", "j", "]", "\n\n", "if", "prev", ".", "mined", "==", "ef", ".", "lastKnownHeight", "{", "prev", ".", "mined", "=", "mining", ".", "UnminedHeight", "\n\n", "newBin", ":=", "append", "(", "ef", ".", "bin", "[", "i", "]", "[", "0", ":", "j", "]", ",", "ef", ".", "bin", "[", "i", "]", "[", "j", "+", "1", ":", "l", "]", "...", ")", "\n", "// TODO This line should prevent an unintentional memory", "// leak but it causes a panic when it is uncommented.", "// ef.bin[i][j] = nil", "ef", ".", "bin", "[", "i", "]", "=", "newBin", "\n\n", "continue", "\n", "}", "\n\n", "j", "++", "\n", "}", "\n", "}", "\n\n", "ef", ".", "dropped", "=", "ef", ".", "dropped", "[", "0", ":", "last", "]", "\n\n", "// The number of blocks the fee estimator has seen is decrimented.", "ef", ".", "numBlocksRegistered", "--", "\n", "ef", ".", "lastKnownHeight", "--", "\n", "}" ]
// rollback rolls back the effect of the last block in the stack // of registered blocks.
[ "rollback", "rolls", "back", "the", "effect", "of", "the", "last", "block", "in", "the", "stack", "of", "registered", "blocks", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/estimatefee.go#L371-L454
train
btcsuite/btcd
mempool/estimatefee.go
estimateFee
func (b *estimateFeeSet) estimateFee(confirmations int) SatoshiPerByte { if confirmations <= 0 { return SatoshiPerByte(math.Inf(1)) } if confirmations > estimateFeeDepth { return 0 } // We don't have any transactions! if len(b.feeRate) == 0 { return 0 } var min, max int = 0, 0 for i := 0; i < confirmations-1; i++ { min += int(b.bin[i]) } max = min + int(b.bin[confirmations-1]) - 1 if max < min { max = min } feeIndex := (min + max) / 2 if feeIndex >= len(b.feeRate) { feeIndex = len(b.feeRate) - 1 } return b.feeRate[feeIndex] }
go
func (b *estimateFeeSet) estimateFee(confirmations int) SatoshiPerByte { if confirmations <= 0 { return SatoshiPerByte(math.Inf(1)) } if confirmations > estimateFeeDepth { return 0 } // We don't have any transactions! if len(b.feeRate) == 0 { return 0 } var min, max int = 0, 0 for i := 0; i < confirmations-1; i++ { min += int(b.bin[i]) } max = min + int(b.bin[confirmations-1]) - 1 if max < min { max = min } feeIndex := (min + max) / 2 if feeIndex >= len(b.feeRate) { feeIndex = len(b.feeRate) - 1 } return b.feeRate[feeIndex] }
[ "func", "(", "b", "*", "estimateFeeSet", ")", "estimateFee", "(", "confirmations", "int", ")", "SatoshiPerByte", "{", "if", "confirmations", "<=", "0", "{", "return", "SatoshiPerByte", "(", "math", ".", "Inf", "(", "1", ")", ")", "\n", "}", "\n\n", "if", "confirmations", ">", "estimateFeeDepth", "{", "return", "0", "\n", "}", "\n\n", "// We don't have any transactions!", "if", "len", "(", "b", ".", "feeRate", ")", "==", "0", "{", "return", "0", "\n", "}", "\n\n", "var", "min", ",", "max", "int", "=", "0", ",", "0", "\n", "for", "i", ":=", "0", ";", "i", "<", "confirmations", "-", "1", ";", "i", "++", "{", "min", "+=", "int", "(", "b", ".", "bin", "[", "i", "]", ")", "\n", "}", "\n\n", "max", "=", "min", "+", "int", "(", "b", ".", "bin", "[", "confirmations", "-", "1", "]", ")", "-", "1", "\n", "if", "max", "<", "min", "{", "max", "=", "min", "\n", "}", "\n", "feeIndex", ":=", "(", "min", "+", "max", ")", "/", "2", "\n", "if", "feeIndex", ">=", "len", "(", "b", ".", "feeRate", ")", "{", "feeIndex", "=", "len", "(", "b", ".", "feeRate", ")", "-", "1", "\n", "}", "\n\n", "return", "b", ".", "feeRate", "[", "feeIndex", "]", "\n", "}" ]
// estimateFee returns the estimated fee for a transaction // to confirm in confirmations blocks from now, given // the data set we have collected.
[ "estimateFee", "returns", "the", "estimated", "fee", "for", "a", "transaction", "to", "confirm", "in", "confirmations", "blocks", "from", "now", "given", "the", "data", "set", "we", "have", "collected", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mempool/estimatefee.go#L476-L505
train