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
btcec/signature.go
ParseDERSignature
func ParseDERSignature(sigStr []byte, curve elliptic.Curve) (*Signature, error) { return parseSig(sigStr, curve, true) }
go
func ParseDERSignature(sigStr []byte, curve elliptic.Curve) (*Signature, error) { return parseSig(sigStr, curve, true) }
[ "func", "ParseDERSignature", "(", "sigStr", "[", "]", "byte", ",", "curve", "elliptic", ".", "Curve", ")", "(", "*", "Signature", ",", "error", ")", "{", "return", "parseSig", "(", "sigStr", ",", "curve", ",", "true", ")", "\n", "}" ]
// ParseDERSignature parses a signature in DER format for the curve type // `curve` into a Signature type. If parsing according to the less strict // BER format is needed, use ParseSignature.
[ "ParseDERSignature", "parses", "a", "signature", "in", "DER", "format", "for", "the", "curve", "type", "curve", "into", "a", "Signature", "type", ".", "If", "parsing", "according", "to", "the", "less", "strict", "BER", "format", "is", "needed", "use", "ParseSignature", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/signature.go#L218-L220
train
btcsuite/btcd
btcec/signature.go
canonicalizeInt
func canonicalizeInt(val *big.Int) []byte { b := val.Bytes() if len(b) == 0 { b = []byte{0x00} } if b[0]&0x80 != 0 { paddedBytes := make([]byte, len(b)+1) copy(paddedBytes[1:], b) b = paddedBytes } return b }
go
func canonicalizeInt(val *big.Int) []byte { b := val.Bytes() if len(b) == 0 { b = []byte{0x00} } if b[0]&0x80 != 0 { paddedBytes := make([]byte, len(b)+1) copy(paddedBytes[1:], b) b = paddedBytes } return b }
[ "func", "canonicalizeInt", "(", "val", "*", "big", ".", "Int", ")", "[", "]", "byte", "{", "b", ":=", "val", ".", "Bytes", "(", ")", "\n", "if", "len", "(", "b", ")", "==", "0", "{", "b", "=", "[", "]", "byte", "{", "0x00", "}", "\n", "}", "\n", "if", "b", "[", "0", "]", "&", "0x80", "!=", "0", "{", "paddedBytes", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "b", ")", "+", "1", ")", "\n", "copy", "(", "paddedBytes", "[", "1", ":", "]", ",", "b", ")", "\n", "b", "=", "paddedBytes", "\n", "}", "\n", "return", "b", "\n", "}" ]
// canonicalizeInt returns the bytes for the passed big integer adjusted as // necessary to ensure that a big-endian encoded integer can't possibly be // misinterpreted as a negative number. This can happen when the most // significant bit is set, so it is padded by a leading zero byte in this case. // Also, the returned bytes will have at least a single byte when the passed // value is 0. This is required for DER encoding.
[ "canonicalizeInt", "returns", "the", "bytes", "for", "the", "passed", "big", "integer", "adjusted", "as", "necessary", "to", "ensure", "that", "a", "big", "-", "endian", "encoded", "integer", "can", "t", "possibly", "be", "misinterpreted", "as", "a", "negative", "number", ".", "This", "can", "happen", "when", "the", "most", "significant", "bit", "is", "set", "so", "it", "is", "padded", "by", "a", "leading", "zero", "byte", "in", "this", "case", ".", "Also", "the", "returned", "bytes", "will", "have", "at", "least", "a", "single", "byte", "when", "the", "passed", "value", "is", "0", ".", "This", "is", "required", "for", "DER", "encoding", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/signature.go#L228-L239
train
btcsuite/btcd
btcec/signature.go
RecoverCompact
func RecoverCompact(curve *KoblitzCurve, signature, hash []byte) (*PublicKey, bool, error) { bitlen := (curve.BitSize + 7) / 8 if len(signature) != 1+bitlen*2 { return nil, false, errors.New("invalid compact signature size") } iteration := int((signature[0] - 27) & ^byte(4)) // format is <header byte><bitlen R><bitlen S> sig := &Signature{ R: new(big.Int).SetBytes(signature[1 : bitlen+1]), S: new(big.Int).SetBytes(signature[bitlen+1:]), } // The iteration used here was encoded key, err := recoverKeyFromSignature(curve, sig, hash, iteration, false) if err != nil { return nil, false, err } return key, ((signature[0] - 27) & 4) == 4, nil }
go
func RecoverCompact(curve *KoblitzCurve, signature, hash []byte) (*PublicKey, bool, error) { bitlen := (curve.BitSize + 7) / 8 if len(signature) != 1+bitlen*2 { return nil, false, errors.New("invalid compact signature size") } iteration := int((signature[0] - 27) & ^byte(4)) // format is <header byte><bitlen R><bitlen S> sig := &Signature{ R: new(big.Int).SetBytes(signature[1 : bitlen+1]), S: new(big.Int).SetBytes(signature[bitlen+1:]), } // The iteration used here was encoded key, err := recoverKeyFromSignature(curve, sig, hash, iteration, false) if err != nil { return nil, false, err } return key, ((signature[0] - 27) & 4) == 4, nil }
[ "func", "RecoverCompact", "(", "curve", "*", "KoblitzCurve", ",", "signature", ",", "hash", "[", "]", "byte", ")", "(", "*", "PublicKey", ",", "bool", ",", "error", ")", "{", "bitlen", ":=", "(", "curve", ".", "BitSize", "+", "7", ")", "/", "8", "\n", "if", "len", "(", "signature", ")", "!=", "1", "+", "bitlen", "*", "2", "{", "return", "nil", ",", "false", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "iteration", ":=", "int", "(", "(", "signature", "[", "0", "]", "-", "27", ")", "&", "^", "byte", "(", "4", ")", ")", "\n\n", "// format is <header byte><bitlen R><bitlen S>", "sig", ":=", "&", "Signature", "{", "R", ":", "new", "(", "big", ".", "Int", ")", ".", "SetBytes", "(", "signature", "[", "1", ":", "bitlen", "+", "1", "]", ")", ",", "S", ":", "new", "(", "big", ".", "Int", ")", ".", "SetBytes", "(", "signature", "[", "bitlen", "+", "1", ":", "]", ")", ",", "}", "\n", "// The iteration used here was encoded", "key", ",", "err", ":=", "recoverKeyFromSignature", "(", "curve", ",", "sig", ",", "hash", ",", "iteration", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "false", ",", "err", "\n", "}", "\n\n", "return", "key", ",", "(", "(", "signature", "[", "0", "]", "-", "27", ")", "&", "4", ")", "==", "4", ",", "nil", "\n", "}" ]
// RecoverCompact verifies the compact signature "signature" of "hash" for the // Koblitz curve in "curve". If the signature matches then the recovered public // key will be returned as well as a boolen if the original key was compressed // or not, else an error will be returned.
[ "RecoverCompact", "verifies", "the", "compact", "signature", "signature", "of", "hash", "for", "the", "Koblitz", "curve", "in", "curve", ".", "If", "the", "signature", "matches", "then", "the", "recovered", "public", "key", "will", "be", "returned", "as", "well", "as", "a", "boolen", "if", "the", "original", "key", "was", "compressed", "or", "not", "else", "an", "error", "will", "be", "returned", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/signature.go#L398-L419
train
btcsuite/btcd
btcec/signature.go
signRFC6979
func signRFC6979(privateKey *PrivateKey, hash []byte) (*Signature, error) { privkey := privateKey.ToECDSA() N := S256().N halfOrder := S256().halfOrder k := nonceRFC6979(privkey.D, hash) inv := new(big.Int).ModInverse(k, N) r, _ := privkey.Curve.ScalarBaseMult(k.Bytes()) r.Mod(r, N) if r.Sign() == 0 { return nil, errors.New("calculated R is zero") } e := hashToInt(hash, privkey.Curve) s := new(big.Int).Mul(privkey.D, r) s.Add(s, e) s.Mul(s, inv) s.Mod(s, N) if s.Cmp(halfOrder) == 1 { s.Sub(N, s) } if s.Sign() == 0 { return nil, errors.New("calculated S is zero") } return &Signature{R: r, S: s}, nil }
go
func signRFC6979(privateKey *PrivateKey, hash []byte) (*Signature, error) { privkey := privateKey.ToECDSA() N := S256().N halfOrder := S256().halfOrder k := nonceRFC6979(privkey.D, hash) inv := new(big.Int).ModInverse(k, N) r, _ := privkey.Curve.ScalarBaseMult(k.Bytes()) r.Mod(r, N) if r.Sign() == 0 { return nil, errors.New("calculated R is zero") } e := hashToInt(hash, privkey.Curve) s := new(big.Int).Mul(privkey.D, r) s.Add(s, e) s.Mul(s, inv) s.Mod(s, N) if s.Cmp(halfOrder) == 1 { s.Sub(N, s) } if s.Sign() == 0 { return nil, errors.New("calculated S is zero") } return &Signature{R: r, S: s}, nil }
[ "func", "signRFC6979", "(", "privateKey", "*", "PrivateKey", ",", "hash", "[", "]", "byte", ")", "(", "*", "Signature", ",", "error", ")", "{", "privkey", ":=", "privateKey", ".", "ToECDSA", "(", ")", "\n", "N", ":=", "S256", "(", ")", ".", "N", "\n", "halfOrder", ":=", "S256", "(", ")", ".", "halfOrder", "\n", "k", ":=", "nonceRFC6979", "(", "privkey", ".", "D", ",", "hash", ")", "\n", "inv", ":=", "new", "(", "big", ".", "Int", ")", ".", "ModInverse", "(", "k", ",", "N", ")", "\n", "r", ",", "_", ":=", "privkey", ".", "Curve", ".", "ScalarBaseMult", "(", "k", ".", "Bytes", "(", ")", ")", "\n", "r", ".", "Mod", "(", "r", ",", "N", ")", "\n\n", "if", "r", ".", "Sign", "(", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "e", ":=", "hashToInt", "(", "hash", ",", "privkey", ".", "Curve", ")", "\n", "s", ":=", "new", "(", "big", ".", "Int", ")", ".", "Mul", "(", "privkey", ".", "D", ",", "r", ")", "\n", "s", ".", "Add", "(", "s", ",", "e", ")", "\n", "s", ".", "Mul", "(", "s", ",", "inv", ")", "\n", "s", ".", "Mod", "(", "s", ",", "N", ")", "\n\n", "if", "s", ".", "Cmp", "(", "halfOrder", ")", "==", "1", "{", "s", ".", "Sub", "(", "N", ",", "s", ")", "\n", "}", "\n", "if", "s", ".", "Sign", "(", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "&", "Signature", "{", "R", ":", "r", ",", "S", ":", "s", "}", ",", "nil", "\n", "}" ]
// signRFC6979 generates a deterministic ECDSA signature according to RFC 6979 and BIP 62.
[ "signRFC6979", "generates", "a", "deterministic", "ECDSA", "signature", "according", "to", "RFC", "6979", "and", "BIP", "62", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/signature.go#L422-L449
train
btcsuite/btcd
btcec/signature.go
mac
func mac(alg func() hash.Hash, k, m []byte) []byte { h := hmac.New(alg, k) h.Write(m) return h.Sum(nil) }
go
func mac(alg func() hash.Hash, k, m []byte) []byte { h := hmac.New(alg, k) h.Write(m) return h.Sum(nil) }
[ "func", "mac", "(", "alg", "func", "(", ")", "hash", ".", "Hash", ",", "k", ",", "m", "[", "]", "byte", ")", "[", "]", "byte", "{", "h", ":=", "hmac", ".", "New", "(", "alg", ",", "k", ")", "\n", "h", ".", "Write", "(", "m", ")", "\n", "return", "h", ".", "Sum", "(", "nil", ")", "\n", "}" ]
// mac returns an HMAC of the given key and message.
[ "mac", "returns", "an", "HMAC", "of", "the", "given", "key", "and", "message", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcec/signature.go#L505-L509
train
btcsuite/btcd
mining/mining.go
Less
func (pq *txPriorityQueue) Less(i, j int) bool { return pq.lessFunc(pq, i, j) }
go
func (pq *txPriorityQueue) Less(i, j int) bool { return pq.lessFunc(pq, i, j) }
[ "func", "(", "pq", "*", "txPriorityQueue", ")", "Less", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "pq", ".", "lessFunc", "(", "pq", ",", "i", ",", "j", ")", "\n", "}" ]
// Less returns whether the item in the priority queue with index i should sort // before the item with index j by deferring to the assigned less function. It // is part of the heap.Interface implementation.
[ "Less", "returns", "whether", "the", "item", "in", "the", "priority", "queue", "with", "index", "i", "should", "sort", "before", "the", "item", "with", "index", "j", "by", "deferring", "to", "the", "assigned", "less", "function", ".", "It", "is", "part", "of", "the", "heap", ".", "Interface", "implementation", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/mining.go#L111-L113
train
btcsuite/btcd
mining/mining.go
Swap
func (pq *txPriorityQueue) Swap(i, j int) { pq.items[i], pq.items[j] = pq.items[j], pq.items[i] }
go
func (pq *txPriorityQueue) Swap(i, j int) { pq.items[i], pq.items[j] = pq.items[j], pq.items[i] }
[ "func", "(", "pq", "*", "txPriorityQueue", ")", "Swap", "(", "i", ",", "j", "int", ")", "{", "pq", ".", "items", "[", "i", "]", ",", "pq", ".", "items", "[", "j", "]", "=", "pq", ".", "items", "[", "j", "]", ",", "pq", ".", "items", "[", "i", "]", "\n", "}" ]
// Swap swaps the items at the passed indices in the priority queue. It is // part of the heap.Interface implementation.
[ "Swap", "swaps", "the", "items", "at", "the", "passed", "indices", "in", "the", "priority", "queue", ".", "It", "is", "part", "of", "the", "heap", ".", "Interface", "implementation", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/mining.go#L117-L119
train
btcsuite/btcd
mining/mining.go
Push
func (pq *txPriorityQueue) Push(x interface{}) { pq.items = append(pq.items, x.(*txPrioItem)) }
go
func (pq *txPriorityQueue) Push(x interface{}) { pq.items = append(pq.items, x.(*txPrioItem)) }
[ "func", "(", "pq", "*", "txPriorityQueue", ")", "Push", "(", "x", "interface", "{", "}", ")", "{", "pq", ".", "items", "=", "append", "(", "pq", ".", "items", ",", "x", ".", "(", "*", "txPrioItem", ")", ")", "\n", "}" ]
// Push pushes the passed item onto the priority queue. It is part of the // heap.Interface implementation.
[ "Push", "pushes", "the", "passed", "item", "onto", "the", "priority", "queue", ".", "It", "is", "part", "of", "the", "heap", ".", "Interface", "implementation", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/mining.go#L123-L125
train
btcsuite/btcd
mining/mining.go
txPQByPriority
func txPQByPriority(pq *txPriorityQueue, i, j int) bool { // Using > here so that pop gives the highest priority item as opposed // to the lowest. Sort by priority first, then fee. if pq.items[i].priority == pq.items[j].priority { return pq.items[i].feePerKB > pq.items[j].feePerKB } return pq.items[i].priority > pq.items[j].priority }
go
func txPQByPriority(pq *txPriorityQueue, i, j int) bool { // Using > here so that pop gives the highest priority item as opposed // to the lowest. Sort by priority first, then fee. if pq.items[i].priority == pq.items[j].priority { return pq.items[i].feePerKB > pq.items[j].feePerKB } return pq.items[i].priority > pq.items[j].priority }
[ "func", "txPQByPriority", "(", "pq", "*", "txPriorityQueue", ",", "i", ",", "j", "int", ")", "bool", "{", "// Using > here so that pop gives the highest priority item as opposed", "// to the lowest. Sort by priority first, then fee.", "if", "pq", ".", "items", "[", "i", "]", ".", "priority", "==", "pq", ".", "items", "[", "j", "]", ".", "priority", "{", "return", "pq", ".", "items", "[", "i", "]", ".", "feePerKB", ">", "pq", ".", "items", "[", "j", "]", ".", "feePerKB", "\n", "}", "\n", "return", "pq", ".", "items", "[", "i", "]", ".", "priority", ">", "pq", ".", "items", "[", "j", "]", ".", "priority", "\n\n", "}" ]
// txPQByPriority sorts a txPriorityQueue by transaction priority and then fees // per kilobyte.
[ "txPQByPriority", "sorts", "a", "txPriorityQueue", "by", "transaction", "priority", "and", "then", "fees", "per", "kilobyte", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/mining.go#L147-L155
train
btcsuite/btcd
mining/mining.go
mergeUtxoView
func mergeUtxoView(viewA *blockchain.UtxoViewpoint, viewB *blockchain.UtxoViewpoint) { viewAEntries := viewA.Entries() for outpoint, entryB := range viewB.Entries() { if entryA, exists := viewAEntries[outpoint]; !exists || entryA == nil || entryA.IsSpent() { viewAEntries[outpoint] = entryB } } }
go
func mergeUtxoView(viewA *blockchain.UtxoViewpoint, viewB *blockchain.UtxoViewpoint) { viewAEntries := viewA.Entries() for outpoint, entryB := range viewB.Entries() { if entryA, exists := viewAEntries[outpoint]; !exists || entryA == nil || entryA.IsSpent() { viewAEntries[outpoint] = entryB } } }
[ "func", "mergeUtxoView", "(", "viewA", "*", "blockchain", ".", "UtxoViewpoint", ",", "viewB", "*", "blockchain", ".", "UtxoViewpoint", ")", "{", "viewAEntries", ":=", "viewA", ".", "Entries", "(", ")", "\n", "for", "outpoint", ",", "entryB", ":=", "range", "viewB", ".", "Entries", "(", ")", "{", "if", "entryA", ",", "exists", ":=", "viewAEntries", "[", "outpoint", "]", ";", "!", "exists", "||", "entryA", "==", "nil", "||", "entryA", ".", "IsSpent", "(", ")", "{", "viewAEntries", "[", "outpoint", "]", "=", "entryB", "\n", "}", "\n", "}", "\n", "}" ]
// mergeUtxoView adds all of the entries in viewB to viewA. The result is that // viewA will contain all of its original entries plus all of the entries // in viewB. It will replace any entries in viewB which also exist in viewA // if the entry in viewA is spent.
[ "mergeUtxoView", "adds", "all", "of", "the", "entries", "in", "viewB", "to", "viewA", ".", "The", "result", "is", "that", "viewA", "will", "contain", "all", "of", "its", "original", "entries", "plus", "all", "of", "the", "entries", "in", "viewB", ".", "It", "will", "replace", "any", "entries", "in", "viewB", "which", "also", "exist", "in", "viewA", "if", "the", "entry", "in", "viewA", "is", "spent", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/mining.go#L226-L235
train
btcsuite/btcd
mining/mining.go
standardCoinbaseScript
func standardCoinbaseScript(nextBlockHeight int32, extraNonce uint64) ([]byte, error) { return txscript.NewScriptBuilder().AddInt64(int64(nextBlockHeight)). AddInt64(int64(extraNonce)).AddData([]byte(CoinbaseFlags)). Script() }
go
func standardCoinbaseScript(nextBlockHeight int32, extraNonce uint64) ([]byte, error) { return txscript.NewScriptBuilder().AddInt64(int64(nextBlockHeight)). AddInt64(int64(extraNonce)).AddData([]byte(CoinbaseFlags)). Script() }
[ "func", "standardCoinbaseScript", "(", "nextBlockHeight", "int32", ",", "extraNonce", "uint64", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "txscript", ".", "NewScriptBuilder", "(", ")", ".", "AddInt64", "(", "int64", "(", "nextBlockHeight", ")", ")", ".", "AddInt64", "(", "int64", "(", "extraNonce", ")", ")", ".", "AddData", "(", "[", "]", "byte", "(", "CoinbaseFlags", ")", ")", ".", "Script", "(", ")", "\n", "}" ]
// standardCoinbaseScript returns a standard script suitable for use as the // signature script of the coinbase transaction of a new block. In particular, // it starts with the block height that is required by version 2 blocks and adds // the extra nonce as well as additional coinbase flags.
[ "standardCoinbaseScript", "returns", "a", "standard", "script", "suitable", "for", "use", "as", "the", "signature", "script", "of", "the", "coinbase", "transaction", "of", "a", "new", "block", ".", "In", "particular", "it", "starts", "with", "the", "block", "height", "that", "is", "required", "by", "version", "2", "blocks", "and", "adds", "the", "extra", "nonce", "as", "well", "as", "additional", "coinbase", "flags", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/mining.go#L241-L245
train
btcsuite/btcd
mining/mining.go
createCoinbaseTx
func createCoinbaseTx(params *chaincfg.Params, coinbaseScript []byte, nextBlockHeight int32, addr btcutil.Address) (*btcutil.Tx, error) { // Create the script to pay to the provided payment address if one was // specified. Otherwise create a script that allows the coinbase to be // redeemable by anyone. var pkScript []byte if addr != nil { var err error pkScript, err = txscript.PayToAddrScript(addr) if err != nil { return nil, err } } else { var err error scriptBuilder := txscript.NewScriptBuilder() pkScript, err = scriptBuilder.AddOp(txscript.OP_TRUE).Script() if err != nil { return nil, err } } tx := wire.NewMsgTx(wire.TxVersion) tx.AddTxIn(&wire.TxIn{ // Coinbase transactions have no inputs, so previous outpoint is // zero hash and max index. PreviousOutPoint: *wire.NewOutPoint(&chainhash.Hash{}, wire.MaxPrevOutIndex), SignatureScript: coinbaseScript, Sequence: wire.MaxTxInSequenceNum, }) tx.AddTxOut(&wire.TxOut{ Value: blockchain.CalcBlockSubsidy(nextBlockHeight, params), PkScript: pkScript, }) return btcutil.NewTx(tx), nil }
go
func createCoinbaseTx(params *chaincfg.Params, coinbaseScript []byte, nextBlockHeight int32, addr btcutil.Address) (*btcutil.Tx, error) { // Create the script to pay to the provided payment address if one was // specified. Otherwise create a script that allows the coinbase to be // redeemable by anyone. var pkScript []byte if addr != nil { var err error pkScript, err = txscript.PayToAddrScript(addr) if err != nil { return nil, err } } else { var err error scriptBuilder := txscript.NewScriptBuilder() pkScript, err = scriptBuilder.AddOp(txscript.OP_TRUE).Script() if err != nil { return nil, err } } tx := wire.NewMsgTx(wire.TxVersion) tx.AddTxIn(&wire.TxIn{ // Coinbase transactions have no inputs, so previous outpoint is // zero hash and max index. PreviousOutPoint: *wire.NewOutPoint(&chainhash.Hash{}, wire.MaxPrevOutIndex), SignatureScript: coinbaseScript, Sequence: wire.MaxTxInSequenceNum, }) tx.AddTxOut(&wire.TxOut{ Value: blockchain.CalcBlockSubsidy(nextBlockHeight, params), PkScript: pkScript, }) return btcutil.NewTx(tx), nil }
[ "func", "createCoinbaseTx", "(", "params", "*", "chaincfg", ".", "Params", ",", "coinbaseScript", "[", "]", "byte", ",", "nextBlockHeight", "int32", ",", "addr", "btcutil", ".", "Address", ")", "(", "*", "btcutil", ".", "Tx", ",", "error", ")", "{", "// Create the script to pay to the provided payment address if one was", "// specified. Otherwise create a script that allows the coinbase to be", "// redeemable by anyone.", "var", "pkScript", "[", "]", "byte", "\n", "if", "addr", "!=", "nil", "{", "var", "err", "error", "\n", "pkScript", ",", "err", "=", "txscript", ".", "PayToAddrScript", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "else", "{", "var", "err", "error", "\n", "scriptBuilder", ":=", "txscript", ".", "NewScriptBuilder", "(", ")", "\n", "pkScript", ",", "err", "=", "scriptBuilder", ".", "AddOp", "(", "txscript", ".", "OP_TRUE", ")", ".", "Script", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "tx", ":=", "wire", ".", "NewMsgTx", "(", "wire", ".", "TxVersion", ")", "\n", "tx", ".", "AddTxIn", "(", "&", "wire", ".", "TxIn", "{", "// Coinbase transactions have no inputs, so previous outpoint is", "// zero hash and max index.", "PreviousOutPoint", ":", "*", "wire", ".", "NewOutPoint", "(", "&", "chainhash", ".", "Hash", "{", "}", ",", "wire", ".", "MaxPrevOutIndex", ")", ",", "SignatureScript", ":", "coinbaseScript", ",", "Sequence", ":", "wire", ".", "MaxTxInSequenceNum", ",", "}", ")", "\n", "tx", ".", "AddTxOut", "(", "&", "wire", ".", "TxOut", "{", "Value", ":", "blockchain", ".", "CalcBlockSubsidy", "(", "nextBlockHeight", ",", "params", ")", ",", "PkScript", ":", "pkScript", ",", "}", ")", "\n", "return", "btcutil", ".", "NewTx", "(", "tx", ")", ",", "nil", "\n", "}" ]
// createCoinbaseTx returns a coinbase transaction paying an appropriate subsidy // based on the passed block height to the provided address. When the address // is nil, the coinbase transaction will instead be redeemable by anyone. // // See the comment for NewBlockTemplate for more information about why the nil // address handling is useful.
[ "createCoinbaseTx", "returns", "a", "coinbase", "transaction", "paying", "an", "appropriate", "subsidy", "based", "on", "the", "passed", "block", "height", "to", "the", "provided", "address", ".", "When", "the", "address", "is", "nil", "the", "coinbase", "transaction", "will", "instead", "be", "redeemable", "by", "anyone", ".", "See", "the", "comment", "for", "NewBlockTemplate", "for", "more", "information", "about", "why", "the", "nil", "address", "handling", "is", "useful", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/mining.go#L253-L287
train
btcsuite/btcd
mining/mining.go
spendTransaction
func spendTransaction(utxoView *blockchain.UtxoViewpoint, tx *btcutil.Tx, height int32) error { for _, txIn := range tx.MsgTx().TxIn { entry := utxoView.LookupEntry(txIn.PreviousOutPoint) if entry != nil { entry.Spend() } } utxoView.AddTxOuts(tx, height) return nil }
go
func spendTransaction(utxoView *blockchain.UtxoViewpoint, tx *btcutil.Tx, height int32) error { for _, txIn := range tx.MsgTx().TxIn { entry := utxoView.LookupEntry(txIn.PreviousOutPoint) if entry != nil { entry.Spend() } } utxoView.AddTxOuts(tx, height) return nil }
[ "func", "spendTransaction", "(", "utxoView", "*", "blockchain", ".", "UtxoViewpoint", ",", "tx", "*", "btcutil", ".", "Tx", ",", "height", "int32", ")", "error", "{", "for", "_", ",", "txIn", ":=", "range", "tx", ".", "MsgTx", "(", ")", ".", "TxIn", "{", "entry", ":=", "utxoView", ".", "LookupEntry", "(", "txIn", ".", "PreviousOutPoint", ")", "\n", "if", "entry", "!=", "nil", "{", "entry", ".", "Spend", "(", ")", "\n", "}", "\n", "}", "\n\n", "utxoView", ".", "AddTxOuts", "(", "tx", ",", "height", ")", "\n", "return", "nil", "\n", "}" ]
// spendTransaction updates the passed view by marking the inputs to the passed // transaction as spent. It also adds all outputs in the passed transaction // which are not provably unspendable as available unspent transaction outputs.
[ "spendTransaction", "updates", "the", "passed", "view", "by", "marking", "the", "inputs", "to", "the", "passed", "transaction", "as", "spent", ".", "It", "also", "adds", "all", "outputs", "in", "the", "passed", "transaction", "which", "are", "not", "provably", "unspendable", "as", "available", "unspent", "transaction", "outputs", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/mining.go#L292-L302
train
btcsuite/btcd
mining/mining.go
logSkippedDeps
func logSkippedDeps(tx *btcutil.Tx, deps map[chainhash.Hash]*txPrioItem) { if deps == nil { return } for _, item := range deps { log.Tracef("Skipping tx %s since it depends on %s\n", item.tx.Hash(), tx.Hash()) } }
go
func logSkippedDeps(tx *btcutil.Tx, deps map[chainhash.Hash]*txPrioItem) { if deps == nil { return } for _, item := range deps { log.Tracef("Skipping tx %s since it depends on %s\n", item.tx.Hash(), tx.Hash()) } }
[ "func", "logSkippedDeps", "(", "tx", "*", "btcutil", ".", "Tx", ",", "deps", "map", "[", "chainhash", ".", "Hash", "]", "*", "txPrioItem", ")", "{", "if", "deps", "==", "nil", "{", "return", "\n", "}", "\n\n", "for", "_", ",", "item", ":=", "range", "deps", "{", "log", ".", "Tracef", "(", "\"", "\\n", "\"", ",", "item", ".", "tx", ".", "Hash", "(", ")", ",", "tx", ".", "Hash", "(", ")", ")", "\n", "}", "\n", "}" ]
// logSkippedDeps logs any dependencies which are also skipped as a result of // skipping a transaction while generating a block template at the trace level.
[ "logSkippedDeps", "logs", "any", "dependencies", "which", "are", "also", "skipped", "as", "a", "result", "of", "skipping", "a", "transaction", "while", "generating", "a", "block", "template", "at", "the", "trace", "level", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/mining.go#L306-L315
train
btcsuite/btcd
mining/mining.go
MinimumMedianTime
func MinimumMedianTime(chainState *blockchain.BestState) time.Time { return chainState.MedianTime.Add(time.Second) }
go
func MinimumMedianTime(chainState *blockchain.BestState) time.Time { return chainState.MedianTime.Add(time.Second) }
[ "func", "MinimumMedianTime", "(", "chainState", "*", "blockchain", ".", "BestState", ")", "time", ".", "Time", "{", "return", "chainState", ".", "MedianTime", ".", "Add", "(", "time", ".", "Second", ")", "\n", "}" ]
// MinimumMedianTime returns the minimum allowed timestamp for a block building // on the end of the provided best chain. In particular, it is one second after // the median timestamp of the last several blocks per the chain consensus // rules.
[ "MinimumMedianTime", "returns", "the", "minimum", "allowed", "timestamp", "for", "a", "block", "building", "on", "the", "end", "of", "the", "provided", "best", "chain", ".", "In", "particular", "it", "is", "one", "second", "after", "the", "median", "timestamp", "of", "the", "last", "several", "blocks", "per", "the", "chain", "consensus", "rules", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/mining.go#L321-L323
train
btcsuite/btcd
mining/mining.go
medianAdjustedTime
func medianAdjustedTime(chainState *blockchain.BestState, timeSource blockchain.MedianTimeSource) time.Time { // The timestamp for the block must not be before the median timestamp // of the last several blocks. Thus, choose the maximum between the // current time and one second after the past median time. The current // timestamp is truncated to a second boundary before comparison since a // block timestamp does not supported a precision greater than one // second. newTimestamp := timeSource.AdjustedTime() minTimestamp := MinimumMedianTime(chainState) if newTimestamp.Before(minTimestamp) { newTimestamp = minTimestamp } return newTimestamp }
go
func medianAdjustedTime(chainState *blockchain.BestState, timeSource blockchain.MedianTimeSource) time.Time { // The timestamp for the block must not be before the median timestamp // of the last several blocks. Thus, choose the maximum between the // current time and one second after the past median time. The current // timestamp is truncated to a second boundary before comparison since a // block timestamp does not supported a precision greater than one // second. newTimestamp := timeSource.AdjustedTime() minTimestamp := MinimumMedianTime(chainState) if newTimestamp.Before(minTimestamp) { newTimestamp = minTimestamp } return newTimestamp }
[ "func", "medianAdjustedTime", "(", "chainState", "*", "blockchain", ".", "BestState", ",", "timeSource", "blockchain", ".", "MedianTimeSource", ")", "time", ".", "Time", "{", "// The timestamp for the block must not be before the median timestamp", "// of the last several blocks. Thus, choose the maximum between the", "// current time and one second after the past median time. The current", "// timestamp is truncated to a second boundary before comparison since a", "// block timestamp does not supported a precision greater than one", "// second.", "newTimestamp", ":=", "timeSource", ".", "AdjustedTime", "(", ")", "\n", "minTimestamp", ":=", "MinimumMedianTime", "(", "chainState", ")", "\n", "if", "newTimestamp", ".", "Before", "(", "minTimestamp", ")", "{", "newTimestamp", "=", "minTimestamp", "\n", "}", "\n\n", "return", "newTimestamp", "\n", "}" ]
// medianAdjustedTime returns the current time adjusted to ensure it is at least // one second after the median timestamp of the last several blocks per the // chain consensus rules.
[ "medianAdjustedTime", "returns", "the", "current", "time", "adjusted", "to", "ensure", "it", "is", "at", "least", "one", "second", "after", "the", "median", "timestamp", "of", "the", "last", "several", "blocks", "per", "the", "chain", "consensus", "rules", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/mining.go#L328-L342
train
btcsuite/btcd
mining/mining.go
NewBlkTmplGenerator
func NewBlkTmplGenerator(policy *Policy, params *chaincfg.Params, txSource TxSource, chain *blockchain.BlockChain, timeSource blockchain.MedianTimeSource, sigCache *txscript.SigCache, hashCache *txscript.HashCache) *BlkTmplGenerator { return &BlkTmplGenerator{ policy: policy, chainParams: params, txSource: txSource, chain: chain, timeSource: timeSource, sigCache: sigCache, hashCache: hashCache, } }
go
func NewBlkTmplGenerator(policy *Policy, params *chaincfg.Params, txSource TxSource, chain *blockchain.BlockChain, timeSource blockchain.MedianTimeSource, sigCache *txscript.SigCache, hashCache *txscript.HashCache) *BlkTmplGenerator { return &BlkTmplGenerator{ policy: policy, chainParams: params, txSource: txSource, chain: chain, timeSource: timeSource, sigCache: sigCache, hashCache: hashCache, } }
[ "func", "NewBlkTmplGenerator", "(", "policy", "*", "Policy", ",", "params", "*", "chaincfg", ".", "Params", ",", "txSource", "TxSource", ",", "chain", "*", "blockchain", ".", "BlockChain", ",", "timeSource", "blockchain", ".", "MedianTimeSource", ",", "sigCache", "*", "txscript", ".", "SigCache", ",", "hashCache", "*", "txscript", ".", "HashCache", ")", "*", "BlkTmplGenerator", "{", "return", "&", "BlkTmplGenerator", "{", "policy", ":", "policy", ",", "chainParams", ":", "params", ",", "txSource", ":", "txSource", ",", "chain", ":", "chain", ",", "timeSource", ":", "timeSource", ",", "sigCache", ":", "sigCache", ",", "hashCache", ":", "hashCache", ",", "}", "\n", "}" ]
// NewBlkTmplGenerator returns a new block template generator for the given // policy using transactions from the provided transaction source. // // The additional state-related fields are required in order to ensure the // templates are built on top of the current best chain and adhere to the // consensus rules.
[ "NewBlkTmplGenerator", "returns", "a", "new", "block", "template", "generator", "for", "the", "given", "policy", "using", "transactions", "from", "the", "provided", "transaction", "source", ".", "The", "additional", "state", "-", "related", "fields", "are", "required", "in", "order", "to", "ensure", "the", "templates", "are", "built", "on", "top", "of", "the", "current", "best", "chain", "and", "adhere", "to", "the", "consensus", "rules", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/mining.go#L364-L379
train
btcsuite/btcd
mining/mining.go
UpdateBlockTime
func (g *BlkTmplGenerator) UpdateBlockTime(msgBlock *wire.MsgBlock) error { // The new timestamp is potentially adjusted to ensure it comes after // the median time of the last several blocks per the chain consensus // rules. newTime := medianAdjustedTime(g.chain.BestSnapshot(), g.timeSource) msgBlock.Header.Timestamp = newTime // Recalculate the difficulty if running on a network that requires it. if g.chainParams.ReduceMinDifficulty { difficulty, err := g.chain.CalcNextRequiredDifficulty(newTime) if err != nil { return err } msgBlock.Header.Bits = difficulty } return nil }
go
func (g *BlkTmplGenerator) UpdateBlockTime(msgBlock *wire.MsgBlock) error { // The new timestamp is potentially adjusted to ensure it comes after // the median time of the last several blocks per the chain consensus // rules. newTime := medianAdjustedTime(g.chain.BestSnapshot(), g.timeSource) msgBlock.Header.Timestamp = newTime // Recalculate the difficulty if running on a network that requires it. if g.chainParams.ReduceMinDifficulty { difficulty, err := g.chain.CalcNextRequiredDifficulty(newTime) if err != nil { return err } msgBlock.Header.Bits = difficulty } return nil }
[ "func", "(", "g", "*", "BlkTmplGenerator", ")", "UpdateBlockTime", "(", "msgBlock", "*", "wire", ".", "MsgBlock", ")", "error", "{", "// The new timestamp is potentially adjusted to ensure it comes after", "// the median time of the last several blocks per the chain consensus", "// rules.", "newTime", ":=", "medianAdjustedTime", "(", "g", ".", "chain", ".", "BestSnapshot", "(", ")", ",", "g", ".", "timeSource", ")", "\n", "msgBlock", ".", "Header", ".", "Timestamp", "=", "newTime", "\n\n", "// Recalculate the difficulty if running on a network that requires it.", "if", "g", ".", "chainParams", ".", "ReduceMinDifficulty", "{", "difficulty", ",", "err", ":=", "g", ".", "chain", ".", "CalcNextRequiredDifficulty", "(", "newTime", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "msgBlock", ".", "Header", ".", "Bits", "=", "difficulty", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// UpdateBlockTime updates the timestamp in the header of the passed block to // the current time while taking into account the median time of the last // several blocks to ensure the new time is after that time per the chain // consensus rules. Finally, it will update the target difficulty if needed // based on the new time for the test networks since their target difficulty can // change based upon time.
[ "UpdateBlockTime", "updates", "the", "timestamp", "in", "the", "header", "of", "the", "passed", "block", "to", "the", "current", "time", "while", "taking", "into", "account", "the", "median", "time", "of", "the", "last", "several", "blocks", "to", "ensure", "the", "new", "time", "is", "after", "that", "time", "per", "the", "chain", "consensus", "rules", ".", "Finally", "it", "will", "update", "the", "target", "difficulty", "if", "needed", "based", "on", "the", "new", "time", "for", "the", "test", "networks", "since", "their", "target", "difficulty", "can", "change", "based", "upon", "time", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/mining.go#L904-L921
train
btcsuite/btcd
mining/mining.go
UpdateExtraNonce
func (g *BlkTmplGenerator) UpdateExtraNonce(msgBlock *wire.MsgBlock, blockHeight int32, extraNonce uint64) error { coinbaseScript, err := standardCoinbaseScript(blockHeight, extraNonce) if err != nil { return err } if len(coinbaseScript) > blockchain.MaxCoinbaseScriptLen { return fmt.Errorf("coinbase transaction script length "+ "of %d is out of range (min: %d, max: %d)", len(coinbaseScript), blockchain.MinCoinbaseScriptLen, blockchain.MaxCoinbaseScriptLen) } msgBlock.Transactions[0].TxIn[0].SignatureScript = coinbaseScript // TODO(davec): A btcutil.Block should use saved in the state to avoid // recalculating all of the other transaction hashes. // block.Transactions[0].InvalidateCache() // Recalculate the merkle root with the updated extra nonce. block := btcutil.NewBlock(msgBlock) merkles := blockchain.BuildMerkleTreeStore(block.Transactions(), false) msgBlock.Header.MerkleRoot = *merkles[len(merkles)-1] return nil }
go
func (g *BlkTmplGenerator) UpdateExtraNonce(msgBlock *wire.MsgBlock, blockHeight int32, extraNonce uint64) error { coinbaseScript, err := standardCoinbaseScript(blockHeight, extraNonce) if err != nil { return err } if len(coinbaseScript) > blockchain.MaxCoinbaseScriptLen { return fmt.Errorf("coinbase transaction script length "+ "of %d is out of range (min: %d, max: %d)", len(coinbaseScript), blockchain.MinCoinbaseScriptLen, blockchain.MaxCoinbaseScriptLen) } msgBlock.Transactions[0].TxIn[0].SignatureScript = coinbaseScript // TODO(davec): A btcutil.Block should use saved in the state to avoid // recalculating all of the other transaction hashes. // block.Transactions[0].InvalidateCache() // Recalculate the merkle root with the updated extra nonce. block := btcutil.NewBlock(msgBlock) merkles := blockchain.BuildMerkleTreeStore(block.Transactions(), false) msgBlock.Header.MerkleRoot = *merkles[len(merkles)-1] return nil }
[ "func", "(", "g", "*", "BlkTmplGenerator", ")", "UpdateExtraNonce", "(", "msgBlock", "*", "wire", ".", "MsgBlock", ",", "blockHeight", "int32", ",", "extraNonce", "uint64", ")", "error", "{", "coinbaseScript", ",", "err", ":=", "standardCoinbaseScript", "(", "blockHeight", ",", "extraNonce", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "len", "(", "coinbaseScript", ")", ">", "blockchain", ".", "MaxCoinbaseScriptLen", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "len", "(", "coinbaseScript", ")", ",", "blockchain", ".", "MinCoinbaseScriptLen", ",", "blockchain", ".", "MaxCoinbaseScriptLen", ")", "\n", "}", "\n", "msgBlock", ".", "Transactions", "[", "0", "]", ".", "TxIn", "[", "0", "]", ".", "SignatureScript", "=", "coinbaseScript", "\n\n", "// TODO(davec): A btcutil.Block should use saved in the state to avoid", "// recalculating all of the other transaction hashes.", "// block.Transactions[0].InvalidateCache()", "// Recalculate the merkle root with the updated extra nonce.", "block", ":=", "btcutil", ".", "NewBlock", "(", "msgBlock", ")", "\n", "merkles", ":=", "blockchain", ".", "BuildMerkleTreeStore", "(", "block", ".", "Transactions", "(", ")", ",", "false", ")", "\n", "msgBlock", ".", "Header", ".", "MerkleRoot", "=", "*", "merkles", "[", "len", "(", "merkles", ")", "-", "1", "]", "\n", "return", "nil", "\n", "}" ]
// UpdateExtraNonce updates the extra nonce in the coinbase script of the passed // block by regenerating the coinbase script with the passed value and block // height. It also recalculates and updates the new merkle root that results // from changing the coinbase script.
[ "UpdateExtraNonce", "updates", "the", "extra", "nonce", "in", "the", "coinbase", "script", "of", "the", "passed", "block", "by", "regenerating", "the", "coinbase", "script", "with", "the", "passed", "value", "and", "block", "height", ".", "It", "also", "recalculates", "and", "updates", "the", "new", "merkle", "root", "that", "results", "from", "changing", "the", "coinbase", "script", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/mining/mining.go#L927-L949
train
btcsuite/btcd
rpcserverhelp.go
rpcMethodHelp
func (c *helpCacher) rpcMethodHelp(method string) (string, error) { c.Lock() defer c.Unlock() // Return the cached method help if it exists. if help, exists := c.methodHelp[method]; exists { return help, nil } // Look up the result types for the method. resultTypes, ok := rpcResultTypes[method] if !ok { return "", errors.New("no result types specified for method " + method) } // Generate, cache, and return the help. help, err := btcjson.GenerateHelp(method, helpDescsEnUS, resultTypes...) if err != nil { return "", err } c.methodHelp[method] = help return help, nil }
go
func (c *helpCacher) rpcMethodHelp(method string) (string, error) { c.Lock() defer c.Unlock() // Return the cached method help if it exists. if help, exists := c.methodHelp[method]; exists { return help, nil } // Look up the result types for the method. resultTypes, ok := rpcResultTypes[method] if !ok { return "", errors.New("no result types specified for method " + method) } // Generate, cache, and return the help. help, err := btcjson.GenerateHelp(method, helpDescsEnUS, resultTypes...) if err != nil { return "", err } c.methodHelp[method] = help return help, nil }
[ "func", "(", "c", "*", "helpCacher", ")", "rpcMethodHelp", "(", "method", "string", ")", "(", "string", ",", "error", ")", "{", "c", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "Unlock", "(", ")", "\n\n", "// Return the cached method help if it exists.", "if", "help", ",", "exists", ":=", "c", ".", "methodHelp", "[", "method", "]", ";", "exists", "{", "return", "help", ",", "nil", "\n", "}", "\n\n", "// Look up the result types for the method.", "resultTypes", ",", "ok", ":=", "rpcResultTypes", "[", "method", "]", "\n", "if", "!", "ok", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", "+", "method", ")", "\n", "}", "\n\n", "// Generate, cache, and return the help.", "help", ",", "err", ":=", "btcjson", ".", "GenerateHelp", "(", "method", ",", "helpDescsEnUS", ",", "resultTypes", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "c", ".", "methodHelp", "[", "method", "]", "=", "help", "\n", "return", "help", ",", "nil", "\n", "}" ]
// rpcMethodHelp returns an RPC help string for the provided method. // // This function is safe for concurrent access.
[ "rpcMethodHelp", "returns", "an", "RPC", "help", "string", "for", "the", "provided", "method", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserverhelp.go#L750-L773
train
btcsuite/btcd
rpcserverhelp.go
rpcUsage
func (c *helpCacher) rpcUsage(includeWebsockets bool) (string, error) { c.Lock() defer c.Unlock() // Return the cached usage if it is available. if c.usage != "" { return c.usage, nil } // Generate a list of one-line usage for every command. usageTexts := make([]string, 0, len(rpcHandlers)) for k := range rpcHandlers { usage, err := btcjson.MethodUsageText(k) if err != nil { return "", err } usageTexts = append(usageTexts, usage) } // Include websockets commands if requested. if includeWebsockets { for k := range wsHandlers { usage, err := btcjson.MethodUsageText(k) if err != nil { return "", err } usageTexts = append(usageTexts, usage) } } sort.Sort(sort.StringSlice(usageTexts)) c.usage = strings.Join(usageTexts, "\n") return c.usage, nil }
go
func (c *helpCacher) rpcUsage(includeWebsockets bool) (string, error) { c.Lock() defer c.Unlock() // Return the cached usage if it is available. if c.usage != "" { return c.usage, nil } // Generate a list of one-line usage for every command. usageTexts := make([]string, 0, len(rpcHandlers)) for k := range rpcHandlers { usage, err := btcjson.MethodUsageText(k) if err != nil { return "", err } usageTexts = append(usageTexts, usage) } // Include websockets commands if requested. if includeWebsockets { for k := range wsHandlers { usage, err := btcjson.MethodUsageText(k) if err != nil { return "", err } usageTexts = append(usageTexts, usage) } } sort.Sort(sort.StringSlice(usageTexts)) c.usage = strings.Join(usageTexts, "\n") return c.usage, nil }
[ "func", "(", "c", "*", "helpCacher", ")", "rpcUsage", "(", "includeWebsockets", "bool", ")", "(", "string", ",", "error", ")", "{", "c", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "Unlock", "(", ")", "\n\n", "// Return the cached usage if it is available.", "if", "c", ".", "usage", "!=", "\"", "\"", "{", "return", "c", ".", "usage", ",", "nil", "\n", "}", "\n\n", "// Generate a list of one-line usage for every command.", "usageTexts", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "rpcHandlers", ")", ")", "\n", "for", "k", ":=", "range", "rpcHandlers", "{", "usage", ",", "err", ":=", "btcjson", ".", "MethodUsageText", "(", "k", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "usageTexts", "=", "append", "(", "usageTexts", ",", "usage", ")", "\n", "}", "\n\n", "// Include websockets commands if requested.", "if", "includeWebsockets", "{", "for", "k", ":=", "range", "wsHandlers", "{", "usage", ",", "err", ":=", "btcjson", ".", "MethodUsageText", "(", "k", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "usageTexts", "=", "append", "(", "usageTexts", ",", "usage", ")", "\n", "}", "\n", "}", "\n\n", "sort", ".", "Sort", "(", "sort", ".", "StringSlice", "(", "usageTexts", ")", ")", "\n", "c", ".", "usage", "=", "strings", ".", "Join", "(", "usageTexts", ",", "\"", "\\n", "\"", ")", "\n", "return", "c", ".", "usage", ",", "nil", "\n", "}" ]
// rpcUsage returns one-line usage for all support RPC commands. // // This function is safe for concurrent access.
[ "rpcUsage", "returns", "one", "-", "line", "usage", "for", "all", "support", "RPC", "commands", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcserverhelp.go#L778-L811
train
btcsuite/btcd
blockchain/indexers/manager.go
dbFetchIndexerTip
func dbFetchIndexerTip(dbTx database.Tx, idxKey []byte) (*chainhash.Hash, int32, error) { indexesBucket := dbTx.Metadata().Bucket(indexTipsBucketName) serialized := indexesBucket.Get(idxKey) if len(serialized) < chainhash.HashSize+4 { return nil, 0, database.Error{ ErrorCode: database.ErrCorruption, Description: fmt.Sprintf("unexpected end of data for "+ "index %q tip", string(idxKey)), } } var hash chainhash.Hash copy(hash[:], serialized[:chainhash.HashSize]) height := int32(byteOrder.Uint32(serialized[chainhash.HashSize:])) return &hash, height, nil }
go
func dbFetchIndexerTip(dbTx database.Tx, idxKey []byte) (*chainhash.Hash, int32, error) { indexesBucket := dbTx.Metadata().Bucket(indexTipsBucketName) serialized := indexesBucket.Get(idxKey) if len(serialized) < chainhash.HashSize+4 { return nil, 0, database.Error{ ErrorCode: database.ErrCorruption, Description: fmt.Sprintf("unexpected end of data for "+ "index %q tip", string(idxKey)), } } var hash chainhash.Hash copy(hash[:], serialized[:chainhash.HashSize]) height := int32(byteOrder.Uint32(serialized[chainhash.HashSize:])) return &hash, height, nil }
[ "func", "dbFetchIndexerTip", "(", "dbTx", "database", ".", "Tx", ",", "idxKey", "[", "]", "byte", ")", "(", "*", "chainhash", ".", "Hash", ",", "int32", ",", "error", ")", "{", "indexesBucket", ":=", "dbTx", ".", "Metadata", "(", ")", ".", "Bucket", "(", "indexTipsBucketName", ")", "\n", "serialized", ":=", "indexesBucket", ".", "Get", "(", "idxKey", ")", "\n", "if", "len", "(", "serialized", ")", "<", "chainhash", ".", "HashSize", "+", "4", "{", "return", "nil", ",", "0", ",", "database", ".", "Error", "{", "ErrorCode", ":", "database", ".", "ErrCorruption", ",", "Description", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "string", "(", "idxKey", ")", ")", ",", "}", "\n", "}", "\n\n", "var", "hash", "chainhash", ".", "Hash", "\n", "copy", "(", "hash", "[", ":", "]", ",", "serialized", "[", ":", "chainhash", ".", "HashSize", "]", ")", "\n", "height", ":=", "int32", "(", "byteOrder", ".", "Uint32", "(", "serialized", "[", "chainhash", ".", "HashSize", ":", "]", ")", ")", "\n", "return", "&", "hash", ",", "height", ",", "nil", "\n", "}" ]
// dbFetchIndexerTip uses an existing database transaction to retrieve the // hash and height of the current tip for the provided index.
[ "dbFetchIndexerTip", "uses", "an", "existing", "database", "transaction", "to", "retrieve", "the", "hash", "and", "height", "of", "the", "current", "tip", "for", "the", "provided", "index", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/manager.go#L50-L65
train
btcsuite/btcd
blockchain/indexers/manager.go
dbIndexConnectBlock
func dbIndexConnectBlock(dbTx database.Tx, indexer Indexer, block *btcutil.Block, stxo []blockchain.SpentTxOut) error { // Assert that the block being connected properly connects to the // current tip of the index. idxKey := indexer.Key() curTipHash, _, err := dbFetchIndexerTip(dbTx, idxKey) if err != nil { return err } if !curTipHash.IsEqual(&block.MsgBlock().Header.PrevBlock) { return AssertError(fmt.Sprintf("dbIndexConnectBlock must be "+ "called with a block that extends the current index "+ "tip (%s, tip %s, block %s)", indexer.Name(), curTipHash, block.Hash())) } // Notify the indexer with the connected block so it can index it. if err := indexer.ConnectBlock(dbTx, block, stxo); err != nil { return err } // Update the current index tip. return dbPutIndexerTip(dbTx, idxKey, block.Hash(), block.Height()) }
go
func dbIndexConnectBlock(dbTx database.Tx, indexer Indexer, block *btcutil.Block, stxo []blockchain.SpentTxOut) error { // Assert that the block being connected properly connects to the // current tip of the index. idxKey := indexer.Key() curTipHash, _, err := dbFetchIndexerTip(dbTx, idxKey) if err != nil { return err } if !curTipHash.IsEqual(&block.MsgBlock().Header.PrevBlock) { return AssertError(fmt.Sprintf("dbIndexConnectBlock must be "+ "called with a block that extends the current index "+ "tip (%s, tip %s, block %s)", indexer.Name(), curTipHash, block.Hash())) } // Notify the indexer with the connected block so it can index it. if err := indexer.ConnectBlock(dbTx, block, stxo); err != nil { return err } // Update the current index tip. return dbPutIndexerTip(dbTx, idxKey, block.Hash(), block.Height()) }
[ "func", "dbIndexConnectBlock", "(", "dbTx", "database", ".", "Tx", ",", "indexer", "Indexer", ",", "block", "*", "btcutil", ".", "Block", ",", "stxo", "[", "]", "blockchain", ".", "SpentTxOut", ")", "error", "{", "// Assert that the block being connected properly connects to the", "// current tip of the index.", "idxKey", ":=", "indexer", ".", "Key", "(", ")", "\n", "curTipHash", ",", "_", ",", "err", ":=", "dbFetchIndexerTip", "(", "dbTx", ",", "idxKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "!", "curTipHash", ".", "IsEqual", "(", "&", "block", ".", "MsgBlock", "(", ")", ".", "Header", ".", "PrevBlock", ")", "{", "return", "AssertError", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ",", "indexer", ".", "Name", "(", ")", ",", "curTipHash", ",", "block", ".", "Hash", "(", ")", ")", ")", "\n", "}", "\n\n", "// Notify the indexer with the connected block so it can index it.", "if", "err", ":=", "indexer", ".", "ConnectBlock", "(", "dbTx", ",", "block", ",", "stxo", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Update the current index tip.", "return", "dbPutIndexerTip", "(", "dbTx", ",", "idxKey", ",", "block", ".", "Hash", "(", ")", ",", "block", ".", "Height", "(", ")", ")", "\n", "}" ]
// dbIndexConnectBlock adds all of the index entries associated with the // given block using the provided indexer and updates the tip of the indexer // accordingly. An error will be returned if the current tip for the indexer is // not the previous block for the passed block.
[ "dbIndexConnectBlock", "adds", "all", "of", "the", "index", "entries", "associated", "with", "the", "given", "block", "using", "the", "provided", "indexer", "and", "updates", "the", "tip", "of", "the", "indexer", "accordingly", ".", "An", "error", "will", "be", "returned", "if", "the", "current", "tip", "for", "the", "indexer", "is", "not", "the", "previous", "block", "for", "the", "passed", "block", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/manager.go#L71-L95
train
btcsuite/btcd
blockchain/indexers/manager.go
indexDropKey
func indexDropKey(idxKey []byte) []byte { dropKey := make([]byte, len(idxKey)+1) dropKey[0] = 'd' copy(dropKey[1:], idxKey) return dropKey }
go
func indexDropKey(idxKey []byte) []byte { dropKey := make([]byte, len(idxKey)+1) dropKey[0] = 'd' copy(dropKey[1:], idxKey) return dropKey }
[ "func", "indexDropKey", "(", "idxKey", "[", "]", "byte", ")", "[", "]", "byte", "{", "dropKey", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "idxKey", ")", "+", "1", ")", "\n", "dropKey", "[", "0", "]", "=", "'d'", "\n", "copy", "(", "dropKey", "[", "1", ":", "]", ",", "idxKey", ")", "\n", "return", "dropKey", "\n", "}" ]
// indexDropKey returns the key for an index which indicates it is in the // process of being dropped.
[ "indexDropKey", "returns", "the", "key", "for", "an", "index", "which", "indicates", "it", "is", "in", "the", "process", "of", "being", "dropped", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/manager.go#L142-L147
train
btcsuite/btcd
blockchain/indexers/manager.go
maybeFinishDrops
func (m *Manager) maybeFinishDrops(interrupt <-chan struct{}) error { indexNeedsDrop := make([]bool, len(m.enabledIndexes)) err := m.db.View(func(dbTx database.Tx) error { // None of the indexes needs to be dropped if the index tips // bucket hasn't been created yet. indexesBucket := dbTx.Metadata().Bucket(indexTipsBucketName) if indexesBucket == nil { return nil } // Mark the indexer as requiring a drop if one is already in // progress. for i, indexer := range m.enabledIndexes { dropKey := indexDropKey(indexer.Key()) if indexesBucket.Get(dropKey) != nil { indexNeedsDrop[i] = true } } return nil }) if err != nil { return err } if interruptRequested(interrupt) { return errInterruptRequested } // Finish dropping any of the enabled indexes that are already in the // middle of being dropped. for i, indexer := range m.enabledIndexes { if !indexNeedsDrop[i] { continue } log.Infof("Resuming %s drop", indexer.Name()) err := dropIndex(m.db, indexer.Key(), indexer.Name(), interrupt) if err != nil { return err } } return nil }
go
func (m *Manager) maybeFinishDrops(interrupt <-chan struct{}) error { indexNeedsDrop := make([]bool, len(m.enabledIndexes)) err := m.db.View(func(dbTx database.Tx) error { // None of the indexes needs to be dropped if the index tips // bucket hasn't been created yet. indexesBucket := dbTx.Metadata().Bucket(indexTipsBucketName) if indexesBucket == nil { return nil } // Mark the indexer as requiring a drop if one is already in // progress. for i, indexer := range m.enabledIndexes { dropKey := indexDropKey(indexer.Key()) if indexesBucket.Get(dropKey) != nil { indexNeedsDrop[i] = true } } return nil }) if err != nil { return err } if interruptRequested(interrupt) { return errInterruptRequested } // Finish dropping any of the enabled indexes that are already in the // middle of being dropped. for i, indexer := range m.enabledIndexes { if !indexNeedsDrop[i] { continue } log.Infof("Resuming %s drop", indexer.Name()) err := dropIndex(m.db, indexer.Key(), indexer.Name(), interrupt) if err != nil { return err } } return nil }
[ "func", "(", "m", "*", "Manager", ")", "maybeFinishDrops", "(", "interrupt", "<-", "chan", "struct", "{", "}", ")", "error", "{", "indexNeedsDrop", ":=", "make", "(", "[", "]", "bool", ",", "len", "(", "m", ".", "enabledIndexes", ")", ")", "\n", "err", ":=", "m", ".", "db", ".", "View", "(", "func", "(", "dbTx", "database", ".", "Tx", ")", "error", "{", "// None of the indexes needs to be dropped if the index tips", "// bucket hasn't been created yet.", "indexesBucket", ":=", "dbTx", ".", "Metadata", "(", ")", ".", "Bucket", "(", "indexTipsBucketName", ")", "\n", "if", "indexesBucket", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "// Mark the indexer as requiring a drop if one is already in", "// progress.", "for", "i", ",", "indexer", ":=", "range", "m", ".", "enabledIndexes", "{", "dropKey", ":=", "indexDropKey", "(", "indexer", ".", "Key", "(", ")", ")", "\n", "if", "indexesBucket", ".", "Get", "(", "dropKey", ")", "!=", "nil", "{", "indexNeedsDrop", "[", "i", "]", "=", "true", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "interruptRequested", "(", "interrupt", ")", "{", "return", "errInterruptRequested", "\n", "}", "\n\n", "// Finish dropping any of the enabled indexes that are already in the", "// middle of being dropped.", "for", "i", ",", "indexer", ":=", "range", "m", ".", "enabledIndexes", "{", "if", "!", "indexNeedsDrop", "[", "i", "]", "{", "continue", "\n", "}", "\n\n", "log", ".", "Infof", "(", "\"", "\"", ",", "indexer", ".", "Name", "(", ")", ")", "\n", "err", ":=", "dropIndex", "(", "m", ".", "db", ",", "indexer", ".", "Key", "(", ")", ",", "indexer", ".", "Name", "(", ")", ",", "interrupt", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// maybeFinishDrops determines if each of the enabled indexes are in the middle // of being dropped and finishes dropping them when the are. This is necessary // because dropping and index has to be done in several atomic steps rather than // one big atomic step due to the massive number of entries.
[ "maybeFinishDrops", "determines", "if", "each", "of", "the", "enabled", "indexes", "are", "in", "the", "middle", "of", "being", "dropped", "and", "finishes", "dropping", "them", "when", "the", "are", ".", "This", "is", "necessary", "because", "dropping", "and", "index", "has", "to", "be", "done", "in", "several", "atomic", "steps", "rather", "than", "one", "big", "atomic", "step", "due", "to", "the", "massive", "number", "of", "entries", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/manager.go#L153-L197
train
btcsuite/btcd
blockchain/indexers/manager.go
maybeCreateIndexes
func (m *Manager) maybeCreateIndexes(dbTx database.Tx) error { indexesBucket := dbTx.Metadata().Bucket(indexTipsBucketName) for _, indexer := range m.enabledIndexes { // Nothing to do if the index tip already exists. idxKey := indexer.Key() if indexesBucket.Get(idxKey) != nil { continue } // The tip for the index does not exist, so create it and // invoke the create callback for the index so it can perform // any one-time initialization it requires. if err := indexer.Create(dbTx); err != nil { return err } // Set the tip for the index to values which represent an // uninitialized index. err := dbPutIndexerTip(dbTx, idxKey, &chainhash.Hash{}, -1) if err != nil { return err } } return nil }
go
func (m *Manager) maybeCreateIndexes(dbTx database.Tx) error { indexesBucket := dbTx.Metadata().Bucket(indexTipsBucketName) for _, indexer := range m.enabledIndexes { // Nothing to do if the index tip already exists. idxKey := indexer.Key() if indexesBucket.Get(idxKey) != nil { continue } // The tip for the index does not exist, so create it and // invoke the create callback for the index so it can perform // any one-time initialization it requires. if err := indexer.Create(dbTx); err != nil { return err } // Set the tip for the index to values which represent an // uninitialized index. err := dbPutIndexerTip(dbTx, idxKey, &chainhash.Hash{}, -1) if err != nil { return err } } return nil }
[ "func", "(", "m", "*", "Manager", ")", "maybeCreateIndexes", "(", "dbTx", "database", ".", "Tx", ")", "error", "{", "indexesBucket", ":=", "dbTx", ".", "Metadata", "(", ")", ".", "Bucket", "(", "indexTipsBucketName", ")", "\n", "for", "_", ",", "indexer", ":=", "range", "m", ".", "enabledIndexes", "{", "// Nothing to do if the index tip already exists.", "idxKey", ":=", "indexer", ".", "Key", "(", ")", "\n", "if", "indexesBucket", ".", "Get", "(", "idxKey", ")", "!=", "nil", "{", "continue", "\n", "}", "\n\n", "// The tip for the index does not exist, so create it and", "// invoke the create callback for the index so it can perform", "// any one-time initialization it requires.", "if", "err", ":=", "indexer", ".", "Create", "(", "dbTx", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Set the tip for the index to values which represent an", "// uninitialized index.", "err", ":=", "dbPutIndexerTip", "(", "dbTx", ",", "idxKey", ",", "&", "chainhash", ".", "Hash", "{", "}", ",", "-", "1", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// maybeCreateIndexes determines if each of the enabled indexes have already // been created and creates them if not.
[ "maybeCreateIndexes", "determines", "if", "each", "of", "the", "enabled", "indexes", "have", "already", "been", "created", "and", "creates", "them", "if", "not", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/manager.go#L201-L226
train
btcsuite/btcd
blockchain/indexers/manager.go
indexNeedsInputs
func indexNeedsInputs(index Indexer) bool { if idx, ok := index.(NeedsInputser); ok { return idx.NeedsInputs() } return false }
go
func indexNeedsInputs(index Indexer) bool { if idx, ok := index.(NeedsInputser); ok { return idx.NeedsInputs() } return false }
[ "func", "indexNeedsInputs", "(", "index", "Indexer", ")", "bool", "{", "if", "idx", ",", "ok", ":=", "index", ".", "(", "NeedsInputser", ")", ";", "ok", "{", "return", "idx", ".", "NeedsInputs", "(", ")", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// indexNeedsInputs returns whether or not the index needs access to the txouts // referenced by the transaction inputs being indexed.
[ "indexNeedsInputs", "returns", "whether", "or", "not", "the", "index", "needs", "access", "to", "the", "txouts", "referenced", "by", "the", "transaction", "inputs", "being", "indexed", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/manager.go#L461-L467
train
btcsuite/btcd
blockchain/indexers/manager.go
dbFetchTx
func dbFetchTx(dbTx database.Tx, hash *chainhash.Hash) (*wire.MsgTx, error) { // Look up the location of the transaction. blockRegion, err := dbFetchTxIndexEntry(dbTx, hash) if err != nil { return nil, err } if blockRegion == nil { return nil, fmt.Errorf("transaction %v not found", hash) } // Load the raw transaction bytes from the database. txBytes, err := dbTx.FetchBlockRegion(blockRegion) if err != nil { return nil, err } // Deserialize the transaction. var msgTx wire.MsgTx err = msgTx.Deserialize(bytes.NewReader(txBytes)) if err != nil { return nil, err } return &msgTx, nil }
go
func dbFetchTx(dbTx database.Tx, hash *chainhash.Hash) (*wire.MsgTx, error) { // Look up the location of the transaction. blockRegion, err := dbFetchTxIndexEntry(dbTx, hash) if err != nil { return nil, err } if blockRegion == nil { return nil, fmt.Errorf("transaction %v not found", hash) } // Load the raw transaction bytes from the database. txBytes, err := dbTx.FetchBlockRegion(blockRegion) if err != nil { return nil, err } // Deserialize the transaction. var msgTx wire.MsgTx err = msgTx.Deserialize(bytes.NewReader(txBytes)) if err != nil { return nil, err } return &msgTx, nil }
[ "func", "dbFetchTx", "(", "dbTx", "database", ".", "Tx", ",", "hash", "*", "chainhash", ".", "Hash", ")", "(", "*", "wire", ".", "MsgTx", ",", "error", ")", "{", "// Look up the location of the transaction.", "blockRegion", ",", "err", ":=", "dbFetchTxIndexEntry", "(", "dbTx", ",", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "blockRegion", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hash", ")", "\n", "}", "\n\n", "// Load the raw transaction bytes from the database.", "txBytes", ",", "err", ":=", "dbTx", ".", "FetchBlockRegion", "(", "blockRegion", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Deserialize the transaction.", "var", "msgTx", "wire", ".", "MsgTx", "\n", "err", "=", "msgTx", ".", "Deserialize", "(", "bytes", ".", "NewReader", "(", "txBytes", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "msgTx", ",", "nil", "\n", "}" ]
// dbFetchTx looks up the passed transaction hash in the transaction index and // loads it from the database.
[ "dbFetchTx", "looks", "up", "the", "passed", "transaction", "hash", "in", "the", "transaction", "index", "and", "loads", "it", "from", "the", "database", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/manager.go#L471-L495
train
btcsuite/btcd
blockchain/indexers/manager.go
ConnectBlock
func (m *Manager) ConnectBlock(dbTx database.Tx, block *btcutil.Block, stxos []blockchain.SpentTxOut) error { // Call each of the currently active optional indexes with the block // being connected so they can update accordingly. for _, index := range m.enabledIndexes { err := dbIndexConnectBlock(dbTx, index, block, stxos) if err != nil { return err } } return nil }
go
func (m *Manager) ConnectBlock(dbTx database.Tx, block *btcutil.Block, stxos []blockchain.SpentTxOut) error { // Call each of the currently active optional indexes with the block // being connected so they can update accordingly. for _, index := range m.enabledIndexes { err := dbIndexConnectBlock(dbTx, index, block, stxos) if err != nil { return err } } return nil }
[ "func", "(", "m", "*", "Manager", ")", "ConnectBlock", "(", "dbTx", "database", ".", "Tx", ",", "block", "*", "btcutil", ".", "Block", ",", "stxos", "[", "]", "blockchain", ".", "SpentTxOut", ")", "error", "{", "// Call each of the currently active optional indexes with the block", "// being connected so they can update accordingly.", "for", "_", ",", "index", ":=", "range", "m", ".", "enabledIndexes", "{", "err", ":=", "dbIndexConnectBlock", "(", "dbTx", ",", "index", ",", "block", ",", "stxos", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ConnectBlock must be invoked when a block is extending the main chain. It // keeps track of the state of each index it is managing, performs some sanity // checks, and invokes each indexer. // // This is part of the blockchain.IndexManager interface.
[ "ConnectBlock", "must", "be", "invoked", "when", "a", "block", "is", "extending", "the", "main", "chain", ".", "It", "keeps", "track", "of", "the", "state", "of", "each", "index", "it", "is", "managing", "performs", "some", "sanity", "checks", "and", "invokes", "each", "indexer", ".", "This", "is", "part", "of", "the", "blockchain", ".", "IndexManager", "interface", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/manager.go#L502-L514
train
btcsuite/btcd
blockchain/indexers/manager.go
DisconnectBlock
func (m *Manager) DisconnectBlock(dbTx database.Tx, block *btcutil.Block, stxo []blockchain.SpentTxOut) error { // Call each of the currently active optional indexes with the block // being disconnected so they can update accordingly. for _, index := range m.enabledIndexes { err := dbIndexDisconnectBlock(dbTx, index, block, stxo) if err != nil { return err } } return nil }
go
func (m *Manager) DisconnectBlock(dbTx database.Tx, block *btcutil.Block, stxo []blockchain.SpentTxOut) error { // Call each of the currently active optional indexes with the block // being disconnected so they can update accordingly. for _, index := range m.enabledIndexes { err := dbIndexDisconnectBlock(dbTx, index, block, stxo) if err != nil { return err } } return nil }
[ "func", "(", "m", "*", "Manager", ")", "DisconnectBlock", "(", "dbTx", "database", ".", "Tx", ",", "block", "*", "btcutil", ".", "Block", ",", "stxo", "[", "]", "blockchain", ".", "SpentTxOut", ")", "error", "{", "// Call each of the currently active optional indexes with the block", "// being disconnected so they can update accordingly.", "for", "_", ",", "index", ":=", "range", "m", ".", "enabledIndexes", "{", "err", ":=", "dbIndexDisconnectBlock", "(", "dbTx", ",", "index", ",", "block", ",", "stxo", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DisconnectBlock must be invoked when a block is being disconnected from the // end of the main chain. It keeps track of the state of each index it is // managing, performs some sanity checks, and invokes each indexer to remove // the index entries associated with the block. // // This is part of the blockchain.IndexManager interface.
[ "DisconnectBlock", "must", "be", "invoked", "when", "a", "block", "is", "being", "disconnected", "from", "the", "end", "of", "the", "main", "chain", ".", "It", "keeps", "track", "of", "the", "state", "of", "each", "index", "it", "is", "managing", "performs", "some", "sanity", "checks", "and", "invokes", "each", "indexer", "to", "remove", "the", "index", "entries", "associated", "with", "the", "block", ".", "This", "is", "part", "of", "the", "blockchain", ".", "IndexManager", "interface", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/manager.go#L522-L534
train
btcsuite/btcd
blockchain/indexers/manager.go
NewManager
func NewManager(db database.DB, enabledIndexes []Indexer) *Manager { return &Manager{ db: db, enabledIndexes: enabledIndexes, } }
go
func NewManager(db database.DB, enabledIndexes []Indexer) *Manager { return &Manager{ db: db, enabledIndexes: enabledIndexes, } }
[ "func", "NewManager", "(", "db", "database", ".", "DB", ",", "enabledIndexes", "[", "]", "Indexer", ")", "*", "Manager", "{", "return", "&", "Manager", "{", "db", ":", "db", ",", "enabledIndexes", ":", "enabledIndexes", ",", "}", "\n", "}" ]
// NewManager returns a new index manager with the provided indexes enabled. // // The manager returned satisfies the blockchain.IndexManager interface and thus // cleanly plugs into the normal blockchain processing path.
[ "NewManager", "returns", "a", "new", "index", "manager", "with", "the", "provided", "indexes", "enabled", ".", "The", "manager", "returned", "satisfies", "the", "blockchain", ".", "IndexManager", "interface", "and", "thus", "cleanly", "plugs", "into", "the", "normal", "blockchain", "processing", "path", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/indexers/manager.go#L540-L545
train
btcsuite/btcd
rpcclient/rawrequest.go
RawRequestAsync
func (c *Client) RawRequestAsync(method string, params []json.RawMessage) FutureRawResult { // Method may not be empty. if method == "" { return newFutureError(errors.New("no method")) } // Marshal parameters as "[]" instead of "null" when no parameters // are passed. if params == nil { params = []json.RawMessage{} } // Create a raw JSON-RPC request using the provided method and params // and marshal it. This is done rather than using the sendCmd function // since that relies on marshalling registered btcjson commands rather // than custom commands. id := c.NextID() rawRequest := &btcjson.Request{ Jsonrpc: "1.0", ID: id, Method: method, Params: params, } marshalledJSON, err := json.Marshal(rawRequest) if err != nil { return newFutureError(err) } // Generate the request and send it along with a channel to respond on. responseChan := make(chan *response, 1) jReq := &jsonRequest{ id: id, method: method, cmd: nil, marshalledJSON: marshalledJSON, responseChan: responseChan, } c.sendRequest(jReq) return responseChan }
go
func (c *Client) RawRequestAsync(method string, params []json.RawMessage) FutureRawResult { // Method may not be empty. if method == "" { return newFutureError(errors.New("no method")) } // Marshal parameters as "[]" instead of "null" when no parameters // are passed. if params == nil { params = []json.RawMessage{} } // Create a raw JSON-RPC request using the provided method and params // and marshal it. This is done rather than using the sendCmd function // since that relies on marshalling registered btcjson commands rather // than custom commands. id := c.NextID() rawRequest := &btcjson.Request{ Jsonrpc: "1.0", ID: id, Method: method, Params: params, } marshalledJSON, err := json.Marshal(rawRequest) if err != nil { return newFutureError(err) } // Generate the request and send it along with a channel to respond on. responseChan := make(chan *response, 1) jReq := &jsonRequest{ id: id, method: method, cmd: nil, marshalledJSON: marshalledJSON, responseChan: responseChan, } c.sendRequest(jReq) return responseChan }
[ "func", "(", "c", "*", "Client", ")", "RawRequestAsync", "(", "method", "string", ",", "params", "[", "]", "json", ".", "RawMessage", ")", "FutureRawResult", "{", "// Method may not be empty.", "if", "method", "==", "\"", "\"", "{", "return", "newFutureError", "(", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n\n", "// Marshal parameters as \"[]\" instead of \"null\" when no parameters", "// are passed.", "if", "params", "==", "nil", "{", "params", "=", "[", "]", "json", ".", "RawMessage", "{", "}", "\n", "}", "\n\n", "// Create a raw JSON-RPC request using the provided method and params", "// and marshal it. This is done rather than using the sendCmd function", "// since that relies on marshalling registered btcjson commands rather", "// than custom commands.", "id", ":=", "c", ".", "NextID", "(", ")", "\n", "rawRequest", ":=", "&", "btcjson", ".", "Request", "{", "Jsonrpc", ":", "\"", "\"", ",", "ID", ":", "id", ",", "Method", ":", "method", ",", "Params", ":", "params", ",", "}", "\n", "marshalledJSON", ",", "err", ":=", "json", ".", "Marshal", "(", "rawRequest", ")", "\n", "if", "err", "!=", "nil", "{", "return", "newFutureError", "(", "err", ")", "\n", "}", "\n\n", "// Generate the request and send it along with a channel to respond on.", "responseChan", ":=", "make", "(", "chan", "*", "response", ",", "1", ")", "\n", "jReq", ":=", "&", "jsonRequest", "{", "id", ":", "id", ",", "method", ":", "method", ",", "cmd", ":", "nil", ",", "marshalledJSON", ":", "marshalledJSON", ",", "responseChan", ":", "responseChan", ",", "}", "\n", "c", ".", "sendRequest", "(", "jReq", ")", "\n\n", "return", "responseChan", "\n", "}" ]
// RawRequestAsync returns an instance of a type that can be used to get the // result of a custom RPC request at some future time by invoking the Receive // function on the returned instance. // // See RawRequest for the blocking version and more details.
[ "RawRequestAsync", "returns", "an", "instance", "of", "a", "type", "that", "can", "be", "used", "to", "get", "the", "result", "of", "a", "custom", "RPC", "request", "at", "some", "future", "time", "by", "invoking", "the", "Receive", "function", "on", "the", "returned", "instance", ".", "See", "RawRequest", "for", "the", "blocking", "version", "and", "more", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/rawrequest.go#L29-L69
train
btcsuite/btcd
rpcclient/rawrequest.go
RawRequest
func (c *Client) RawRequest(method string, params []json.RawMessage) (json.RawMessage, error) { return c.RawRequestAsync(method, params).Receive() }
go
func (c *Client) RawRequest(method string, params []json.RawMessage) (json.RawMessage, error) { return c.RawRequestAsync(method, params).Receive() }
[ "func", "(", "c", "*", "Client", ")", "RawRequest", "(", "method", "string", ",", "params", "[", "]", "json", ".", "RawMessage", ")", "(", "json", ".", "RawMessage", ",", "error", ")", "{", "return", "c", ".", "RawRequestAsync", "(", "method", ",", "params", ")", ".", "Receive", "(", ")", "\n", "}" ]
// RawRequest allows the caller to send a raw or custom request to the server. // This method may be used to send and receive requests and responses for // requests that are not handled by this client package, or to proxy partially // unmarshaled requests to another JSON-RPC server if a request cannot be // handled directly.
[ "RawRequest", "allows", "the", "caller", "to", "send", "a", "raw", "or", "custom", "request", "to", "the", "server", ".", "This", "method", "may", "be", "used", "to", "send", "and", "receive", "requests", "and", "responses", "for", "requests", "that", "are", "not", "handled", "by", "this", "client", "package", "or", "to", "proxy", "partially", "unmarshaled", "requests", "to", "another", "JSON", "-", "RPC", "server", "if", "a", "request", "cannot", "be", "handled", "directly", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/rawrequest.go#L76-L78
train
btcsuite/btcd
blockchain/validate.go
isNullOutpoint
func isNullOutpoint(outpoint *wire.OutPoint) bool { if outpoint.Index == math.MaxUint32 && outpoint.Hash == zeroHash { return true } return false }
go
func isNullOutpoint(outpoint *wire.OutPoint) bool { if outpoint.Index == math.MaxUint32 && outpoint.Hash == zeroHash { return true } return false }
[ "func", "isNullOutpoint", "(", "outpoint", "*", "wire", ".", "OutPoint", ")", "bool", "{", "if", "outpoint", ".", "Index", "==", "math", ".", "MaxUint32", "&&", "outpoint", ".", "Hash", "==", "zeroHash", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isNullOutpoint determines whether or not a previous transaction output point // is set.
[ "isNullOutpoint", "determines", "whether", "or", "not", "a", "previous", "transaction", "output", "point", "is", "set", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/validate.go#L65-L70
train
btcsuite/btcd
blockchain/validate.go
IsCoinBaseTx
func IsCoinBaseTx(msgTx *wire.MsgTx) bool { // A coin base must only have one transaction input. if len(msgTx.TxIn) != 1 { return false } // The previous output of a coin base must have a max value index and // a zero hash. prevOut := &msgTx.TxIn[0].PreviousOutPoint if prevOut.Index != math.MaxUint32 || prevOut.Hash != zeroHash { return false } return true }
go
func IsCoinBaseTx(msgTx *wire.MsgTx) bool { // A coin base must only have one transaction input. if len(msgTx.TxIn) != 1 { return false } // The previous output of a coin base must have a max value index and // a zero hash. prevOut := &msgTx.TxIn[0].PreviousOutPoint if prevOut.Index != math.MaxUint32 || prevOut.Hash != zeroHash { return false } return true }
[ "func", "IsCoinBaseTx", "(", "msgTx", "*", "wire", ".", "MsgTx", ")", "bool", "{", "// A coin base must only have one transaction input.", "if", "len", "(", "msgTx", ".", "TxIn", ")", "!=", "1", "{", "return", "false", "\n", "}", "\n\n", "// The previous output of a coin base must have a max value index and", "// a zero hash.", "prevOut", ":=", "&", "msgTx", ".", "TxIn", "[", "0", "]", ".", "PreviousOutPoint", "\n", "if", "prevOut", ".", "Index", "!=", "math", ".", "MaxUint32", "||", "prevOut", ".", "Hash", "!=", "zeroHash", "{", "return", "false", "\n", "}", "\n\n", "return", "true", "\n", "}" ]
// IsCoinBaseTx determines whether or not a transaction is a coinbase. A coinbase // is a special transaction created by miners that has no inputs. This is // represented in the block chain by a transaction with a single input that has // a previous output transaction index set to the maximum value along with a // zero hash. // // This function only differs from IsCoinBase in that it works with a raw wire // transaction as opposed to a higher level util transaction.
[ "IsCoinBaseTx", "determines", "whether", "or", "not", "a", "transaction", "is", "a", "coinbase", ".", "A", "coinbase", "is", "a", "special", "transaction", "created", "by", "miners", "that", "has", "no", "inputs", ".", "This", "is", "represented", "in", "the", "block", "chain", "by", "a", "transaction", "with", "a", "single", "input", "that", "has", "a", "previous", "output", "transaction", "index", "set", "to", "the", "maximum", "value", "along", "with", "a", "zero", "hash", ".", "This", "function", "only", "differs", "from", "IsCoinBase", "in", "that", "it", "works", "with", "a", "raw", "wire", "transaction", "as", "opposed", "to", "a", "higher", "level", "util", "transaction", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/validate.go#L89-L103
train
btcsuite/btcd
blockchain/validate.go
SequenceLockActive
func SequenceLockActive(sequenceLock *SequenceLock, blockHeight int32, medianTimePast time.Time) bool { // If either the seconds, or height relative-lock time has not yet // reached, then the transaction is not yet mature according to its // sequence locks. if sequenceLock.Seconds >= medianTimePast.Unix() || sequenceLock.BlockHeight >= blockHeight { return false } return true }
go
func SequenceLockActive(sequenceLock *SequenceLock, blockHeight int32, medianTimePast time.Time) bool { // If either the seconds, or height relative-lock time has not yet // reached, then the transaction is not yet mature according to its // sequence locks. if sequenceLock.Seconds >= medianTimePast.Unix() || sequenceLock.BlockHeight >= blockHeight { return false } return true }
[ "func", "SequenceLockActive", "(", "sequenceLock", "*", "SequenceLock", ",", "blockHeight", "int32", ",", "medianTimePast", "time", ".", "Time", ")", "bool", "{", "// If either the seconds, or height relative-lock time has not yet", "// reached, then the transaction is not yet mature according to its", "// sequence locks.", "if", "sequenceLock", ".", "Seconds", ">=", "medianTimePast", ".", "Unix", "(", ")", "||", "sequenceLock", ".", "BlockHeight", ">=", "blockHeight", "{", "return", "false", "\n", "}", "\n\n", "return", "true", "\n", "}" ]
// SequenceLockActive determines if a transaction's sequence locks have been // met, meaning that all the inputs of a given transaction have reached a // height or time sufficient for their relative lock-time maturity.
[ "SequenceLockActive", "determines", "if", "a", "transaction", "s", "sequence", "locks", "have", "been", "met", "meaning", "that", "all", "the", "inputs", "of", "a", "given", "transaction", "have", "reached", "a", "height", "or", "time", "sufficient", "for", "their", "relative", "lock", "-", "time", "maturity", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/validate.go#L120-L132
train
btcsuite/btcd
blockchain/validate.go
IsFinalizedTransaction
func IsFinalizedTransaction(tx *btcutil.Tx, blockHeight int32, blockTime time.Time) bool { msgTx := tx.MsgTx() // Lock time of zero means the transaction is finalized. lockTime := msgTx.LockTime if lockTime == 0 { return true } // The lock time field of a transaction is either a block height at // which the transaction is finalized or a timestamp depending on if the // value is before the txscript.LockTimeThreshold. When it is under the // threshold it is a block height. blockTimeOrHeight := int64(0) if lockTime < txscript.LockTimeThreshold { blockTimeOrHeight = int64(blockHeight) } else { blockTimeOrHeight = blockTime.Unix() } if int64(lockTime) < blockTimeOrHeight { return true } // At this point, the transaction's lock time hasn't occurred yet, but // the transaction might still be finalized if the sequence number // for all transaction inputs is maxed out. for _, txIn := range msgTx.TxIn { if txIn.Sequence != math.MaxUint32 { return false } } return true }
go
func IsFinalizedTransaction(tx *btcutil.Tx, blockHeight int32, blockTime time.Time) bool { msgTx := tx.MsgTx() // Lock time of zero means the transaction is finalized. lockTime := msgTx.LockTime if lockTime == 0 { return true } // The lock time field of a transaction is either a block height at // which the transaction is finalized or a timestamp depending on if the // value is before the txscript.LockTimeThreshold. When it is under the // threshold it is a block height. blockTimeOrHeight := int64(0) if lockTime < txscript.LockTimeThreshold { blockTimeOrHeight = int64(blockHeight) } else { blockTimeOrHeight = blockTime.Unix() } if int64(lockTime) < blockTimeOrHeight { return true } // At this point, the transaction's lock time hasn't occurred yet, but // the transaction might still be finalized if the sequence number // for all transaction inputs is maxed out. for _, txIn := range msgTx.TxIn { if txIn.Sequence != math.MaxUint32 { return false } } return true }
[ "func", "IsFinalizedTransaction", "(", "tx", "*", "btcutil", ".", "Tx", ",", "blockHeight", "int32", ",", "blockTime", "time", ".", "Time", ")", "bool", "{", "msgTx", ":=", "tx", ".", "MsgTx", "(", ")", "\n\n", "// Lock time of zero means the transaction is finalized.", "lockTime", ":=", "msgTx", ".", "LockTime", "\n", "if", "lockTime", "==", "0", "{", "return", "true", "\n", "}", "\n\n", "// The lock time field of a transaction is either a block height at", "// which the transaction is finalized or a timestamp depending on if the", "// value is before the txscript.LockTimeThreshold. When it is under the", "// threshold it is a block height.", "blockTimeOrHeight", ":=", "int64", "(", "0", ")", "\n", "if", "lockTime", "<", "txscript", ".", "LockTimeThreshold", "{", "blockTimeOrHeight", "=", "int64", "(", "blockHeight", ")", "\n", "}", "else", "{", "blockTimeOrHeight", "=", "blockTime", ".", "Unix", "(", ")", "\n", "}", "\n", "if", "int64", "(", "lockTime", ")", "<", "blockTimeOrHeight", "{", "return", "true", "\n", "}", "\n\n", "// At this point, the transaction's lock time hasn't occurred yet, but", "// the transaction might still be finalized if the sequence number", "// for all transaction inputs is maxed out.", "for", "_", ",", "txIn", ":=", "range", "msgTx", ".", "TxIn", "{", "if", "txIn", ".", "Sequence", "!=", "math", ".", "MaxUint32", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// IsFinalizedTransaction determines whether or not a transaction is finalized.
[ "IsFinalizedTransaction", "determines", "whether", "or", "not", "a", "transaction", "is", "finalized", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/validate.go#L135-L167
train
btcsuite/btcd
blockchain/validate.go
isBIP0030Node
func isBIP0030Node(node *blockNode) bool { if node.height == 91842 && node.hash.IsEqual(block91842Hash) { return true } if node.height == 91880 && node.hash.IsEqual(block91880Hash) { return true } return false }
go
func isBIP0030Node(node *blockNode) bool { if node.height == 91842 && node.hash.IsEqual(block91842Hash) { return true } if node.height == 91880 && node.hash.IsEqual(block91880Hash) { return true } return false }
[ "func", "isBIP0030Node", "(", "node", "*", "blockNode", ")", "bool", "{", "if", "node", ".", "height", "==", "91842", "&&", "node", ".", "hash", ".", "IsEqual", "(", "block91842Hash", ")", "{", "return", "true", "\n", "}", "\n\n", "if", "node", ".", "height", "==", "91880", "&&", "node", ".", "hash", ".", "IsEqual", "(", "block91880Hash", ")", "{", "return", "true", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// isBIP0030Node returns whether or not the passed node represents one of the // two blocks that violate the BIP0030 rule which prevents transactions from // overwriting old ones.
[ "isBIP0030Node", "returns", "whether", "or", "not", "the", "passed", "node", "represents", "one", "of", "the", "two", "blocks", "that", "violate", "the", "BIP0030", "rule", "which", "prevents", "transactions", "from", "overwriting", "old", "ones", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/validate.go#L172-L182
train
btcsuite/btcd
blockchain/validate.go
CheckTransactionSanity
func CheckTransactionSanity(tx *btcutil.Tx) error { // A transaction must have at least one input. msgTx := tx.MsgTx() if len(msgTx.TxIn) == 0 { return ruleError(ErrNoTxInputs, "transaction has no inputs") } // A transaction must have at least one output. if len(msgTx.TxOut) == 0 { return ruleError(ErrNoTxOutputs, "transaction has no outputs") } // A transaction must not exceed the maximum allowed block payload when // serialized. serializedTxSize := tx.MsgTx().SerializeSizeStripped() if serializedTxSize > MaxBlockBaseSize { str := fmt.Sprintf("serialized transaction is too big - got "+ "%d, max %d", serializedTxSize, MaxBlockBaseSize) return ruleError(ErrTxTooBig, str) } // Ensure the transaction amounts are in range. Each transaction // output must not be negative or more than the max allowed per // transaction. Also, the total of all outputs must abide by the same // restrictions. All amounts in a transaction are in a unit value known // as a satoshi. One bitcoin is a quantity of satoshi as defined by the // SatoshiPerBitcoin constant. var totalSatoshi int64 for _, txOut := range msgTx.TxOut { satoshi := txOut.Value if satoshi < 0 { str := fmt.Sprintf("transaction output has negative "+ "value of %v", satoshi) return ruleError(ErrBadTxOutValue, str) } if satoshi > btcutil.MaxSatoshi { str := fmt.Sprintf("transaction output value of %v is "+ "higher than max allowed value of %v", satoshi, btcutil.MaxSatoshi) return ruleError(ErrBadTxOutValue, str) } // Two's complement int64 overflow guarantees that any overflow // is detected and reported. This is impossible for Bitcoin, but // perhaps possible if an alt increases the total money supply. totalSatoshi += satoshi if totalSatoshi < 0 { str := fmt.Sprintf("total value of all transaction "+ "outputs exceeds max allowed value of %v", btcutil.MaxSatoshi) return ruleError(ErrBadTxOutValue, str) } if totalSatoshi > btcutil.MaxSatoshi { str := fmt.Sprintf("total value of all transaction "+ "outputs is %v which is higher than max "+ "allowed value of %v", totalSatoshi, btcutil.MaxSatoshi) return ruleError(ErrBadTxOutValue, str) } } // Check for duplicate transaction inputs. existingTxOut := make(map[wire.OutPoint]struct{}) for _, txIn := range msgTx.TxIn { if _, exists := existingTxOut[txIn.PreviousOutPoint]; exists { return ruleError(ErrDuplicateTxInputs, "transaction "+ "contains duplicate inputs") } existingTxOut[txIn.PreviousOutPoint] = struct{}{} } // Coinbase script length must be between min and max length. if IsCoinBase(tx) { slen := len(msgTx.TxIn[0].SignatureScript) if slen < MinCoinbaseScriptLen || slen > MaxCoinbaseScriptLen { str := fmt.Sprintf("coinbase transaction script length "+ "of %d is out of range (min: %d, max: %d)", slen, MinCoinbaseScriptLen, MaxCoinbaseScriptLen) return ruleError(ErrBadCoinbaseScriptLen, str) } } else { // Previous transaction outputs referenced by the inputs to this // transaction must not be null. for _, txIn := range msgTx.TxIn { if isNullOutpoint(&txIn.PreviousOutPoint) { return ruleError(ErrBadTxInput, "transaction "+ "input refers to previous output that "+ "is null") } } } return nil }
go
func CheckTransactionSanity(tx *btcutil.Tx) error { // A transaction must have at least one input. msgTx := tx.MsgTx() if len(msgTx.TxIn) == 0 { return ruleError(ErrNoTxInputs, "transaction has no inputs") } // A transaction must have at least one output. if len(msgTx.TxOut) == 0 { return ruleError(ErrNoTxOutputs, "transaction has no outputs") } // A transaction must not exceed the maximum allowed block payload when // serialized. serializedTxSize := tx.MsgTx().SerializeSizeStripped() if serializedTxSize > MaxBlockBaseSize { str := fmt.Sprintf("serialized transaction is too big - got "+ "%d, max %d", serializedTxSize, MaxBlockBaseSize) return ruleError(ErrTxTooBig, str) } // Ensure the transaction amounts are in range. Each transaction // output must not be negative or more than the max allowed per // transaction. Also, the total of all outputs must abide by the same // restrictions. All amounts in a transaction are in a unit value known // as a satoshi. One bitcoin is a quantity of satoshi as defined by the // SatoshiPerBitcoin constant. var totalSatoshi int64 for _, txOut := range msgTx.TxOut { satoshi := txOut.Value if satoshi < 0 { str := fmt.Sprintf("transaction output has negative "+ "value of %v", satoshi) return ruleError(ErrBadTxOutValue, str) } if satoshi > btcutil.MaxSatoshi { str := fmt.Sprintf("transaction output value of %v is "+ "higher than max allowed value of %v", satoshi, btcutil.MaxSatoshi) return ruleError(ErrBadTxOutValue, str) } // Two's complement int64 overflow guarantees that any overflow // is detected and reported. This is impossible for Bitcoin, but // perhaps possible if an alt increases the total money supply. totalSatoshi += satoshi if totalSatoshi < 0 { str := fmt.Sprintf("total value of all transaction "+ "outputs exceeds max allowed value of %v", btcutil.MaxSatoshi) return ruleError(ErrBadTxOutValue, str) } if totalSatoshi > btcutil.MaxSatoshi { str := fmt.Sprintf("total value of all transaction "+ "outputs is %v which is higher than max "+ "allowed value of %v", totalSatoshi, btcutil.MaxSatoshi) return ruleError(ErrBadTxOutValue, str) } } // Check for duplicate transaction inputs. existingTxOut := make(map[wire.OutPoint]struct{}) for _, txIn := range msgTx.TxIn { if _, exists := existingTxOut[txIn.PreviousOutPoint]; exists { return ruleError(ErrDuplicateTxInputs, "transaction "+ "contains duplicate inputs") } existingTxOut[txIn.PreviousOutPoint] = struct{}{} } // Coinbase script length must be between min and max length. if IsCoinBase(tx) { slen := len(msgTx.TxIn[0].SignatureScript) if slen < MinCoinbaseScriptLen || slen > MaxCoinbaseScriptLen { str := fmt.Sprintf("coinbase transaction script length "+ "of %d is out of range (min: %d, max: %d)", slen, MinCoinbaseScriptLen, MaxCoinbaseScriptLen) return ruleError(ErrBadCoinbaseScriptLen, str) } } else { // Previous transaction outputs referenced by the inputs to this // transaction must not be null. for _, txIn := range msgTx.TxIn { if isNullOutpoint(&txIn.PreviousOutPoint) { return ruleError(ErrBadTxInput, "transaction "+ "input refers to previous output that "+ "is null") } } } return nil }
[ "func", "CheckTransactionSanity", "(", "tx", "*", "btcutil", ".", "Tx", ")", "error", "{", "// A transaction must have at least one input.", "msgTx", ":=", "tx", ".", "MsgTx", "(", ")", "\n", "if", "len", "(", "msgTx", ".", "TxIn", ")", "==", "0", "{", "return", "ruleError", "(", "ErrNoTxInputs", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// A transaction must have at least one output.", "if", "len", "(", "msgTx", ".", "TxOut", ")", "==", "0", "{", "return", "ruleError", "(", "ErrNoTxOutputs", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// A transaction must not exceed the maximum allowed block payload when", "// serialized.", "serializedTxSize", ":=", "tx", ".", "MsgTx", "(", ")", ".", "SerializeSizeStripped", "(", ")", "\n", "if", "serializedTxSize", ">", "MaxBlockBaseSize", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "serializedTxSize", ",", "MaxBlockBaseSize", ")", "\n", "return", "ruleError", "(", "ErrTxTooBig", ",", "str", ")", "\n", "}", "\n\n", "// Ensure the transaction amounts are in range. Each transaction", "// output must not be negative or more than the max allowed per", "// transaction. Also, the total of all outputs must abide by the same", "// restrictions. All amounts in a transaction are in a unit value known", "// as a satoshi. One bitcoin is a quantity of satoshi as defined by the", "// SatoshiPerBitcoin constant.", "var", "totalSatoshi", "int64", "\n", "for", "_", ",", "txOut", ":=", "range", "msgTx", ".", "TxOut", "{", "satoshi", ":=", "txOut", ".", "Value", "\n", "if", "satoshi", "<", "0", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "satoshi", ")", "\n", "return", "ruleError", "(", "ErrBadTxOutValue", ",", "str", ")", "\n", "}", "\n", "if", "satoshi", ">", "btcutil", ".", "MaxSatoshi", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "satoshi", ",", "btcutil", ".", "MaxSatoshi", ")", "\n", "return", "ruleError", "(", "ErrBadTxOutValue", ",", "str", ")", "\n", "}", "\n\n", "// Two's complement int64 overflow guarantees that any overflow", "// is detected and reported. This is impossible for Bitcoin, but", "// perhaps possible if an alt increases the total money supply.", "totalSatoshi", "+=", "satoshi", "\n", "if", "totalSatoshi", "<", "0", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "btcutil", ".", "MaxSatoshi", ")", "\n", "return", "ruleError", "(", "ErrBadTxOutValue", ",", "str", ")", "\n", "}", "\n", "if", "totalSatoshi", ">", "btcutil", ".", "MaxSatoshi", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ",", "totalSatoshi", ",", "btcutil", ".", "MaxSatoshi", ")", "\n", "return", "ruleError", "(", "ErrBadTxOutValue", ",", "str", ")", "\n", "}", "\n", "}", "\n\n", "// Check for duplicate transaction inputs.", "existingTxOut", ":=", "make", "(", "map", "[", "wire", ".", "OutPoint", "]", "struct", "{", "}", ")", "\n", "for", "_", ",", "txIn", ":=", "range", "msgTx", ".", "TxIn", "{", "if", "_", ",", "exists", ":=", "existingTxOut", "[", "txIn", ".", "PreviousOutPoint", "]", ";", "exists", "{", "return", "ruleError", "(", "ErrDuplicateTxInputs", ",", "\"", "\"", "+", "\"", "\"", ")", "\n", "}", "\n", "existingTxOut", "[", "txIn", ".", "PreviousOutPoint", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n\n", "// Coinbase script length must be between min and max length.", "if", "IsCoinBase", "(", "tx", ")", "{", "slen", ":=", "len", "(", "msgTx", ".", "TxIn", "[", "0", "]", ".", "SignatureScript", ")", "\n", "if", "slen", "<", "MinCoinbaseScriptLen", "||", "slen", ">", "MaxCoinbaseScriptLen", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "slen", ",", "MinCoinbaseScriptLen", ",", "MaxCoinbaseScriptLen", ")", "\n", "return", "ruleError", "(", "ErrBadCoinbaseScriptLen", ",", "str", ")", "\n", "}", "\n", "}", "else", "{", "// Previous transaction outputs referenced by the inputs to this", "// transaction must not be null.", "for", "_", ",", "txIn", ":=", "range", "msgTx", ".", "TxIn", "{", "if", "isNullOutpoint", "(", "&", "txIn", ".", "PreviousOutPoint", ")", "{", "return", "ruleError", "(", "ErrBadTxInput", ",", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// CheckTransactionSanity performs some preliminary checks on a transaction to // ensure it is sane. These checks are context free.
[ "CheckTransactionSanity", "performs", "some", "preliminary", "checks", "on", "a", "transaction", "to", "ensure", "it", "is", "sane", ".", "These", "checks", "are", "context", "free", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/validate.go#L205-L298
train
btcsuite/btcd
blockchain/validate.go
CountSigOps
func CountSigOps(tx *btcutil.Tx) int { msgTx := tx.MsgTx() // Accumulate the number of signature operations in all transaction // inputs. totalSigOps := 0 for _, txIn := range msgTx.TxIn { numSigOps := txscript.GetSigOpCount(txIn.SignatureScript) totalSigOps += numSigOps } // Accumulate the number of signature operations in all transaction // outputs. for _, txOut := range msgTx.TxOut { numSigOps := txscript.GetSigOpCount(txOut.PkScript) totalSigOps += numSigOps } return totalSigOps }
go
func CountSigOps(tx *btcutil.Tx) int { msgTx := tx.MsgTx() // Accumulate the number of signature operations in all transaction // inputs. totalSigOps := 0 for _, txIn := range msgTx.TxIn { numSigOps := txscript.GetSigOpCount(txIn.SignatureScript) totalSigOps += numSigOps } // Accumulate the number of signature operations in all transaction // outputs. for _, txOut := range msgTx.TxOut { numSigOps := txscript.GetSigOpCount(txOut.PkScript) totalSigOps += numSigOps } return totalSigOps }
[ "func", "CountSigOps", "(", "tx", "*", "btcutil", ".", "Tx", ")", "int", "{", "msgTx", ":=", "tx", ".", "MsgTx", "(", ")", "\n\n", "// Accumulate the number of signature operations in all transaction", "// inputs.", "totalSigOps", ":=", "0", "\n", "for", "_", ",", "txIn", ":=", "range", "msgTx", ".", "TxIn", "{", "numSigOps", ":=", "txscript", ".", "GetSigOpCount", "(", "txIn", ".", "SignatureScript", ")", "\n", "totalSigOps", "+=", "numSigOps", "\n", "}", "\n\n", "// Accumulate the number of signature operations in all transaction", "// outputs.", "for", "_", ",", "txOut", ":=", "range", "msgTx", ".", "TxOut", "{", "numSigOps", ":=", "txscript", ".", "GetSigOpCount", "(", "txOut", ".", "PkScript", ")", "\n", "totalSigOps", "+=", "numSigOps", "\n", "}", "\n\n", "return", "totalSigOps", "\n", "}" ]
// CountSigOps returns the number of signature operations for all transaction // input and output scripts in the provided transaction. This uses the // quicker, but imprecise, signature operation counting mechanism from // txscript.
[ "CountSigOps", "returns", "the", "number", "of", "signature", "operations", "for", "all", "transaction", "input", "and", "output", "scripts", "in", "the", "provided", "transaction", ".", "This", "uses", "the", "quicker", "but", "imprecise", "signature", "operation", "counting", "mechanism", "from", "txscript", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/validate.go#L350-L369
train
btcsuite/btcd
blockchain/validate.go
CountP2SHSigOps
func CountP2SHSigOps(tx *btcutil.Tx, isCoinBaseTx bool, utxoView *UtxoViewpoint) (int, error) { // Coinbase transactions have no interesting inputs. if isCoinBaseTx { return 0, nil } // Accumulate the number of signature operations in all transaction // inputs. msgTx := tx.MsgTx() totalSigOps := 0 for txInIndex, txIn := range msgTx.TxIn { // Ensure the referenced input transaction is available. utxo := utxoView.LookupEntry(txIn.PreviousOutPoint) if utxo == nil || utxo.IsSpent() { str := fmt.Sprintf("output %v referenced from "+ "transaction %s:%d either does not exist or "+ "has already been spent", txIn.PreviousOutPoint, tx.Hash(), txInIndex) return 0, ruleError(ErrMissingTxOut, str) } // We're only interested in pay-to-script-hash types, so skip // this input if it's not one. pkScript := utxo.PkScript() if !txscript.IsPayToScriptHash(pkScript) { continue } // Count the precise number of signature operations in the // referenced public key script. sigScript := txIn.SignatureScript numSigOps := txscript.GetPreciseSigOpCount(sigScript, pkScript, true) // We could potentially overflow the accumulator so check for // overflow. lastSigOps := totalSigOps totalSigOps += numSigOps if totalSigOps < lastSigOps { str := fmt.Sprintf("the public key script from output "+ "%v contains too many signature operations - "+ "overflow", txIn.PreviousOutPoint) return 0, ruleError(ErrTooManySigOps, str) } } return totalSigOps, nil }
go
func CountP2SHSigOps(tx *btcutil.Tx, isCoinBaseTx bool, utxoView *UtxoViewpoint) (int, error) { // Coinbase transactions have no interesting inputs. if isCoinBaseTx { return 0, nil } // Accumulate the number of signature operations in all transaction // inputs. msgTx := tx.MsgTx() totalSigOps := 0 for txInIndex, txIn := range msgTx.TxIn { // Ensure the referenced input transaction is available. utxo := utxoView.LookupEntry(txIn.PreviousOutPoint) if utxo == nil || utxo.IsSpent() { str := fmt.Sprintf("output %v referenced from "+ "transaction %s:%d either does not exist or "+ "has already been spent", txIn.PreviousOutPoint, tx.Hash(), txInIndex) return 0, ruleError(ErrMissingTxOut, str) } // We're only interested in pay-to-script-hash types, so skip // this input if it's not one. pkScript := utxo.PkScript() if !txscript.IsPayToScriptHash(pkScript) { continue } // Count the precise number of signature operations in the // referenced public key script. sigScript := txIn.SignatureScript numSigOps := txscript.GetPreciseSigOpCount(sigScript, pkScript, true) // We could potentially overflow the accumulator so check for // overflow. lastSigOps := totalSigOps totalSigOps += numSigOps if totalSigOps < lastSigOps { str := fmt.Sprintf("the public key script from output "+ "%v contains too many signature operations - "+ "overflow", txIn.PreviousOutPoint) return 0, ruleError(ErrTooManySigOps, str) } } return totalSigOps, nil }
[ "func", "CountP2SHSigOps", "(", "tx", "*", "btcutil", ".", "Tx", ",", "isCoinBaseTx", "bool", ",", "utxoView", "*", "UtxoViewpoint", ")", "(", "int", ",", "error", ")", "{", "// Coinbase transactions have no interesting inputs.", "if", "isCoinBaseTx", "{", "return", "0", ",", "nil", "\n", "}", "\n\n", "// Accumulate the number of signature operations in all transaction", "// inputs.", "msgTx", ":=", "tx", ".", "MsgTx", "(", ")", "\n", "totalSigOps", ":=", "0", "\n", "for", "txInIndex", ",", "txIn", ":=", "range", "msgTx", ".", "TxIn", "{", "// Ensure the referenced input transaction is available.", "utxo", ":=", "utxoView", ".", "LookupEntry", "(", "txIn", ".", "PreviousOutPoint", ")", "\n", "if", "utxo", "==", "nil", "||", "utxo", ".", "IsSpent", "(", ")", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ",", "txIn", ".", "PreviousOutPoint", ",", "tx", ".", "Hash", "(", ")", ",", "txInIndex", ")", "\n", "return", "0", ",", "ruleError", "(", "ErrMissingTxOut", ",", "str", ")", "\n", "}", "\n\n", "// We're only interested in pay-to-script-hash types, so skip", "// this input if it's not one.", "pkScript", ":=", "utxo", ".", "PkScript", "(", ")", "\n", "if", "!", "txscript", ".", "IsPayToScriptHash", "(", "pkScript", ")", "{", "continue", "\n", "}", "\n\n", "// Count the precise number of signature operations in the", "// referenced public key script.", "sigScript", ":=", "txIn", ".", "SignatureScript", "\n", "numSigOps", ":=", "txscript", ".", "GetPreciseSigOpCount", "(", "sigScript", ",", "pkScript", ",", "true", ")", "\n\n", "// We could potentially overflow the accumulator so check for", "// overflow.", "lastSigOps", ":=", "totalSigOps", "\n", "totalSigOps", "+=", "numSigOps", "\n", "if", "totalSigOps", "<", "lastSigOps", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ",", "txIn", ".", "PreviousOutPoint", ")", "\n", "return", "0", ",", "ruleError", "(", "ErrTooManySigOps", ",", "str", ")", "\n", "}", "\n", "}", "\n\n", "return", "totalSigOps", ",", "nil", "\n", "}" ]
// CountP2SHSigOps returns the number of signature operations for all input // transactions which are of the pay-to-script-hash type. This uses the // precise, signature operation counting mechanism from the script engine which // requires access to the input transaction scripts.
[ "CountP2SHSigOps", "returns", "the", "number", "of", "signature", "operations", "for", "all", "input", "transactions", "which", "are", "of", "the", "pay", "-", "to", "-", "script", "-", "hash", "type", ".", "This", "uses", "the", "precise", "signature", "operation", "counting", "mechanism", "from", "the", "script", "engine", "which", "requires", "access", "to", "the", "input", "transaction", "scripts", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/validate.go#L375-L422
train
btcsuite/btcd
blockchain/validate.go
checkBlockHeaderSanity
func checkBlockHeaderSanity(header *wire.BlockHeader, powLimit *big.Int, timeSource MedianTimeSource, flags BehaviorFlags) error { // Ensure the proof of work bits in the block header is in min/max range // and the block hash is less than the target value described by the // bits. err := checkProofOfWork(header, powLimit, flags) if err != nil { return err } // A block timestamp must not have a greater precision than one second. // This check is necessary because Go time.Time values support // nanosecond precision whereas the consensus rules only apply to // seconds and it's much nicer to deal with standard Go time values // instead of converting to seconds everywhere. if !header.Timestamp.Equal(time.Unix(header.Timestamp.Unix(), 0)) { str := fmt.Sprintf("block timestamp of %v has a higher "+ "precision than one second", header.Timestamp) return ruleError(ErrInvalidTime, str) } // Ensure the block time is not too far in the future. maxTimestamp := timeSource.AdjustedTime().Add(time.Second * MaxTimeOffsetSeconds) if header.Timestamp.After(maxTimestamp) { str := fmt.Sprintf("block timestamp of %v is too far in the "+ "future", header.Timestamp) return ruleError(ErrTimeTooNew, str) } return nil }
go
func checkBlockHeaderSanity(header *wire.BlockHeader, powLimit *big.Int, timeSource MedianTimeSource, flags BehaviorFlags) error { // Ensure the proof of work bits in the block header is in min/max range // and the block hash is less than the target value described by the // bits. err := checkProofOfWork(header, powLimit, flags) if err != nil { return err } // A block timestamp must not have a greater precision than one second. // This check is necessary because Go time.Time values support // nanosecond precision whereas the consensus rules only apply to // seconds and it's much nicer to deal with standard Go time values // instead of converting to seconds everywhere. if !header.Timestamp.Equal(time.Unix(header.Timestamp.Unix(), 0)) { str := fmt.Sprintf("block timestamp of %v has a higher "+ "precision than one second", header.Timestamp) return ruleError(ErrInvalidTime, str) } // Ensure the block time is not too far in the future. maxTimestamp := timeSource.AdjustedTime().Add(time.Second * MaxTimeOffsetSeconds) if header.Timestamp.After(maxTimestamp) { str := fmt.Sprintf("block timestamp of %v is too far in the "+ "future", header.Timestamp) return ruleError(ErrTimeTooNew, str) } return nil }
[ "func", "checkBlockHeaderSanity", "(", "header", "*", "wire", ".", "BlockHeader", ",", "powLimit", "*", "big", ".", "Int", ",", "timeSource", "MedianTimeSource", ",", "flags", "BehaviorFlags", ")", "error", "{", "// Ensure the proof of work bits in the block header is in min/max range", "// and the block hash is less than the target value described by the", "// bits.", "err", ":=", "checkProofOfWork", "(", "header", ",", "powLimit", ",", "flags", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// A block timestamp must not have a greater precision than one second.", "// This check is necessary because Go time.Time values support", "// nanosecond precision whereas the consensus rules only apply to", "// seconds and it's much nicer to deal with standard Go time values", "// instead of converting to seconds everywhere.", "if", "!", "header", ".", "Timestamp", ".", "Equal", "(", "time", ".", "Unix", "(", "header", ".", "Timestamp", ".", "Unix", "(", ")", ",", "0", ")", ")", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "header", ".", "Timestamp", ")", "\n", "return", "ruleError", "(", "ErrInvalidTime", ",", "str", ")", "\n", "}", "\n\n", "// Ensure the block time is not too far in the future.", "maxTimestamp", ":=", "timeSource", ".", "AdjustedTime", "(", ")", ".", "Add", "(", "time", ".", "Second", "*", "MaxTimeOffsetSeconds", ")", "\n", "if", "header", ".", "Timestamp", ".", "After", "(", "maxTimestamp", ")", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "header", ".", "Timestamp", ")", "\n", "return", "ruleError", "(", "ErrTimeTooNew", ",", "str", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// checkBlockHeaderSanity performs some preliminary checks on a block header to // ensure it is sane before continuing with processing. These checks are // context free. // // The flags do not modify the behavior of this function directly, however they // are needed to pass along to checkProofOfWork.
[ "checkBlockHeaderSanity", "performs", "some", "preliminary", "checks", "on", "a", "block", "header", "to", "ensure", "it", "is", "sane", "before", "continuing", "with", "processing", ".", "These", "checks", "are", "context", "free", ".", "The", "flags", "do", "not", "modify", "the", "behavior", "of", "this", "function", "directly", "however", "they", "are", "needed", "to", "pass", "along", "to", "checkProofOfWork", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/validate.go#L430-L460
train
btcsuite/btcd
blockchain/validate.go
checkBlockSanity
func checkBlockSanity(block *btcutil.Block, powLimit *big.Int, timeSource MedianTimeSource, flags BehaviorFlags) error { msgBlock := block.MsgBlock() header := &msgBlock.Header err := checkBlockHeaderSanity(header, powLimit, timeSource, flags) if err != nil { return err } // A block must have at least one transaction. numTx := len(msgBlock.Transactions) if numTx == 0 { return ruleError(ErrNoTransactions, "block does not contain "+ "any transactions") } // A block must not have more transactions than the max block payload or // else it is certainly over the weight limit. if numTx > MaxBlockBaseSize { str := fmt.Sprintf("block contains too many transactions - "+ "got %d, max %d", numTx, MaxBlockBaseSize) return ruleError(ErrBlockTooBig, str) } // A block must not exceed the maximum allowed block payload when // serialized. serializedSize := msgBlock.SerializeSizeStripped() if serializedSize > MaxBlockBaseSize { str := fmt.Sprintf("serialized block is too big - got %d, "+ "max %d", serializedSize, MaxBlockBaseSize) return ruleError(ErrBlockTooBig, str) } // The first transaction in a block must be a coinbase. transactions := block.Transactions() if !IsCoinBase(transactions[0]) { return ruleError(ErrFirstTxNotCoinbase, "first transaction in "+ "block is not a coinbase") } // A block must not have more than one coinbase. for i, tx := range transactions[1:] { if IsCoinBase(tx) { str := fmt.Sprintf("block contains second coinbase at "+ "index %d", i+1) return ruleError(ErrMultipleCoinbases, str) } } // Do some preliminary checks on each transaction to ensure they are // sane before continuing. for _, tx := range transactions { err := CheckTransactionSanity(tx) if err != nil { return err } } // Build merkle tree and ensure the calculated merkle root matches the // entry in the block header. This also has the effect of caching all // of the transaction hashes in the block to speed up future hash // checks. Bitcoind builds the tree here and checks the merkle root // after the following checks, but there is no reason not to check the // merkle root matches here. merkles := BuildMerkleTreeStore(block.Transactions(), false) calculatedMerkleRoot := merkles[len(merkles)-1] if !header.MerkleRoot.IsEqual(calculatedMerkleRoot) { str := fmt.Sprintf("block merkle root is invalid - block "+ "header indicates %v, but calculated value is %v", header.MerkleRoot, calculatedMerkleRoot) return ruleError(ErrBadMerkleRoot, str) } // Check for duplicate transactions. This check will be fairly quick // since the transaction hashes are already cached due to building the // merkle tree above. existingTxHashes := make(map[chainhash.Hash]struct{}) for _, tx := range transactions { hash := tx.Hash() if _, exists := existingTxHashes[*hash]; exists { str := fmt.Sprintf("block contains duplicate "+ "transaction %v", hash) return ruleError(ErrDuplicateTx, str) } existingTxHashes[*hash] = struct{}{} } // The number of signature operations must be less than the maximum // allowed per block. totalSigOps := 0 for _, tx := range transactions { // We could potentially overflow the accumulator so check for // overflow. lastSigOps := totalSigOps totalSigOps += (CountSigOps(tx) * WitnessScaleFactor) if totalSigOps < lastSigOps || totalSigOps > MaxBlockSigOpsCost { str := fmt.Sprintf("block contains too many signature "+ "operations - got %v, max %v", totalSigOps, MaxBlockSigOpsCost) return ruleError(ErrTooManySigOps, str) } } return nil }
go
func checkBlockSanity(block *btcutil.Block, powLimit *big.Int, timeSource MedianTimeSource, flags BehaviorFlags) error { msgBlock := block.MsgBlock() header := &msgBlock.Header err := checkBlockHeaderSanity(header, powLimit, timeSource, flags) if err != nil { return err } // A block must have at least one transaction. numTx := len(msgBlock.Transactions) if numTx == 0 { return ruleError(ErrNoTransactions, "block does not contain "+ "any transactions") } // A block must not have more transactions than the max block payload or // else it is certainly over the weight limit. if numTx > MaxBlockBaseSize { str := fmt.Sprintf("block contains too many transactions - "+ "got %d, max %d", numTx, MaxBlockBaseSize) return ruleError(ErrBlockTooBig, str) } // A block must not exceed the maximum allowed block payload when // serialized. serializedSize := msgBlock.SerializeSizeStripped() if serializedSize > MaxBlockBaseSize { str := fmt.Sprintf("serialized block is too big - got %d, "+ "max %d", serializedSize, MaxBlockBaseSize) return ruleError(ErrBlockTooBig, str) } // The first transaction in a block must be a coinbase. transactions := block.Transactions() if !IsCoinBase(transactions[0]) { return ruleError(ErrFirstTxNotCoinbase, "first transaction in "+ "block is not a coinbase") } // A block must not have more than one coinbase. for i, tx := range transactions[1:] { if IsCoinBase(tx) { str := fmt.Sprintf("block contains second coinbase at "+ "index %d", i+1) return ruleError(ErrMultipleCoinbases, str) } } // Do some preliminary checks on each transaction to ensure they are // sane before continuing. for _, tx := range transactions { err := CheckTransactionSanity(tx) if err != nil { return err } } // Build merkle tree and ensure the calculated merkle root matches the // entry in the block header. This also has the effect of caching all // of the transaction hashes in the block to speed up future hash // checks. Bitcoind builds the tree here and checks the merkle root // after the following checks, but there is no reason not to check the // merkle root matches here. merkles := BuildMerkleTreeStore(block.Transactions(), false) calculatedMerkleRoot := merkles[len(merkles)-1] if !header.MerkleRoot.IsEqual(calculatedMerkleRoot) { str := fmt.Sprintf("block merkle root is invalid - block "+ "header indicates %v, but calculated value is %v", header.MerkleRoot, calculatedMerkleRoot) return ruleError(ErrBadMerkleRoot, str) } // Check for duplicate transactions. This check will be fairly quick // since the transaction hashes are already cached due to building the // merkle tree above. existingTxHashes := make(map[chainhash.Hash]struct{}) for _, tx := range transactions { hash := tx.Hash() if _, exists := existingTxHashes[*hash]; exists { str := fmt.Sprintf("block contains duplicate "+ "transaction %v", hash) return ruleError(ErrDuplicateTx, str) } existingTxHashes[*hash] = struct{}{} } // The number of signature operations must be less than the maximum // allowed per block. totalSigOps := 0 for _, tx := range transactions { // We could potentially overflow the accumulator so check for // overflow. lastSigOps := totalSigOps totalSigOps += (CountSigOps(tx) * WitnessScaleFactor) if totalSigOps < lastSigOps || totalSigOps > MaxBlockSigOpsCost { str := fmt.Sprintf("block contains too many signature "+ "operations - got %v, max %v", totalSigOps, MaxBlockSigOpsCost) return ruleError(ErrTooManySigOps, str) } } return nil }
[ "func", "checkBlockSanity", "(", "block", "*", "btcutil", ".", "Block", ",", "powLimit", "*", "big", ".", "Int", ",", "timeSource", "MedianTimeSource", ",", "flags", "BehaviorFlags", ")", "error", "{", "msgBlock", ":=", "block", ".", "MsgBlock", "(", ")", "\n", "header", ":=", "&", "msgBlock", ".", "Header", "\n", "err", ":=", "checkBlockHeaderSanity", "(", "header", ",", "powLimit", ",", "timeSource", ",", "flags", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// A block must have at least one transaction.", "numTx", ":=", "len", "(", "msgBlock", ".", "Transactions", ")", "\n", "if", "numTx", "==", "0", "{", "return", "ruleError", "(", "ErrNoTransactions", ",", "\"", "\"", "+", "\"", "\"", ")", "\n", "}", "\n\n", "// A block must not have more transactions than the max block payload or", "// else it is certainly over the weight limit.", "if", "numTx", ">", "MaxBlockBaseSize", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "numTx", ",", "MaxBlockBaseSize", ")", "\n", "return", "ruleError", "(", "ErrBlockTooBig", ",", "str", ")", "\n", "}", "\n\n", "// A block must not exceed the maximum allowed block payload when", "// serialized.", "serializedSize", ":=", "msgBlock", ".", "SerializeSizeStripped", "(", ")", "\n", "if", "serializedSize", ">", "MaxBlockBaseSize", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "serializedSize", ",", "MaxBlockBaseSize", ")", "\n", "return", "ruleError", "(", "ErrBlockTooBig", ",", "str", ")", "\n", "}", "\n\n", "// The first transaction in a block must be a coinbase.", "transactions", ":=", "block", ".", "Transactions", "(", ")", "\n", "if", "!", "IsCoinBase", "(", "transactions", "[", "0", "]", ")", "{", "return", "ruleError", "(", "ErrFirstTxNotCoinbase", ",", "\"", "\"", "+", "\"", "\"", ")", "\n", "}", "\n\n", "// A block must not have more than one coinbase.", "for", "i", ",", "tx", ":=", "range", "transactions", "[", "1", ":", "]", "{", "if", "IsCoinBase", "(", "tx", ")", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "i", "+", "1", ")", "\n", "return", "ruleError", "(", "ErrMultipleCoinbases", ",", "str", ")", "\n", "}", "\n", "}", "\n\n", "// Do some preliminary checks on each transaction to ensure they are", "// sane before continuing.", "for", "_", ",", "tx", ":=", "range", "transactions", "{", "err", ":=", "CheckTransactionSanity", "(", "tx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "// Build merkle tree and ensure the calculated merkle root matches the", "// entry in the block header. This also has the effect of caching all", "// of the transaction hashes in the block to speed up future hash", "// checks. Bitcoind builds the tree here and checks the merkle root", "// after the following checks, but there is no reason not to check the", "// merkle root matches here.", "merkles", ":=", "BuildMerkleTreeStore", "(", "block", ".", "Transactions", "(", ")", ",", "false", ")", "\n", "calculatedMerkleRoot", ":=", "merkles", "[", "len", "(", "merkles", ")", "-", "1", "]", "\n", "if", "!", "header", ".", "MerkleRoot", ".", "IsEqual", "(", "calculatedMerkleRoot", ")", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "header", ".", "MerkleRoot", ",", "calculatedMerkleRoot", ")", "\n", "return", "ruleError", "(", "ErrBadMerkleRoot", ",", "str", ")", "\n", "}", "\n\n", "// Check for duplicate transactions. This check will be fairly quick", "// since the transaction hashes are already cached due to building the", "// merkle tree above.", "existingTxHashes", ":=", "make", "(", "map", "[", "chainhash", ".", "Hash", "]", "struct", "{", "}", ")", "\n", "for", "_", ",", "tx", ":=", "range", "transactions", "{", "hash", ":=", "tx", ".", "Hash", "(", ")", "\n", "if", "_", ",", "exists", ":=", "existingTxHashes", "[", "*", "hash", "]", ";", "exists", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "hash", ")", "\n", "return", "ruleError", "(", "ErrDuplicateTx", ",", "str", ")", "\n", "}", "\n", "existingTxHashes", "[", "*", "hash", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n\n", "// The number of signature operations must be less than the maximum", "// allowed per block.", "totalSigOps", ":=", "0", "\n", "for", "_", ",", "tx", ":=", "range", "transactions", "{", "// We could potentially overflow the accumulator so check for", "// overflow.", "lastSigOps", ":=", "totalSigOps", "\n", "totalSigOps", "+=", "(", "CountSigOps", "(", "tx", ")", "*", "WitnessScaleFactor", ")", "\n", "if", "totalSigOps", "<", "lastSigOps", "||", "totalSigOps", ">", "MaxBlockSigOpsCost", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "totalSigOps", ",", "MaxBlockSigOpsCost", ")", "\n", "return", "ruleError", "(", "ErrTooManySigOps", ",", "str", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// checkBlockSanity performs some preliminary checks on a block to ensure it is // sane before continuing with block processing. These checks are context free. // // The flags do not modify the behavior of this function directly, however they // are needed to pass along to checkBlockHeaderSanity.
[ "checkBlockSanity", "performs", "some", "preliminary", "checks", "on", "a", "block", "to", "ensure", "it", "is", "sane", "before", "continuing", "with", "block", "processing", ".", "These", "checks", "are", "context", "free", ".", "The", "flags", "do", "not", "modify", "the", "behavior", "of", "this", "function", "directly", "however", "they", "are", "needed", "to", "pass", "along", "to", "checkBlockHeaderSanity", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/validate.go#L467-L570
train
btcsuite/btcd
blockchain/validate.go
CheckBlockSanity
func CheckBlockSanity(block *btcutil.Block, powLimit *big.Int, timeSource MedianTimeSource) error { return checkBlockSanity(block, powLimit, timeSource, BFNone) }
go
func CheckBlockSanity(block *btcutil.Block, powLimit *big.Int, timeSource MedianTimeSource) error { return checkBlockSanity(block, powLimit, timeSource, BFNone) }
[ "func", "CheckBlockSanity", "(", "block", "*", "btcutil", ".", "Block", ",", "powLimit", "*", "big", ".", "Int", ",", "timeSource", "MedianTimeSource", ")", "error", "{", "return", "checkBlockSanity", "(", "block", ",", "powLimit", ",", "timeSource", ",", "BFNone", ")", "\n", "}" ]
// CheckBlockSanity performs some preliminary checks on a block to ensure it is // sane before continuing with block processing. These checks are context free.
[ "CheckBlockSanity", "performs", "some", "preliminary", "checks", "on", "a", "block", "to", "ensure", "it", "is", "sane", "before", "continuing", "with", "block", "processing", ".", "These", "checks", "are", "context", "free", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/validate.go#L574-L576
train
btcsuite/btcd
blockchain/validate.go
ExtractCoinbaseHeight
func ExtractCoinbaseHeight(coinbaseTx *btcutil.Tx) (int32, error) { sigScript := coinbaseTx.MsgTx().TxIn[0].SignatureScript if len(sigScript) < 1 { str := "the coinbase signature script for blocks of " + "version %d or greater must start with the " + "length of the serialized block height" str = fmt.Sprintf(str, serializedHeightVersion) return 0, ruleError(ErrMissingCoinbaseHeight, str) } // Detect the case when the block height is a small integer encoded with // as single byte. opcode := int(sigScript[0]) if opcode == txscript.OP_0 { return 0, nil } if opcode >= txscript.OP_1 && opcode <= txscript.OP_16 { return int32(opcode - (txscript.OP_1 - 1)), nil } // Otherwise, the opcode is the length of the following bytes which // encode in the block height. serializedLen := int(sigScript[0]) if len(sigScript[1:]) < serializedLen { str := "the coinbase signature script for blocks of " + "version %d or greater must start with the " + "serialized block height" str = fmt.Sprintf(str, serializedLen) return 0, ruleError(ErrMissingCoinbaseHeight, str) } serializedHeightBytes := make([]byte, 8) copy(serializedHeightBytes, sigScript[1:serializedLen+1]) serializedHeight := binary.LittleEndian.Uint64(serializedHeightBytes) return int32(serializedHeight), nil }
go
func ExtractCoinbaseHeight(coinbaseTx *btcutil.Tx) (int32, error) { sigScript := coinbaseTx.MsgTx().TxIn[0].SignatureScript if len(sigScript) < 1 { str := "the coinbase signature script for blocks of " + "version %d or greater must start with the " + "length of the serialized block height" str = fmt.Sprintf(str, serializedHeightVersion) return 0, ruleError(ErrMissingCoinbaseHeight, str) } // Detect the case when the block height is a small integer encoded with // as single byte. opcode := int(sigScript[0]) if opcode == txscript.OP_0 { return 0, nil } if opcode >= txscript.OP_1 && opcode <= txscript.OP_16 { return int32(opcode - (txscript.OP_1 - 1)), nil } // Otherwise, the opcode is the length of the following bytes which // encode in the block height. serializedLen := int(sigScript[0]) if len(sigScript[1:]) < serializedLen { str := "the coinbase signature script for blocks of " + "version %d or greater must start with the " + "serialized block height" str = fmt.Sprintf(str, serializedLen) return 0, ruleError(ErrMissingCoinbaseHeight, str) } serializedHeightBytes := make([]byte, 8) copy(serializedHeightBytes, sigScript[1:serializedLen+1]) serializedHeight := binary.LittleEndian.Uint64(serializedHeightBytes) return int32(serializedHeight), nil }
[ "func", "ExtractCoinbaseHeight", "(", "coinbaseTx", "*", "btcutil", ".", "Tx", ")", "(", "int32", ",", "error", ")", "{", "sigScript", ":=", "coinbaseTx", ".", "MsgTx", "(", ")", ".", "TxIn", "[", "0", "]", ".", "SignatureScript", "\n", "if", "len", "(", "sigScript", ")", "<", "1", "{", "str", ":=", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", "\n", "str", "=", "fmt", ".", "Sprintf", "(", "str", ",", "serializedHeightVersion", ")", "\n", "return", "0", ",", "ruleError", "(", "ErrMissingCoinbaseHeight", ",", "str", ")", "\n", "}", "\n\n", "// Detect the case when the block height is a small integer encoded with", "// as single byte.", "opcode", ":=", "int", "(", "sigScript", "[", "0", "]", ")", "\n", "if", "opcode", "==", "txscript", ".", "OP_0", "{", "return", "0", ",", "nil", "\n", "}", "\n", "if", "opcode", ">=", "txscript", ".", "OP_1", "&&", "opcode", "<=", "txscript", ".", "OP_16", "{", "return", "int32", "(", "opcode", "-", "(", "txscript", ".", "OP_1", "-", "1", ")", ")", ",", "nil", "\n", "}", "\n\n", "// Otherwise, the opcode is the length of the following bytes which", "// encode in the block height.", "serializedLen", ":=", "int", "(", "sigScript", "[", "0", "]", ")", "\n", "if", "len", "(", "sigScript", "[", "1", ":", "]", ")", "<", "serializedLen", "{", "str", ":=", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", "\n", "str", "=", "fmt", ".", "Sprintf", "(", "str", ",", "serializedLen", ")", "\n", "return", "0", ",", "ruleError", "(", "ErrMissingCoinbaseHeight", ",", "str", ")", "\n", "}", "\n\n", "serializedHeightBytes", ":=", "make", "(", "[", "]", "byte", ",", "8", ")", "\n", "copy", "(", "serializedHeightBytes", ",", "sigScript", "[", "1", ":", "serializedLen", "+", "1", "]", ")", "\n", "serializedHeight", ":=", "binary", ".", "LittleEndian", ".", "Uint64", "(", "serializedHeightBytes", ")", "\n\n", "return", "int32", "(", "serializedHeight", ")", ",", "nil", "\n", "}" ]
// ExtractCoinbaseHeight attempts to extract the height of the block from the // scriptSig of a coinbase transaction. Coinbase heights are only present in // blocks of version 2 or later. This was added as part of BIP0034.
[ "ExtractCoinbaseHeight", "attempts", "to", "extract", "the", "height", "of", "the", "block", "from", "the", "scriptSig", "of", "a", "coinbase", "transaction", ".", "Coinbase", "heights", "are", "only", "present", "in", "blocks", "of", "version", "2", "or", "later", ".", "This", "was", "added", "as", "part", "of", "BIP0034", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/validate.go#L581-L617
train
btcsuite/btcd
blockchain/validate.go
checkSerializedHeight
func checkSerializedHeight(coinbaseTx *btcutil.Tx, wantHeight int32) error { serializedHeight, err := ExtractCoinbaseHeight(coinbaseTx) if err != nil { return err } if serializedHeight != wantHeight { str := fmt.Sprintf("the coinbase signature script serialized "+ "block height is %d when %d was expected", serializedHeight, wantHeight) return ruleError(ErrBadCoinbaseHeight, str) } return nil }
go
func checkSerializedHeight(coinbaseTx *btcutil.Tx, wantHeight int32) error { serializedHeight, err := ExtractCoinbaseHeight(coinbaseTx) if err != nil { return err } if serializedHeight != wantHeight { str := fmt.Sprintf("the coinbase signature script serialized "+ "block height is %d when %d was expected", serializedHeight, wantHeight) return ruleError(ErrBadCoinbaseHeight, str) } return nil }
[ "func", "checkSerializedHeight", "(", "coinbaseTx", "*", "btcutil", ".", "Tx", ",", "wantHeight", "int32", ")", "error", "{", "serializedHeight", ",", "err", ":=", "ExtractCoinbaseHeight", "(", "coinbaseTx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "serializedHeight", "!=", "wantHeight", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "serializedHeight", ",", "wantHeight", ")", "\n", "return", "ruleError", "(", "ErrBadCoinbaseHeight", ",", "str", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// checkSerializedHeight checks if the signature script in the passed // transaction starts with the serialized block height of wantHeight.
[ "checkSerializedHeight", "checks", "if", "the", "signature", "script", "in", "the", "passed", "transaction", "starts", "with", "the", "serialized", "block", "height", "of", "wantHeight", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/validate.go#L621-L634
train
btcsuite/btcd
blockchain/validate.go
CheckConnectBlockTemplate
func (b *BlockChain) CheckConnectBlockTemplate(block *btcutil.Block) error { b.chainLock.Lock() defer b.chainLock.Unlock() // Skip the proof of work check as this is just a block template. flags := BFNoPoWCheck // This only checks whether the block can be connected to the tip of the // current chain. tip := b.bestChain.Tip() header := block.MsgBlock().Header if tip.hash != header.PrevBlock { str := fmt.Sprintf("previous block must be the current chain tip %v, "+ "instead got %v", tip.hash, header.PrevBlock) return ruleError(ErrPrevBlockNotBest, str) } err := checkBlockSanity(block, b.chainParams.PowLimit, b.timeSource, flags) if err != nil { return err } err = b.checkBlockContext(block, tip, flags) if err != nil { return err } // Leave the spent txouts entry nil in the state since the information // is not needed and thus extra work can be avoided. view := NewUtxoViewpoint() view.SetBestHash(&tip.hash) newNode := newBlockNode(&header, tip) return b.checkConnectBlock(newNode, block, view, nil) }
go
func (b *BlockChain) CheckConnectBlockTemplate(block *btcutil.Block) error { b.chainLock.Lock() defer b.chainLock.Unlock() // Skip the proof of work check as this is just a block template. flags := BFNoPoWCheck // This only checks whether the block can be connected to the tip of the // current chain. tip := b.bestChain.Tip() header := block.MsgBlock().Header if tip.hash != header.PrevBlock { str := fmt.Sprintf("previous block must be the current chain tip %v, "+ "instead got %v", tip.hash, header.PrevBlock) return ruleError(ErrPrevBlockNotBest, str) } err := checkBlockSanity(block, b.chainParams.PowLimit, b.timeSource, flags) if err != nil { return err } err = b.checkBlockContext(block, tip, flags) if err != nil { return err } // Leave the spent txouts entry nil in the state since the information // is not needed and thus extra work can be avoided. view := NewUtxoViewpoint() view.SetBestHash(&tip.hash) newNode := newBlockNode(&header, tip) return b.checkConnectBlock(newNode, block, view, nil) }
[ "func", "(", "b", "*", "BlockChain", ")", "CheckConnectBlockTemplate", "(", "block", "*", "btcutil", ".", "Block", ")", "error", "{", "b", ".", "chainLock", ".", "Lock", "(", ")", "\n", "defer", "b", ".", "chainLock", ".", "Unlock", "(", ")", "\n\n", "// Skip the proof of work check as this is just a block template.", "flags", ":=", "BFNoPoWCheck", "\n\n", "// This only checks whether the block can be connected to the tip of the", "// current chain.", "tip", ":=", "b", ".", "bestChain", ".", "Tip", "(", ")", "\n", "header", ":=", "block", ".", "MsgBlock", "(", ")", ".", "Header", "\n", "if", "tip", ".", "hash", "!=", "header", ".", "PrevBlock", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "tip", ".", "hash", ",", "header", ".", "PrevBlock", ")", "\n", "return", "ruleError", "(", "ErrPrevBlockNotBest", ",", "str", ")", "\n", "}", "\n\n", "err", ":=", "checkBlockSanity", "(", "block", ",", "b", ".", "chainParams", ".", "PowLimit", ",", "b", ".", "timeSource", ",", "flags", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "err", "=", "b", ".", "checkBlockContext", "(", "block", ",", "tip", ",", "flags", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Leave the spent txouts entry nil in the state since the information", "// is not needed and thus extra work can be avoided.", "view", ":=", "NewUtxoViewpoint", "(", ")", "\n", "view", ".", "SetBestHash", "(", "&", "tip", ".", "hash", ")", "\n", "newNode", ":=", "newBlockNode", "(", "&", "header", ",", "tip", ")", "\n", "return", "b", ".", "checkConnectBlock", "(", "newNode", ",", "block", ",", "view", ",", "nil", ")", "\n", "}" ]
// CheckConnectBlockTemplate fully validates that connecting the passed block to // the main chain does not violate any consensus rules, aside from the proof of // work requirement. The block must connect to the current tip of the main chain. // // This function is safe for concurrent access.
[ "CheckConnectBlockTemplate", "fully", "validates", "that", "connecting", "the", "passed", "block", "to", "the", "main", "chain", "does", "not", "violate", "any", "consensus", "rules", "aside", "from", "the", "proof", "of", "work", "requirement", ".", "The", "block", "must", "connect", "to", "the", "current", "tip", "of", "the", "main", "chain", ".", "This", "function", "is", "safe", "for", "concurrent", "access", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/blockchain/validate.go#L1246-L1279
train
btcsuite/btcd
txscript/error.go
scriptError
func scriptError(c ErrorCode, desc string) Error { return Error{ErrorCode: c, Description: desc} }
go
func scriptError(c ErrorCode, desc string) Error { return Error{ErrorCode: c, Description: desc} }
[ "func", "scriptError", "(", "c", "ErrorCode", ",", "desc", "string", ")", "Error", "{", "return", "Error", "{", "ErrorCode", ":", "c", ",", "Description", ":", "desc", "}", "\n", "}" ]
// scriptError creates an Error given a set of arguments.
[ "scriptError", "creates", "an", "Error", "given", "a", "set", "of", "arguments", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/error.go#L444-L446
train
btcsuite/btcd
txscript/error.go
IsErrorCode
func IsErrorCode(err error, c ErrorCode) bool { serr, ok := err.(Error) return ok && serr.ErrorCode == c }
go
func IsErrorCode(err error, c ErrorCode) bool { serr, ok := err.(Error) return ok && serr.ErrorCode == c }
[ "func", "IsErrorCode", "(", "err", "error", ",", "c", "ErrorCode", ")", "bool", "{", "serr", ",", "ok", ":=", "err", ".", "(", "Error", ")", "\n", "return", "ok", "&&", "serr", ".", "ErrorCode", "==", "c", "\n", "}" ]
// IsErrorCode returns whether or not the provided error is a script error with // the provided error code.
[ "IsErrorCode", "returns", "whether", "or", "not", "the", "provided", "error", "is", "a", "script", "error", "with", "the", "provided", "error", "code", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/error.go#L450-L453
train
btcsuite/btcd
txscript/standard.go
String
func (t ScriptClass) String() string { if int(t) > len(scriptClassToName) || int(t) < 0 { return "Invalid" } return scriptClassToName[t] }
go
func (t ScriptClass) String() string { if int(t) > len(scriptClassToName) || int(t) < 0 { return "Invalid" } return scriptClassToName[t] }
[ "func", "(", "t", "ScriptClass", ")", "String", "(", ")", "string", "{", "if", "int", "(", "t", ")", ">", "len", "(", "scriptClassToName", ")", "||", "int", "(", "t", ")", "<", "0", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "scriptClassToName", "[", "t", "]", "\n", "}" ]
// String implements the Stringer interface by returning the name of // the enum script class. If the enum is invalid then "Invalid" will be // returned.
[ "String", "implements", "the", "Stringer", "interface", "by", "returning", "the", "name", "of", "the", "enum", "script", "class", ".", "If", "the", "enum", "is", "invalid", "then", "Invalid", "will", "be", "returned", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/standard.go#L79-L84
train
btcsuite/btcd
txscript/standard.go
isPubkey
func isPubkey(pops []parsedOpcode) bool { // Valid pubkeys are either 33 or 65 bytes. return len(pops) == 2 && (len(pops[0].data) == 33 || len(pops[0].data) == 65) && pops[1].opcode.value == OP_CHECKSIG }
go
func isPubkey(pops []parsedOpcode) bool { // Valid pubkeys are either 33 or 65 bytes. return len(pops) == 2 && (len(pops[0].data) == 33 || len(pops[0].data) == 65) && pops[1].opcode.value == OP_CHECKSIG }
[ "func", "isPubkey", "(", "pops", "[", "]", "parsedOpcode", ")", "bool", "{", "// Valid pubkeys are either 33 or 65 bytes.", "return", "len", "(", "pops", ")", "==", "2", "&&", "(", "len", "(", "pops", "[", "0", "]", ".", "data", ")", "==", "33", "||", "len", "(", "pops", "[", "0", "]", ".", "data", ")", "==", "65", ")", "&&", "pops", "[", "1", "]", ".", "opcode", ".", "value", "==", "OP_CHECKSIG", "\n", "}" ]
// isPubkey returns true if the script passed is a pay-to-pubkey transaction, // false otherwise.
[ "isPubkey", "returns", "true", "if", "the", "script", "passed", "is", "a", "pay", "-", "to", "-", "pubkey", "transaction", "false", "otherwise", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/standard.go#L88-L93
train
btcsuite/btcd
txscript/standard.go
isPubkeyHash
func isPubkeyHash(pops []parsedOpcode) bool { return len(pops) == 5 && pops[0].opcode.value == OP_DUP && pops[1].opcode.value == OP_HASH160 && pops[2].opcode.value == OP_DATA_20 && pops[3].opcode.value == OP_EQUALVERIFY && pops[4].opcode.value == OP_CHECKSIG }
go
func isPubkeyHash(pops []parsedOpcode) bool { return len(pops) == 5 && pops[0].opcode.value == OP_DUP && pops[1].opcode.value == OP_HASH160 && pops[2].opcode.value == OP_DATA_20 && pops[3].opcode.value == OP_EQUALVERIFY && pops[4].opcode.value == OP_CHECKSIG }
[ "func", "isPubkeyHash", "(", "pops", "[", "]", "parsedOpcode", ")", "bool", "{", "return", "len", "(", "pops", ")", "==", "5", "&&", "pops", "[", "0", "]", ".", "opcode", ".", "value", "==", "OP_DUP", "&&", "pops", "[", "1", "]", ".", "opcode", ".", "value", "==", "OP_HASH160", "&&", "pops", "[", "2", "]", ".", "opcode", ".", "value", "==", "OP_DATA_20", "&&", "pops", "[", "3", "]", ".", "opcode", ".", "value", "==", "OP_EQUALVERIFY", "&&", "pops", "[", "4", "]", ".", "opcode", ".", "value", "==", "OP_CHECKSIG", "\n\n", "}" ]
// isPubkeyHash returns true if the script passed is a pay-to-pubkey-hash // transaction, false otherwise.
[ "isPubkeyHash", "returns", "true", "if", "the", "script", "passed", "is", "a", "pay", "-", "to", "-", "pubkey", "-", "hash", "transaction", "false", "otherwise", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/standard.go#L97-L105
train
btcsuite/btcd
txscript/standard.go
isMultiSig
func isMultiSig(pops []parsedOpcode) bool { // The absolute minimum is 1 pubkey: // OP_0/OP_1-16 <pubkey> OP_1 OP_CHECKMULTISIG l := len(pops) if l < 4 { return false } if !isSmallInt(pops[0].opcode) { return false } if !isSmallInt(pops[l-2].opcode) { return false } if pops[l-1].opcode.value != OP_CHECKMULTISIG { return false } // Verify the number of pubkeys specified matches the actual number // of pubkeys provided. if l-2-1 != asSmallInt(pops[l-2].opcode) { return false } for _, pop := range pops[1 : l-2] { // Valid pubkeys are either 33 or 65 bytes. if len(pop.data) != 33 && len(pop.data) != 65 { return false } } return true }
go
func isMultiSig(pops []parsedOpcode) bool { // The absolute minimum is 1 pubkey: // OP_0/OP_1-16 <pubkey> OP_1 OP_CHECKMULTISIG l := len(pops) if l < 4 { return false } if !isSmallInt(pops[0].opcode) { return false } if !isSmallInt(pops[l-2].opcode) { return false } if pops[l-1].opcode.value != OP_CHECKMULTISIG { return false } // Verify the number of pubkeys specified matches the actual number // of pubkeys provided. if l-2-1 != asSmallInt(pops[l-2].opcode) { return false } for _, pop := range pops[1 : l-2] { // Valid pubkeys are either 33 or 65 bytes. if len(pop.data) != 33 && len(pop.data) != 65 { return false } } return true }
[ "func", "isMultiSig", "(", "pops", "[", "]", "parsedOpcode", ")", "bool", "{", "// The absolute minimum is 1 pubkey:", "// OP_0/OP_1-16 <pubkey> OP_1 OP_CHECKMULTISIG", "l", ":=", "len", "(", "pops", ")", "\n", "if", "l", "<", "4", "{", "return", "false", "\n", "}", "\n", "if", "!", "isSmallInt", "(", "pops", "[", "0", "]", ".", "opcode", ")", "{", "return", "false", "\n", "}", "\n", "if", "!", "isSmallInt", "(", "pops", "[", "l", "-", "2", "]", ".", "opcode", ")", "{", "return", "false", "\n", "}", "\n", "if", "pops", "[", "l", "-", "1", "]", ".", "opcode", ".", "value", "!=", "OP_CHECKMULTISIG", "{", "return", "false", "\n", "}", "\n\n", "// Verify the number of pubkeys specified matches the actual number", "// of pubkeys provided.", "if", "l", "-", "2", "-", "1", "!=", "asSmallInt", "(", "pops", "[", "l", "-", "2", "]", ".", "opcode", ")", "{", "return", "false", "\n", "}", "\n\n", "for", "_", ",", "pop", ":=", "range", "pops", "[", "1", ":", "l", "-", "2", "]", "{", "// Valid pubkeys are either 33 or 65 bytes.", "if", "len", "(", "pop", ".", "data", ")", "!=", "33", "&&", "len", "(", "pop", ".", "data", ")", "!=", "65", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// isMultiSig returns true if the passed script is a multisig transaction, false // otherwise.
[ "isMultiSig", "returns", "true", "if", "the", "passed", "script", "is", "a", "multisig", "transaction", "false", "otherwise", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/standard.go#L109-L139
train
btcsuite/btcd
txscript/standard.go
isNullData
func isNullData(pops []parsedOpcode) bool { // A nulldata transaction is either a single OP_RETURN or an // OP_RETURN SMALLDATA (where SMALLDATA is a data push up to // MaxDataCarrierSize bytes). l := len(pops) if l == 1 && pops[0].opcode.value == OP_RETURN { return true } return l == 2 && pops[0].opcode.value == OP_RETURN && (isSmallInt(pops[1].opcode) || pops[1].opcode.value <= OP_PUSHDATA4) && len(pops[1].data) <= MaxDataCarrierSize }
go
func isNullData(pops []parsedOpcode) bool { // A nulldata transaction is either a single OP_RETURN or an // OP_RETURN SMALLDATA (where SMALLDATA is a data push up to // MaxDataCarrierSize bytes). l := len(pops) if l == 1 && pops[0].opcode.value == OP_RETURN { return true } return l == 2 && pops[0].opcode.value == OP_RETURN && (isSmallInt(pops[1].opcode) || pops[1].opcode.value <= OP_PUSHDATA4) && len(pops[1].data) <= MaxDataCarrierSize }
[ "func", "isNullData", "(", "pops", "[", "]", "parsedOpcode", ")", "bool", "{", "// A nulldata transaction is either a single OP_RETURN or an", "// OP_RETURN SMALLDATA (where SMALLDATA is a data push up to", "// MaxDataCarrierSize bytes).", "l", ":=", "len", "(", "pops", ")", "\n", "if", "l", "==", "1", "&&", "pops", "[", "0", "]", ".", "opcode", ".", "value", "==", "OP_RETURN", "{", "return", "true", "\n", "}", "\n\n", "return", "l", "==", "2", "&&", "pops", "[", "0", "]", ".", "opcode", ".", "value", "==", "OP_RETURN", "&&", "(", "isSmallInt", "(", "pops", "[", "1", "]", ".", "opcode", ")", "||", "pops", "[", "1", "]", ".", "opcode", ".", "value", "<=", "OP_PUSHDATA4", ")", "&&", "len", "(", "pops", "[", "1", "]", ".", "data", ")", "<=", "MaxDataCarrierSize", "\n", "}" ]
// isNullData returns true if the passed script is a null data transaction, // false otherwise.
[ "isNullData", "returns", "true", "if", "the", "passed", "script", "is", "a", "null", "data", "transaction", "false", "otherwise", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/standard.go#L143-L157
train
btcsuite/btcd
txscript/standard.go
typeOfScript
func typeOfScript(pops []parsedOpcode) ScriptClass { if isPubkey(pops) { return PubKeyTy } else if isPubkeyHash(pops) { return PubKeyHashTy } else if isWitnessPubKeyHash(pops) { return WitnessV0PubKeyHashTy } else if isScriptHash(pops) { return ScriptHashTy } else if isWitnessScriptHash(pops) { return WitnessV0ScriptHashTy } else if isMultiSig(pops) { return MultiSigTy } else if isNullData(pops) { return NullDataTy } return NonStandardTy }
go
func typeOfScript(pops []parsedOpcode) ScriptClass { if isPubkey(pops) { return PubKeyTy } else if isPubkeyHash(pops) { return PubKeyHashTy } else if isWitnessPubKeyHash(pops) { return WitnessV0PubKeyHashTy } else if isScriptHash(pops) { return ScriptHashTy } else if isWitnessScriptHash(pops) { return WitnessV0ScriptHashTy } else if isMultiSig(pops) { return MultiSigTy } else if isNullData(pops) { return NullDataTy } return NonStandardTy }
[ "func", "typeOfScript", "(", "pops", "[", "]", "parsedOpcode", ")", "ScriptClass", "{", "if", "isPubkey", "(", "pops", ")", "{", "return", "PubKeyTy", "\n", "}", "else", "if", "isPubkeyHash", "(", "pops", ")", "{", "return", "PubKeyHashTy", "\n", "}", "else", "if", "isWitnessPubKeyHash", "(", "pops", ")", "{", "return", "WitnessV0PubKeyHashTy", "\n", "}", "else", "if", "isScriptHash", "(", "pops", ")", "{", "return", "ScriptHashTy", "\n", "}", "else", "if", "isWitnessScriptHash", "(", "pops", ")", "{", "return", "WitnessV0ScriptHashTy", "\n", "}", "else", "if", "isMultiSig", "(", "pops", ")", "{", "return", "MultiSigTy", "\n", "}", "else", "if", "isNullData", "(", "pops", ")", "{", "return", "NullDataTy", "\n", "}", "\n", "return", "NonStandardTy", "\n", "}" ]
// scriptType returns the type of the script being inspected from the known // standard types.
[ "scriptType", "returns", "the", "type", "of", "the", "script", "being", "inspected", "from", "the", "known", "standard", "types", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/standard.go#L161-L178
train
btcsuite/btcd
txscript/standard.go
GetScriptClass
func GetScriptClass(script []byte) ScriptClass { pops, err := parseScript(script) if err != nil { return NonStandardTy } return typeOfScript(pops) }
go
func GetScriptClass(script []byte) ScriptClass { pops, err := parseScript(script) if err != nil { return NonStandardTy } return typeOfScript(pops) }
[ "func", "GetScriptClass", "(", "script", "[", "]", "byte", ")", "ScriptClass", "{", "pops", ",", "err", ":=", "parseScript", "(", "script", ")", "\n", "if", "err", "!=", "nil", "{", "return", "NonStandardTy", "\n", "}", "\n", "return", "typeOfScript", "(", "pops", ")", "\n", "}" ]
// GetScriptClass returns the class of the script passed. // // NonStandardTy will be returned when the script does not parse.
[ "GetScriptClass", "returns", "the", "class", "of", "the", "script", "passed", ".", "NonStandardTy", "will", "be", "returned", "when", "the", "script", "does", "not", "parse", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/standard.go#L183-L189
train
btcsuite/btcd
txscript/standard.go
CalcScriptInfo
func CalcScriptInfo(sigScript, pkScript []byte, witness wire.TxWitness, bip16, segwit bool) (*ScriptInfo, error) { sigPops, err := parseScript(sigScript) if err != nil { return nil, err } pkPops, err := parseScript(pkScript) if err != nil { return nil, err } // Push only sigScript makes little sense. si := new(ScriptInfo) si.PkScriptClass = typeOfScript(pkPops) // Can't have a signature script that doesn't just push data. if !isPushOnly(sigPops) { return nil, scriptError(ErrNotPushOnly, "signature script is not push only") } si.ExpectedInputs = expectedInputs(pkPops, si.PkScriptClass) switch { // Count sigops taking into account pay-to-script-hash. case si.PkScriptClass == ScriptHashTy && bip16 && !segwit: // The pay-to-hash-script is the final data push of the // signature script. script := sigPops[len(sigPops)-1].data shPops, err := parseScript(script) if err != nil { return nil, err } shInputs := expectedInputs(shPops, typeOfScript(shPops)) if shInputs == -1 { si.ExpectedInputs = -1 } else { si.ExpectedInputs += shInputs } si.SigOps = getSigOpCount(shPops, true) // All entries pushed to stack (or are OP_RESERVED and exec // will fail). si.NumInputs = len(sigPops) // If segwit is active, and this is a regular p2wkh output, then we'll // treat the script as a p2pkh output in essence. case si.PkScriptClass == WitnessV0PubKeyHashTy && segwit: si.SigOps = GetWitnessSigOpCount(sigScript, pkScript, witness) si.NumInputs = len(witness) // We'll attempt to detect the nested p2sh case so we can accurately // count the signature operations involved. case si.PkScriptClass == ScriptHashTy && IsWitnessProgram(sigScript[1:]) && bip16 && segwit: // Extract the pushed witness program from the sigScript so we // can determine the number of expected inputs. pkPops, _ := parseScript(sigScript[1:]) shInputs := expectedInputs(pkPops, typeOfScript(pkPops)) if shInputs == -1 { si.ExpectedInputs = -1 } else { si.ExpectedInputs += shInputs } si.SigOps = GetWitnessSigOpCount(sigScript, pkScript, witness) si.NumInputs = len(witness) si.NumInputs += len(sigPops) // If segwit is active, and this is a p2wsh output, then we'll need to // examine the witness script to generate accurate script info. case si.PkScriptClass == WitnessV0ScriptHashTy && segwit: // The witness script is the final element of the witness // stack. witnessScript := witness[len(witness)-1] pops, _ := parseScript(witnessScript) shInputs := expectedInputs(pops, typeOfScript(pops)) if shInputs == -1 { si.ExpectedInputs = -1 } else { si.ExpectedInputs += shInputs } si.SigOps = GetWitnessSigOpCount(sigScript, pkScript, witness) si.NumInputs = len(witness) default: si.SigOps = getSigOpCount(pkPops, true) // All entries pushed to stack (or are OP_RESERVED and exec // will fail). si.NumInputs = len(sigPops) } return si, nil }
go
func CalcScriptInfo(sigScript, pkScript []byte, witness wire.TxWitness, bip16, segwit bool) (*ScriptInfo, error) { sigPops, err := parseScript(sigScript) if err != nil { return nil, err } pkPops, err := parseScript(pkScript) if err != nil { return nil, err } // Push only sigScript makes little sense. si := new(ScriptInfo) si.PkScriptClass = typeOfScript(pkPops) // Can't have a signature script that doesn't just push data. if !isPushOnly(sigPops) { return nil, scriptError(ErrNotPushOnly, "signature script is not push only") } si.ExpectedInputs = expectedInputs(pkPops, si.PkScriptClass) switch { // Count sigops taking into account pay-to-script-hash. case si.PkScriptClass == ScriptHashTy && bip16 && !segwit: // The pay-to-hash-script is the final data push of the // signature script. script := sigPops[len(sigPops)-1].data shPops, err := parseScript(script) if err != nil { return nil, err } shInputs := expectedInputs(shPops, typeOfScript(shPops)) if shInputs == -1 { si.ExpectedInputs = -1 } else { si.ExpectedInputs += shInputs } si.SigOps = getSigOpCount(shPops, true) // All entries pushed to stack (or are OP_RESERVED and exec // will fail). si.NumInputs = len(sigPops) // If segwit is active, and this is a regular p2wkh output, then we'll // treat the script as a p2pkh output in essence. case si.PkScriptClass == WitnessV0PubKeyHashTy && segwit: si.SigOps = GetWitnessSigOpCount(sigScript, pkScript, witness) si.NumInputs = len(witness) // We'll attempt to detect the nested p2sh case so we can accurately // count the signature operations involved. case si.PkScriptClass == ScriptHashTy && IsWitnessProgram(sigScript[1:]) && bip16 && segwit: // Extract the pushed witness program from the sigScript so we // can determine the number of expected inputs. pkPops, _ := parseScript(sigScript[1:]) shInputs := expectedInputs(pkPops, typeOfScript(pkPops)) if shInputs == -1 { si.ExpectedInputs = -1 } else { si.ExpectedInputs += shInputs } si.SigOps = GetWitnessSigOpCount(sigScript, pkScript, witness) si.NumInputs = len(witness) si.NumInputs += len(sigPops) // If segwit is active, and this is a p2wsh output, then we'll need to // examine the witness script to generate accurate script info. case si.PkScriptClass == WitnessV0ScriptHashTy && segwit: // The witness script is the final element of the witness // stack. witnessScript := witness[len(witness)-1] pops, _ := parseScript(witnessScript) shInputs := expectedInputs(pops, typeOfScript(pops)) if shInputs == -1 { si.ExpectedInputs = -1 } else { si.ExpectedInputs += shInputs } si.SigOps = GetWitnessSigOpCount(sigScript, pkScript, witness) si.NumInputs = len(witness) default: si.SigOps = getSigOpCount(pkPops, true) // All entries pushed to stack (or are OP_RESERVED and exec // will fail). si.NumInputs = len(sigPops) } return si, nil }
[ "func", "CalcScriptInfo", "(", "sigScript", ",", "pkScript", "[", "]", "byte", ",", "witness", "wire", ".", "TxWitness", ",", "bip16", ",", "segwit", "bool", ")", "(", "*", "ScriptInfo", ",", "error", ")", "{", "sigPops", ",", "err", ":=", "parseScript", "(", "sigScript", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "pkPops", ",", "err", ":=", "parseScript", "(", "pkScript", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Push only sigScript makes little sense.", "si", ":=", "new", "(", "ScriptInfo", ")", "\n", "si", ".", "PkScriptClass", "=", "typeOfScript", "(", "pkPops", ")", "\n\n", "// Can't have a signature script that doesn't just push data.", "if", "!", "isPushOnly", "(", "sigPops", ")", "{", "return", "nil", ",", "scriptError", "(", "ErrNotPushOnly", ",", "\"", "\"", ")", "\n", "}", "\n\n", "si", ".", "ExpectedInputs", "=", "expectedInputs", "(", "pkPops", ",", "si", ".", "PkScriptClass", ")", "\n\n", "switch", "{", "// Count sigops taking into account pay-to-script-hash.", "case", "si", ".", "PkScriptClass", "==", "ScriptHashTy", "&&", "bip16", "&&", "!", "segwit", ":", "// The pay-to-hash-script is the final data push of the", "// signature script.", "script", ":=", "sigPops", "[", "len", "(", "sigPops", ")", "-", "1", "]", ".", "data", "\n", "shPops", ",", "err", ":=", "parseScript", "(", "script", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "shInputs", ":=", "expectedInputs", "(", "shPops", ",", "typeOfScript", "(", "shPops", ")", ")", "\n", "if", "shInputs", "==", "-", "1", "{", "si", ".", "ExpectedInputs", "=", "-", "1", "\n", "}", "else", "{", "si", ".", "ExpectedInputs", "+=", "shInputs", "\n", "}", "\n", "si", ".", "SigOps", "=", "getSigOpCount", "(", "shPops", ",", "true", ")", "\n\n", "// All entries pushed to stack (or are OP_RESERVED and exec", "// will fail).", "si", ".", "NumInputs", "=", "len", "(", "sigPops", ")", "\n\n", "// If segwit is active, and this is a regular p2wkh output, then we'll", "// treat the script as a p2pkh output in essence.", "case", "si", ".", "PkScriptClass", "==", "WitnessV0PubKeyHashTy", "&&", "segwit", ":", "si", ".", "SigOps", "=", "GetWitnessSigOpCount", "(", "sigScript", ",", "pkScript", ",", "witness", ")", "\n", "si", ".", "NumInputs", "=", "len", "(", "witness", ")", "\n\n", "// We'll attempt to detect the nested p2sh case so we can accurately", "// count the signature operations involved.", "case", "si", ".", "PkScriptClass", "==", "ScriptHashTy", "&&", "IsWitnessProgram", "(", "sigScript", "[", "1", ":", "]", ")", "&&", "bip16", "&&", "segwit", ":", "// Extract the pushed witness program from the sigScript so we", "// can determine the number of expected inputs.", "pkPops", ",", "_", ":=", "parseScript", "(", "sigScript", "[", "1", ":", "]", ")", "\n", "shInputs", ":=", "expectedInputs", "(", "pkPops", ",", "typeOfScript", "(", "pkPops", ")", ")", "\n", "if", "shInputs", "==", "-", "1", "{", "si", ".", "ExpectedInputs", "=", "-", "1", "\n", "}", "else", "{", "si", ".", "ExpectedInputs", "+=", "shInputs", "\n", "}", "\n\n", "si", ".", "SigOps", "=", "GetWitnessSigOpCount", "(", "sigScript", ",", "pkScript", ",", "witness", ")", "\n\n", "si", ".", "NumInputs", "=", "len", "(", "witness", ")", "\n", "si", ".", "NumInputs", "+=", "len", "(", "sigPops", ")", "\n\n", "// If segwit is active, and this is a p2wsh output, then we'll need to", "// examine the witness script to generate accurate script info.", "case", "si", ".", "PkScriptClass", "==", "WitnessV0ScriptHashTy", "&&", "segwit", ":", "// The witness script is the final element of the witness", "// stack.", "witnessScript", ":=", "witness", "[", "len", "(", "witness", ")", "-", "1", "]", "\n", "pops", ",", "_", ":=", "parseScript", "(", "witnessScript", ")", "\n\n", "shInputs", ":=", "expectedInputs", "(", "pops", ",", "typeOfScript", "(", "pops", ")", ")", "\n", "if", "shInputs", "==", "-", "1", "{", "si", ".", "ExpectedInputs", "=", "-", "1", "\n", "}", "else", "{", "si", ".", "ExpectedInputs", "+=", "shInputs", "\n", "}", "\n\n", "si", ".", "SigOps", "=", "GetWitnessSigOpCount", "(", "sigScript", ",", "pkScript", ",", "witness", ")", "\n", "si", ".", "NumInputs", "=", "len", "(", "witness", ")", "\n\n", "default", ":", "si", ".", "SigOps", "=", "getSigOpCount", "(", "pkPops", ",", "true", ")", "\n\n", "// All entries pushed to stack (or are OP_RESERVED and exec", "// will fail).", "si", ".", "NumInputs", "=", "len", "(", "sigPops", ")", "\n", "}", "\n\n", "return", "si", ",", "nil", "\n", "}" ]
// CalcScriptInfo returns a structure providing data about the provided script // pair. It will error if the pair is in someway invalid such that they can not // be analysed, i.e. if they do not parse or the pkScript is not a push-only // script
[ "CalcScriptInfo", "returns", "a", "structure", "providing", "data", "about", "the", "provided", "script", "pair", ".", "It", "will", "error", "if", "the", "pair", "is", "in", "someway", "invalid", "such", "that", "they", "can", "not", "be", "analysed", "i", ".", "e", ".", "if", "they", "do", "not", "parse", "or", "the", "pkScript", "is", "not", "a", "push", "-", "only", "script" ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/standard.go#L255-L357
train
btcsuite/btcd
txscript/standard.go
CalcMultiSigStats
func CalcMultiSigStats(script []byte) (int, int, error) { pops, err := parseScript(script) if err != nil { return 0, 0, err } // A multi-signature script is of the pattern: // NUM_SIGS PUBKEY PUBKEY PUBKEY... NUM_PUBKEYS OP_CHECKMULTISIG // Therefore the number of signatures is the oldest item on the stack // and the number of pubkeys is the 2nd to last. Also, the absolute // minimum for a multi-signature script is 1 pubkey, so at least 4 // items must be on the stack per: // OP_1 PUBKEY OP_1 OP_CHECKMULTISIG if len(pops) < 4 { str := fmt.Sprintf("script %x is not a multisig script", script) return 0, 0, scriptError(ErrNotMultisigScript, str) } numSigs := asSmallInt(pops[0].opcode) numPubKeys := asSmallInt(pops[len(pops)-2].opcode) return numPubKeys, numSigs, nil }
go
func CalcMultiSigStats(script []byte) (int, int, error) { pops, err := parseScript(script) if err != nil { return 0, 0, err } // A multi-signature script is of the pattern: // NUM_SIGS PUBKEY PUBKEY PUBKEY... NUM_PUBKEYS OP_CHECKMULTISIG // Therefore the number of signatures is the oldest item on the stack // and the number of pubkeys is the 2nd to last. Also, the absolute // minimum for a multi-signature script is 1 pubkey, so at least 4 // items must be on the stack per: // OP_1 PUBKEY OP_1 OP_CHECKMULTISIG if len(pops) < 4 { str := fmt.Sprintf("script %x is not a multisig script", script) return 0, 0, scriptError(ErrNotMultisigScript, str) } numSigs := asSmallInt(pops[0].opcode) numPubKeys := asSmallInt(pops[len(pops)-2].opcode) return numPubKeys, numSigs, nil }
[ "func", "CalcMultiSigStats", "(", "script", "[", "]", "byte", ")", "(", "int", ",", "int", ",", "error", ")", "{", "pops", ",", "err", ":=", "parseScript", "(", "script", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "0", ",", "err", "\n", "}", "\n\n", "// A multi-signature script is of the pattern:", "// NUM_SIGS PUBKEY PUBKEY PUBKEY... NUM_PUBKEYS OP_CHECKMULTISIG", "// Therefore the number of signatures is the oldest item on the stack", "// and the number of pubkeys is the 2nd to last. Also, the absolute", "// minimum for a multi-signature script is 1 pubkey, so at least 4", "// items must be on the stack per:", "// OP_1 PUBKEY OP_1 OP_CHECKMULTISIG", "if", "len", "(", "pops", ")", "<", "4", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "script", ")", "\n", "return", "0", ",", "0", ",", "scriptError", "(", "ErrNotMultisigScript", ",", "str", ")", "\n", "}", "\n\n", "numSigs", ":=", "asSmallInt", "(", "pops", "[", "0", "]", ".", "opcode", ")", "\n", "numPubKeys", ":=", "asSmallInt", "(", "pops", "[", "len", "(", "pops", ")", "-", "2", "]", ".", "opcode", ")", "\n", "return", "numPubKeys", ",", "numSigs", ",", "nil", "\n", "}" ]
// CalcMultiSigStats returns the number of public keys and signatures from // a multi-signature transaction script. The passed script MUST already be // known to be a multi-signature script.
[ "CalcMultiSigStats", "returns", "the", "number", "of", "public", "keys", "and", "signatures", "from", "a", "multi", "-", "signature", "transaction", "script", ".", "The", "passed", "script", "MUST", "already", "be", "known", "to", "be", "a", "multi", "-", "signature", "script", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/standard.go#L362-L383
train
btcsuite/btcd
txscript/standard.go
payToPubKeyHashScript
func payToPubKeyHashScript(pubKeyHash []byte) ([]byte, error) { return NewScriptBuilder().AddOp(OP_DUP).AddOp(OP_HASH160). AddData(pubKeyHash).AddOp(OP_EQUALVERIFY).AddOp(OP_CHECKSIG). Script() }
go
func payToPubKeyHashScript(pubKeyHash []byte) ([]byte, error) { return NewScriptBuilder().AddOp(OP_DUP).AddOp(OP_HASH160). AddData(pubKeyHash).AddOp(OP_EQUALVERIFY).AddOp(OP_CHECKSIG). Script() }
[ "func", "payToPubKeyHashScript", "(", "pubKeyHash", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "NewScriptBuilder", "(", ")", ".", "AddOp", "(", "OP_DUP", ")", ".", "AddOp", "(", "OP_HASH160", ")", ".", "AddData", "(", "pubKeyHash", ")", ".", "AddOp", "(", "OP_EQUALVERIFY", ")", ".", "AddOp", "(", "OP_CHECKSIG", ")", ".", "Script", "(", ")", "\n", "}" ]
// payToPubKeyHashScript creates a new script to pay a transaction // output to a 20-byte pubkey hash. It is expected that the input is a valid // hash.
[ "payToPubKeyHashScript", "creates", "a", "new", "script", "to", "pay", "a", "transaction", "output", "to", "a", "20", "-", "byte", "pubkey", "hash", ".", "It", "is", "expected", "that", "the", "input", "is", "a", "valid", "hash", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/standard.go#L388-L392
train
btcsuite/btcd
txscript/standard.go
payToWitnessPubKeyHashScript
func payToWitnessPubKeyHashScript(pubKeyHash []byte) ([]byte, error) { return NewScriptBuilder().AddOp(OP_0).AddData(pubKeyHash).Script() }
go
func payToWitnessPubKeyHashScript(pubKeyHash []byte) ([]byte, error) { return NewScriptBuilder().AddOp(OP_0).AddData(pubKeyHash).Script() }
[ "func", "payToWitnessPubKeyHashScript", "(", "pubKeyHash", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "NewScriptBuilder", "(", ")", ".", "AddOp", "(", "OP_0", ")", ".", "AddData", "(", "pubKeyHash", ")", ".", "Script", "(", ")", "\n", "}" ]
// payToWitnessPubKeyHashScript creates a new script to pay to a version 0 // pubkey hash witness program. The passed hash is expected to be valid.
[ "payToWitnessPubKeyHashScript", "creates", "a", "new", "script", "to", "pay", "to", "a", "version", "0", "pubkey", "hash", "witness", "program", ".", "The", "passed", "hash", "is", "expected", "to", "be", "valid", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/standard.go#L396-L398
train
btcsuite/btcd
txscript/standard.go
payToScriptHashScript
func payToScriptHashScript(scriptHash []byte) ([]byte, error) { return NewScriptBuilder().AddOp(OP_HASH160).AddData(scriptHash). AddOp(OP_EQUAL).Script() }
go
func payToScriptHashScript(scriptHash []byte) ([]byte, error) { return NewScriptBuilder().AddOp(OP_HASH160).AddData(scriptHash). AddOp(OP_EQUAL).Script() }
[ "func", "payToScriptHashScript", "(", "scriptHash", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "NewScriptBuilder", "(", ")", ".", "AddOp", "(", "OP_HASH160", ")", ".", "AddData", "(", "scriptHash", ")", ".", "AddOp", "(", "OP_EQUAL", ")", ".", "Script", "(", ")", "\n", "}" ]
// payToScriptHashScript creates a new script to pay a transaction output to a // script hash. It is expected that the input is a valid hash.
[ "payToScriptHashScript", "creates", "a", "new", "script", "to", "pay", "a", "transaction", "output", "to", "a", "script", "hash", ".", "It", "is", "expected", "that", "the", "input", "is", "a", "valid", "hash", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/standard.go#L402-L405
train
btcsuite/btcd
txscript/standard.go
payToWitnessScriptHashScript
func payToWitnessScriptHashScript(scriptHash []byte) ([]byte, error) { return NewScriptBuilder().AddOp(OP_0).AddData(scriptHash).Script() }
go
func payToWitnessScriptHashScript(scriptHash []byte) ([]byte, error) { return NewScriptBuilder().AddOp(OP_0).AddData(scriptHash).Script() }
[ "func", "payToWitnessScriptHashScript", "(", "scriptHash", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "NewScriptBuilder", "(", ")", ".", "AddOp", "(", "OP_0", ")", ".", "AddData", "(", "scriptHash", ")", ".", "Script", "(", ")", "\n", "}" ]
// payToWitnessPubKeyHashScript creates a new script to pay to a version 0 // script hash witness program. The passed hash is expected to be valid.
[ "payToWitnessPubKeyHashScript", "creates", "a", "new", "script", "to", "pay", "to", "a", "version", "0", "script", "hash", "witness", "program", ".", "The", "passed", "hash", "is", "expected", "to", "be", "valid", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/standard.go#L409-L411
train
btcsuite/btcd
txscript/standard.go
payToPubKeyScript
func payToPubKeyScript(serializedPubKey []byte) ([]byte, error) { return NewScriptBuilder().AddData(serializedPubKey). AddOp(OP_CHECKSIG).Script() }
go
func payToPubKeyScript(serializedPubKey []byte) ([]byte, error) { return NewScriptBuilder().AddData(serializedPubKey). AddOp(OP_CHECKSIG).Script() }
[ "func", "payToPubKeyScript", "(", "serializedPubKey", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "NewScriptBuilder", "(", ")", ".", "AddData", "(", "serializedPubKey", ")", ".", "AddOp", "(", "OP_CHECKSIG", ")", ".", "Script", "(", ")", "\n", "}" ]
// payToPubkeyScript creates a new script to pay a transaction output to a // public key. It is expected that the input is a valid pubkey.
[ "payToPubkeyScript", "creates", "a", "new", "script", "to", "pay", "a", "transaction", "output", "to", "a", "public", "key", ".", "It", "is", "expected", "that", "the", "input", "is", "a", "valid", "pubkey", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/standard.go#L415-L418
train
btcsuite/btcd
txscript/standard.go
PayToAddrScript
func PayToAddrScript(addr btcutil.Address) ([]byte, error) { const nilAddrErrStr = "unable to generate payment script for nil address" switch addr := addr.(type) { case *btcutil.AddressPubKeyHash: if addr == nil { return nil, scriptError(ErrUnsupportedAddress, nilAddrErrStr) } return payToPubKeyHashScript(addr.ScriptAddress()) case *btcutil.AddressScriptHash: if addr == nil { return nil, scriptError(ErrUnsupportedAddress, nilAddrErrStr) } return payToScriptHashScript(addr.ScriptAddress()) case *btcutil.AddressPubKey: if addr == nil { return nil, scriptError(ErrUnsupportedAddress, nilAddrErrStr) } return payToPubKeyScript(addr.ScriptAddress()) case *btcutil.AddressWitnessPubKeyHash: if addr == nil { return nil, scriptError(ErrUnsupportedAddress, nilAddrErrStr) } return payToWitnessPubKeyHashScript(addr.ScriptAddress()) case *btcutil.AddressWitnessScriptHash: if addr == nil { return nil, scriptError(ErrUnsupportedAddress, nilAddrErrStr) } return payToWitnessScriptHashScript(addr.ScriptAddress()) } str := fmt.Sprintf("unable to generate payment script for unsupported "+ "address type %T", addr) return nil, scriptError(ErrUnsupportedAddress, str) }
go
func PayToAddrScript(addr btcutil.Address) ([]byte, error) { const nilAddrErrStr = "unable to generate payment script for nil address" switch addr := addr.(type) { case *btcutil.AddressPubKeyHash: if addr == nil { return nil, scriptError(ErrUnsupportedAddress, nilAddrErrStr) } return payToPubKeyHashScript(addr.ScriptAddress()) case *btcutil.AddressScriptHash: if addr == nil { return nil, scriptError(ErrUnsupportedAddress, nilAddrErrStr) } return payToScriptHashScript(addr.ScriptAddress()) case *btcutil.AddressPubKey: if addr == nil { return nil, scriptError(ErrUnsupportedAddress, nilAddrErrStr) } return payToPubKeyScript(addr.ScriptAddress()) case *btcutil.AddressWitnessPubKeyHash: if addr == nil { return nil, scriptError(ErrUnsupportedAddress, nilAddrErrStr) } return payToWitnessPubKeyHashScript(addr.ScriptAddress()) case *btcutil.AddressWitnessScriptHash: if addr == nil { return nil, scriptError(ErrUnsupportedAddress, nilAddrErrStr) } return payToWitnessScriptHashScript(addr.ScriptAddress()) } str := fmt.Sprintf("unable to generate payment script for unsupported "+ "address type %T", addr) return nil, scriptError(ErrUnsupportedAddress, str) }
[ "func", "PayToAddrScript", "(", "addr", "btcutil", ".", "Address", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "const", "nilAddrErrStr", "=", "\"", "\"", "\n\n", "switch", "addr", ":=", "addr", ".", "(", "type", ")", "{", "case", "*", "btcutil", ".", "AddressPubKeyHash", ":", "if", "addr", "==", "nil", "{", "return", "nil", ",", "scriptError", "(", "ErrUnsupportedAddress", ",", "nilAddrErrStr", ")", "\n", "}", "\n", "return", "payToPubKeyHashScript", "(", "addr", ".", "ScriptAddress", "(", ")", ")", "\n\n", "case", "*", "btcutil", ".", "AddressScriptHash", ":", "if", "addr", "==", "nil", "{", "return", "nil", ",", "scriptError", "(", "ErrUnsupportedAddress", ",", "nilAddrErrStr", ")", "\n", "}", "\n", "return", "payToScriptHashScript", "(", "addr", ".", "ScriptAddress", "(", ")", ")", "\n\n", "case", "*", "btcutil", ".", "AddressPubKey", ":", "if", "addr", "==", "nil", "{", "return", "nil", ",", "scriptError", "(", "ErrUnsupportedAddress", ",", "nilAddrErrStr", ")", "\n", "}", "\n", "return", "payToPubKeyScript", "(", "addr", ".", "ScriptAddress", "(", ")", ")", "\n\n", "case", "*", "btcutil", ".", "AddressWitnessPubKeyHash", ":", "if", "addr", "==", "nil", "{", "return", "nil", ",", "scriptError", "(", "ErrUnsupportedAddress", ",", "nilAddrErrStr", ")", "\n", "}", "\n", "return", "payToWitnessPubKeyHashScript", "(", "addr", ".", "ScriptAddress", "(", ")", ")", "\n", "case", "*", "btcutil", ".", "AddressWitnessScriptHash", ":", "if", "addr", "==", "nil", "{", "return", "nil", ",", "scriptError", "(", "ErrUnsupportedAddress", ",", "nilAddrErrStr", ")", "\n", "}", "\n", "return", "payToWitnessScriptHashScript", "(", "addr", ".", "ScriptAddress", "(", ")", ")", "\n", "}", "\n\n", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "addr", ")", "\n", "return", "nil", ",", "scriptError", "(", "ErrUnsupportedAddress", ",", "str", ")", "\n", "}" ]
// PayToAddrScript creates a new script to pay a transaction output to a the // specified address.
[ "PayToAddrScript", "creates", "a", "new", "script", "to", "pay", "a", "transaction", "output", "to", "a", "the", "specified", "address", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/standard.go#L422-L464
train
btcsuite/btcd
txscript/standard.go
NullDataScript
func NullDataScript(data []byte) ([]byte, error) { if len(data) > MaxDataCarrierSize { str := fmt.Sprintf("data size %d is larger than max "+ "allowed size %d", len(data), MaxDataCarrierSize) return nil, scriptError(ErrTooMuchNullData, str) } return NewScriptBuilder().AddOp(OP_RETURN).AddData(data).Script() }
go
func NullDataScript(data []byte) ([]byte, error) { if len(data) > MaxDataCarrierSize { str := fmt.Sprintf("data size %d is larger than max "+ "allowed size %d", len(data), MaxDataCarrierSize) return nil, scriptError(ErrTooMuchNullData, str) } return NewScriptBuilder().AddOp(OP_RETURN).AddData(data).Script() }
[ "func", "NullDataScript", "(", "data", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "len", "(", "data", ")", ">", "MaxDataCarrierSize", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "len", "(", "data", ")", ",", "MaxDataCarrierSize", ")", "\n", "return", "nil", ",", "scriptError", "(", "ErrTooMuchNullData", ",", "str", ")", "\n", "}", "\n\n", "return", "NewScriptBuilder", "(", ")", ".", "AddOp", "(", "OP_RETURN", ")", ".", "AddData", "(", "data", ")", ".", "Script", "(", ")", "\n", "}" ]
// NullDataScript creates a provably-prunable script containing OP_RETURN // followed by the passed data. An Error with the error code ErrTooMuchNullData // will be returned if the length of the passed data exceeds MaxDataCarrierSize.
[ "NullDataScript", "creates", "a", "provably", "-", "prunable", "script", "containing", "OP_RETURN", "followed", "by", "the", "passed", "data", ".", "An", "Error", "with", "the", "error", "code", "ErrTooMuchNullData", "will", "be", "returned", "if", "the", "length", "of", "the", "passed", "data", "exceeds", "MaxDataCarrierSize", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/standard.go#L469-L477
train
btcsuite/btcd
txscript/standard.go
MultiSigScript
func MultiSigScript(pubkeys []*btcutil.AddressPubKey, nrequired int) ([]byte, error) { if len(pubkeys) < nrequired { str := fmt.Sprintf("unable to generate multisig script with "+ "%d required signatures when there are only %d public "+ "keys available", nrequired, len(pubkeys)) return nil, scriptError(ErrTooManyRequiredSigs, str) } builder := NewScriptBuilder().AddInt64(int64(nrequired)) for _, key := range pubkeys { builder.AddData(key.ScriptAddress()) } builder.AddInt64(int64(len(pubkeys))) builder.AddOp(OP_CHECKMULTISIG) return builder.Script() }
go
func MultiSigScript(pubkeys []*btcutil.AddressPubKey, nrequired int) ([]byte, error) { if len(pubkeys) < nrequired { str := fmt.Sprintf("unable to generate multisig script with "+ "%d required signatures when there are only %d public "+ "keys available", nrequired, len(pubkeys)) return nil, scriptError(ErrTooManyRequiredSigs, str) } builder := NewScriptBuilder().AddInt64(int64(nrequired)) for _, key := range pubkeys { builder.AddData(key.ScriptAddress()) } builder.AddInt64(int64(len(pubkeys))) builder.AddOp(OP_CHECKMULTISIG) return builder.Script() }
[ "func", "MultiSigScript", "(", "pubkeys", "[", "]", "*", "btcutil", ".", "AddressPubKey", ",", "nrequired", "int", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "len", "(", "pubkeys", ")", "<", "nrequired", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ",", "nrequired", ",", "len", "(", "pubkeys", ")", ")", "\n", "return", "nil", ",", "scriptError", "(", "ErrTooManyRequiredSigs", ",", "str", ")", "\n", "}", "\n\n", "builder", ":=", "NewScriptBuilder", "(", ")", ".", "AddInt64", "(", "int64", "(", "nrequired", ")", ")", "\n", "for", "_", ",", "key", ":=", "range", "pubkeys", "{", "builder", ".", "AddData", "(", "key", ".", "ScriptAddress", "(", ")", ")", "\n", "}", "\n", "builder", ".", "AddInt64", "(", "int64", "(", "len", "(", "pubkeys", ")", ")", ")", "\n", "builder", ".", "AddOp", "(", "OP_CHECKMULTISIG", ")", "\n\n", "return", "builder", ".", "Script", "(", ")", "\n", "}" ]
// MultiSigScript returns a valid script for a multisignature redemption where // nrequired of the keys in pubkeys are required to have signed the transaction // for success. An Error with the error code ErrTooManyRequiredSigs will be // returned if nrequired is larger than the number of keys provided.
[ "MultiSigScript", "returns", "a", "valid", "script", "for", "a", "multisignature", "redemption", "where", "nrequired", "of", "the", "keys", "in", "pubkeys", "are", "required", "to", "have", "signed", "the", "transaction", "for", "success", ".", "An", "Error", "with", "the", "error", "code", "ErrTooManyRequiredSigs", "will", "be", "returned", "if", "nrequired", "is", "larger", "than", "the", "number", "of", "keys", "provided", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/standard.go#L483-L499
train
btcsuite/btcd
txscript/standard.go
PushedData
func PushedData(script []byte) ([][]byte, error) { pops, err := parseScript(script) if err != nil { return nil, err } var data [][]byte for _, pop := range pops { if pop.data != nil { data = append(data, pop.data) } else if pop.opcode.value == OP_0 { data = append(data, nil) } } return data, nil }
go
func PushedData(script []byte) ([][]byte, error) { pops, err := parseScript(script) if err != nil { return nil, err } var data [][]byte for _, pop := range pops { if pop.data != nil { data = append(data, pop.data) } else if pop.opcode.value == OP_0 { data = append(data, nil) } } return data, nil }
[ "func", "PushedData", "(", "script", "[", "]", "byte", ")", "(", "[", "]", "[", "]", "byte", ",", "error", ")", "{", "pops", ",", "err", ":=", "parseScript", "(", "script", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "data", "[", "]", "[", "]", "byte", "\n", "for", "_", ",", "pop", ":=", "range", "pops", "{", "if", "pop", ".", "data", "!=", "nil", "{", "data", "=", "append", "(", "data", ",", "pop", ".", "data", ")", "\n", "}", "else", "if", "pop", ".", "opcode", ".", "value", "==", "OP_0", "{", "data", "=", "append", "(", "data", ",", "nil", ")", "\n", "}", "\n", "}", "\n", "return", "data", ",", "nil", "\n", "}" ]
// PushedData returns an array of byte slices containing any pushed data found // in the passed script. This includes OP_0, but not OP_1 - OP_16.
[ "PushedData", "returns", "an", "array", "of", "byte", "slices", "containing", "any", "pushed", "data", "found", "in", "the", "passed", "script", ".", "This", "includes", "OP_0", "but", "not", "OP_1", "-", "OP_16", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/standard.go#L503-L518
train
btcsuite/btcd
txscript/standard.go
ExtractPkScriptAddrs
func ExtractPkScriptAddrs(pkScript []byte, chainParams *chaincfg.Params) (ScriptClass, []btcutil.Address, int, error) { var addrs []btcutil.Address var requiredSigs int // No valid addresses or required signatures if the script doesn't // parse. pops, err := parseScript(pkScript) if err != nil { return NonStandardTy, nil, 0, err } scriptClass := typeOfScript(pops) switch scriptClass { case PubKeyHashTy: // A pay-to-pubkey-hash script is of the form: // OP_DUP OP_HASH160 <hash> OP_EQUALVERIFY OP_CHECKSIG // Therefore the pubkey hash is the 3rd item on the stack. // Skip the pubkey hash if it's invalid for some reason. requiredSigs = 1 addr, err := btcutil.NewAddressPubKeyHash(pops[2].data, chainParams) if err == nil { addrs = append(addrs, addr) } case WitnessV0PubKeyHashTy: // A pay-to-witness-pubkey-hash script is of thw form: // OP_0 <20-byte hash> // Therefore, the pubkey hash is the second item on the stack. // Skip the pubkey hash if it's invalid for some reason. requiredSigs = 1 addr, err := btcutil.NewAddressWitnessPubKeyHash(pops[1].data, chainParams) if err == nil { addrs = append(addrs, addr) } case PubKeyTy: // A pay-to-pubkey script is of the form: // <pubkey> OP_CHECKSIG // Therefore the pubkey is the first item on the stack. // Skip the pubkey if it's invalid for some reason. requiredSigs = 1 addr, err := btcutil.NewAddressPubKey(pops[0].data, chainParams) if err == nil { addrs = append(addrs, addr) } case ScriptHashTy: // A pay-to-script-hash script is of the form: // OP_HASH160 <scripthash> OP_EQUAL // Therefore the script hash is the 2nd item on the stack. // Skip the script hash if it's invalid for some reason. requiredSigs = 1 addr, err := btcutil.NewAddressScriptHashFromHash(pops[1].data, chainParams) if err == nil { addrs = append(addrs, addr) } case WitnessV0ScriptHashTy: // A pay-to-witness-script-hash script is of the form: // OP_0 <32-byte hash> // Therefore, the script hash is the second item on the stack. // Skip the script hash if it's invalid for some reason. requiredSigs = 1 addr, err := btcutil.NewAddressWitnessScriptHash(pops[1].data, chainParams) if err == nil { addrs = append(addrs, addr) } case MultiSigTy: // A multi-signature script is of the form: // <numsigs> <pubkey> <pubkey> <pubkey>... <numpubkeys> OP_CHECKMULTISIG // Therefore the number of required signatures is the 1st item // on the stack and the number of public keys is the 2nd to last // item on the stack. requiredSigs = asSmallInt(pops[0].opcode) numPubKeys := asSmallInt(pops[len(pops)-2].opcode) // Extract the public keys while skipping any that are invalid. addrs = make([]btcutil.Address, 0, numPubKeys) for i := 0; i < numPubKeys; i++ { addr, err := btcutil.NewAddressPubKey(pops[i+1].data, chainParams) if err == nil { addrs = append(addrs, addr) } } case NullDataTy: // Null data transactions have no addresses or required // signatures. case NonStandardTy: // Don't attempt to extract addresses or required signatures for // nonstandard transactions. } return scriptClass, addrs, requiredSigs, nil }
go
func ExtractPkScriptAddrs(pkScript []byte, chainParams *chaincfg.Params) (ScriptClass, []btcutil.Address, int, error) { var addrs []btcutil.Address var requiredSigs int // No valid addresses or required signatures if the script doesn't // parse. pops, err := parseScript(pkScript) if err != nil { return NonStandardTy, nil, 0, err } scriptClass := typeOfScript(pops) switch scriptClass { case PubKeyHashTy: // A pay-to-pubkey-hash script is of the form: // OP_DUP OP_HASH160 <hash> OP_EQUALVERIFY OP_CHECKSIG // Therefore the pubkey hash is the 3rd item on the stack. // Skip the pubkey hash if it's invalid for some reason. requiredSigs = 1 addr, err := btcutil.NewAddressPubKeyHash(pops[2].data, chainParams) if err == nil { addrs = append(addrs, addr) } case WitnessV0PubKeyHashTy: // A pay-to-witness-pubkey-hash script is of thw form: // OP_0 <20-byte hash> // Therefore, the pubkey hash is the second item on the stack. // Skip the pubkey hash if it's invalid for some reason. requiredSigs = 1 addr, err := btcutil.NewAddressWitnessPubKeyHash(pops[1].data, chainParams) if err == nil { addrs = append(addrs, addr) } case PubKeyTy: // A pay-to-pubkey script is of the form: // <pubkey> OP_CHECKSIG // Therefore the pubkey is the first item on the stack. // Skip the pubkey if it's invalid for some reason. requiredSigs = 1 addr, err := btcutil.NewAddressPubKey(pops[0].data, chainParams) if err == nil { addrs = append(addrs, addr) } case ScriptHashTy: // A pay-to-script-hash script is of the form: // OP_HASH160 <scripthash> OP_EQUAL // Therefore the script hash is the 2nd item on the stack. // Skip the script hash if it's invalid for some reason. requiredSigs = 1 addr, err := btcutil.NewAddressScriptHashFromHash(pops[1].data, chainParams) if err == nil { addrs = append(addrs, addr) } case WitnessV0ScriptHashTy: // A pay-to-witness-script-hash script is of the form: // OP_0 <32-byte hash> // Therefore, the script hash is the second item on the stack. // Skip the script hash if it's invalid for some reason. requiredSigs = 1 addr, err := btcutil.NewAddressWitnessScriptHash(pops[1].data, chainParams) if err == nil { addrs = append(addrs, addr) } case MultiSigTy: // A multi-signature script is of the form: // <numsigs> <pubkey> <pubkey> <pubkey>... <numpubkeys> OP_CHECKMULTISIG // Therefore the number of required signatures is the 1st item // on the stack and the number of public keys is the 2nd to last // item on the stack. requiredSigs = asSmallInt(pops[0].opcode) numPubKeys := asSmallInt(pops[len(pops)-2].opcode) // Extract the public keys while skipping any that are invalid. addrs = make([]btcutil.Address, 0, numPubKeys) for i := 0; i < numPubKeys; i++ { addr, err := btcutil.NewAddressPubKey(pops[i+1].data, chainParams) if err == nil { addrs = append(addrs, addr) } } case NullDataTy: // Null data transactions have no addresses or required // signatures. case NonStandardTy: // Don't attempt to extract addresses or required signatures for // nonstandard transactions. } return scriptClass, addrs, requiredSigs, nil }
[ "func", "ExtractPkScriptAddrs", "(", "pkScript", "[", "]", "byte", ",", "chainParams", "*", "chaincfg", ".", "Params", ")", "(", "ScriptClass", ",", "[", "]", "btcutil", ".", "Address", ",", "int", ",", "error", ")", "{", "var", "addrs", "[", "]", "btcutil", ".", "Address", "\n", "var", "requiredSigs", "int", "\n\n", "// No valid addresses or required signatures if the script doesn't", "// parse.", "pops", ",", "err", ":=", "parseScript", "(", "pkScript", ")", "\n", "if", "err", "!=", "nil", "{", "return", "NonStandardTy", ",", "nil", ",", "0", ",", "err", "\n", "}", "\n\n", "scriptClass", ":=", "typeOfScript", "(", "pops", ")", "\n", "switch", "scriptClass", "{", "case", "PubKeyHashTy", ":", "// A pay-to-pubkey-hash script is of the form:", "// OP_DUP OP_HASH160 <hash> OP_EQUALVERIFY OP_CHECKSIG", "// Therefore the pubkey hash is the 3rd item on the stack.", "// Skip the pubkey hash if it's invalid for some reason.", "requiredSigs", "=", "1", "\n", "addr", ",", "err", ":=", "btcutil", ".", "NewAddressPubKeyHash", "(", "pops", "[", "2", "]", ".", "data", ",", "chainParams", ")", "\n", "if", "err", "==", "nil", "{", "addrs", "=", "append", "(", "addrs", ",", "addr", ")", "\n", "}", "\n\n", "case", "WitnessV0PubKeyHashTy", ":", "// A pay-to-witness-pubkey-hash script is of thw form:", "// OP_0 <20-byte hash>", "// Therefore, the pubkey hash is the second item on the stack.", "// Skip the pubkey hash if it's invalid for some reason.", "requiredSigs", "=", "1", "\n", "addr", ",", "err", ":=", "btcutil", ".", "NewAddressWitnessPubKeyHash", "(", "pops", "[", "1", "]", ".", "data", ",", "chainParams", ")", "\n", "if", "err", "==", "nil", "{", "addrs", "=", "append", "(", "addrs", ",", "addr", ")", "\n", "}", "\n\n", "case", "PubKeyTy", ":", "// A pay-to-pubkey script is of the form:", "// <pubkey> OP_CHECKSIG", "// Therefore the pubkey is the first item on the stack.", "// Skip the pubkey if it's invalid for some reason.", "requiredSigs", "=", "1", "\n", "addr", ",", "err", ":=", "btcutil", ".", "NewAddressPubKey", "(", "pops", "[", "0", "]", ".", "data", ",", "chainParams", ")", "\n", "if", "err", "==", "nil", "{", "addrs", "=", "append", "(", "addrs", ",", "addr", ")", "\n", "}", "\n\n", "case", "ScriptHashTy", ":", "// A pay-to-script-hash script is of the form:", "// OP_HASH160 <scripthash> OP_EQUAL", "// Therefore the script hash is the 2nd item on the stack.", "// Skip the script hash if it's invalid for some reason.", "requiredSigs", "=", "1", "\n", "addr", ",", "err", ":=", "btcutil", ".", "NewAddressScriptHashFromHash", "(", "pops", "[", "1", "]", ".", "data", ",", "chainParams", ")", "\n", "if", "err", "==", "nil", "{", "addrs", "=", "append", "(", "addrs", ",", "addr", ")", "\n", "}", "\n\n", "case", "WitnessV0ScriptHashTy", ":", "// A pay-to-witness-script-hash script is of the form:", "// OP_0 <32-byte hash>", "// Therefore, the script hash is the second item on the stack.", "// Skip the script hash if it's invalid for some reason.", "requiredSigs", "=", "1", "\n", "addr", ",", "err", ":=", "btcutil", ".", "NewAddressWitnessScriptHash", "(", "pops", "[", "1", "]", ".", "data", ",", "chainParams", ")", "\n", "if", "err", "==", "nil", "{", "addrs", "=", "append", "(", "addrs", ",", "addr", ")", "\n", "}", "\n\n", "case", "MultiSigTy", ":", "// A multi-signature script is of the form:", "// <numsigs> <pubkey> <pubkey> <pubkey>... <numpubkeys> OP_CHECKMULTISIG", "// Therefore the number of required signatures is the 1st item", "// on the stack and the number of public keys is the 2nd to last", "// item on the stack.", "requiredSigs", "=", "asSmallInt", "(", "pops", "[", "0", "]", ".", "opcode", ")", "\n", "numPubKeys", ":=", "asSmallInt", "(", "pops", "[", "len", "(", "pops", ")", "-", "2", "]", ".", "opcode", ")", "\n\n", "// Extract the public keys while skipping any that are invalid.", "addrs", "=", "make", "(", "[", "]", "btcutil", ".", "Address", ",", "0", ",", "numPubKeys", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "numPubKeys", ";", "i", "++", "{", "addr", ",", "err", ":=", "btcutil", ".", "NewAddressPubKey", "(", "pops", "[", "i", "+", "1", "]", ".", "data", ",", "chainParams", ")", "\n", "if", "err", "==", "nil", "{", "addrs", "=", "append", "(", "addrs", ",", "addr", ")", "\n", "}", "\n", "}", "\n\n", "case", "NullDataTy", ":", "// Null data transactions have no addresses or required", "// signatures.", "case", "NonStandardTy", ":", "// Don't attempt to extract addresses or required signatures for", "// nonstandard transactions.", "}", "\n\n", "return", "scriptClass", ",", "addrs", ",", "requiredSigs", ",", "nil", "\n", "}" ]
// ExtractPkScriptAddrs returns the type of script, addresses and required // signatures associated with the passed PkScript. Note that it only works for // 'standard' transaction script types. Any data such as public keys which are // invalid are omitted from the results.
[ "ExtractPkScriptAddrs", "returns", "the", "type", "of", "script", "addresses", "and", "required", "signatures", "associated", "with", "the", "passed", "PkScript", ".", "Note", "that", "it", "only", "works", "for", "standard", "transaction", "script", "types", ".", "Any", "data", "such", "as", "public", "keys", "which", "are", "invalid", "are", "omitted", "from", "the", "results", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/txscript/standard.go#L524-L625
train
btcsuite/btcd
btcjson/chainsvrwsntfns.go
NewFilteredBlockConnectedNtfn
func NewFilteredBlockConnectedNtfn(height int32, header string, subscribedTxs []string) *FilteredBlockConnectedNtfn { return &FilteredBlockConnectedNtfn{ Height: height, Header: header, SubscribedTxs: subscribedTxs, } }
go
func NewFilteredBlockConnectedNtfn(height int32, header string, subscribedTxs []string) *FilteredBlockConnectedNtfn { return &FilteredBlockConnectedNtfn{ Height: height, Header: header, SubscribedTxs: subscribedTxs, } }
[ "func", "NewFilteredBlockConnectedNtfn", "(", "height", "int32", ",", "header", "string", ",", "subscribedTxs", "[", "]", "string", ")", "*", "FilteredBlockConnectedNtfn", "{", "return", "&", "FilteredBlockConnectedNtfn", "{", "Height", ":", "height", ",", "Header", ":", "header", ",", "SubscribedTxs", ":", "subscribedTxs", ",", "}", "\n", "}" ]
// NewFilteredBlockConnectedNtfn returns a new instance which can be used to // issue a filteredblockconnected JSON-RPC notification.
[ "NewFilteredBlockConnectedNtfn", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "filteredblockconnected", "JSON", "-", "RPC", "notification", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/chainsvrwsntfns.go#L132-L138
train
btcsuite/btcd
btcjson/chainsvrwsntfns.go
NewFilteredBlockDisconnectedNtfn
func NewFilteredBlockDisconnectedNtfn(height int32, header string) *FilteredBlockDisconnectedNtfn { return &FilteredBlockDisconnectedNtfn{ Height: height, Header: header, } }
go
func NewFilteredBlockDisconnectedNtfn(height int32, header string) *FilteredBlockDisconnectedNtfn { return &FilteredBlockDisconnectedNtfn{ Height: height, Header: header, } }
[ "func", "NewFilteredBlockDisconnectedNtfn", "(", "height", "int32", ",", "header", "string", ")", "*", "FilteredBlockDisconnectedNtfn", "{", "return", "&", "FilteredBlockDisconnectedNtfn", "{", "Height", ":", "height", ",", "Header", ":", "header", ",", "}", "\n", "}" ]
// NewFilteredBlockDisconnectedNtfn returns a new instance which can be used to // issue a filteredblockdisconnected JSON-RPC notification.
[ "NewFilteredBlockDisconnectedNtfn", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "filteredblockdisconnected", "JSON", "-", "RPC", "notification", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/chainsvrwsntfns.go#L149-L154
train
btcsuite/btcd
btcjson/chainsvrwsntfns.go
NewTxAcceptedNtfn
func NewTxAcceptedNtfn(txHash string, amount float64) *TxAcceptedNtfn { return &TxAcceptedNtfn{ TxID: txHash, Amount: amount, } }
go
func NewTxAcceptedNtfn(txHash string, amount float64) *TxAcceptedNtfn { return &TxAcceptedNtfn{ TxID: txHash, Amount: amount, } }
[ "func", "NewTxAcceptedNtfn", "(", "txHash", "string", ",", "amount", "float64", ")", "*", "TxAcceptedNtfn", "{", "return", "&", "TxAcceptedNtfn", "{", "TxID", ":", "txHash", ",", "Amount", ":", "amount", ",", "}", "\n", "}" ]
// NewTxAcceptedNtfn returns a new instance which can be used to issue a // txaccepted JSON-RPC notification.
[ "NewTxAcceptedNtfn", "returns", "a", "new", "instance", "which", "can", "be", "used", "to", "issue", "a", "txaccepted", "JSON", "-", "RPC", "notification", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/btcjson/chainsvrwsntfns.go#L256-L261
train
btcsuite/btcd
rpcclient/rawtransactions.go
GetRawTransactionAsync
func (c *Client) GetRawTransactionAsync(txHash *chainhash.Hash) FutureGetRawTransactionResult { hash := "" if txHash != nil { hash = txHash.String() } cmd := btcjson.NewGetRawTransactionCmd(hash, btcjson.Int(0)) return c.sendCmd(cmd) }
go
func (c *Client) GetRawTransactionAsync(txHash *chainhash.Hash) FutureGetRawTransactionResult { hash := "" if txHash != nil { hash = txHash.String() } cmd := btcjson.NewGetRawTransactionCmd(hash, btcjson.Int(0)) return c.sendCmd(cmd) }
[ "func", "(", "c", "*", "Client", ")", "GetRawTransactionAsync", "(", "txHash", "*", "chainhash", ".", "Hash", ")", "FutureGetRawTransactionResult", "{", "hash", ":=", "\"", "\"", "\n", "if", "txHash", "!=", "nil", "{", "hash", "=", "txHash", ".", "String", "(", ")", "\n", "}", "\n\n", "cmd", ":=", "btcjson", ".", "NewGetRawTransactionCmd", "(", "hash", ",", "btcjson", ".", "Int", "(", "0", ")", ")", "\n", "return", "c", ".", "sendCmd", "(", "cmd", ")", "\n", "}" ]
// GetRawTransactionAsync returns an instance of a type that can be used to get // the result of the RPC at some future time by invoking the Receive function on // the returned instance. // // See GetRawTransaction for the blocking version and more details.
[ "GetRawTransactionAsync", "returns", "an", "instance", "of", "a", "type", "that", "can", "be", "used", "to", "get", "the", "result", "of", "the", "RPC", "at", "some", "future", "time", "by", "invoking", "the", "Receive", "function", "on", "the", "returned", "instance", ".", "See", "GetRawTransaction", "for", "the", "blocking", "version", "and", "more", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/rawtransactions.go#L99-L107
train
btcsuite/btcd
rpcclient/rawtransactions.go
GetRawTransaction
func (c *Client) GetRawTransaction(txHash *chainhash.Hash) (*btcutil.Tx, error) { return c.GetRawTransactionAsync(txHash).Receive() }
go
func (c *Client) GetRawTransaction(txHash *chainhash.Hash) (*btcutil.Tx, error) { return c.GetRawTransactionAsync(txHash).Receive() }
[ "func", "(", "c", "*", "Client", ")", "GetRawTransaction", "(", "txHash", "*", "chainhash", ".", "Hash", ")", "(", "*", "btcutil", ".", "Tx", ",", "error", ")", "{", "return", "c", ".", "GetRawTransactionAsync", "(", "txHash", ")", ".", "Receive", "(", ")", "\n", "}" ]
// GetRawTransaction returns a transaction given its hash. // // See GetRawTransactionVerbose to obtain additional information about the // transaction.
[ "GetRawTransaction", "returns", "a", "transaction", "given", "its", "hash", ".", "See", "GetRawTransactionVerbose", "to", "obtain", "additional", "information", "about", "the", "transaction", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/rawtransactions.go#L113-L115
train
btcsuite/btcd
rpcclient/rawtransactions.go
GetRawTransactionVerboseAsync
func (c *Client) GetRawTransactionVerboseAsync(txHash *chainhash.Hash) FutureGetRawTransactionVerboseResult { hash := "" if txHash != nil { hash = txHash.String() } cmd := btcjson.NewGetRawTransactionCmd(hash, btcjson.Int(1)) return c.sendCmd(cmd) }
go
func (c *Client) GetRawTransactionVerboseAsync(txHash *chainhash.Hash) FutureGetRawTransactionVerboseResult { hash := "" if txHash != nil { hash = txHash.String() } cmd := btcjson.NewGetRawTransactionCmd(hash, btcjson.Int(1)) return c.sendCmd(cmd) }
[ "func", "(", "c", "*", "Client", ")", "GetRawTransactionVerboseAsync", "(", "txHash", "*", "chainhash", ".", "Hash", ")", "FutureGetRawTransactionVerboseResult", "{", "hash", ":=", "\"", "\"", "\n", "if", "txHash", "!=", "nil", "{", "hash", "=", "txHash", ".", "String", "(", ")", "\n", "}", "\n\n", "cmd", ":=", "btcjson", ".", "NewGetRawTransactionCmd", "(", "hash", ",", "btcjson", ".", "Int", "(", "1", ")", ")", "\n", "return", "c", ".", "sendCmd", "(", "cmd", ")", "\n", "}" ]
// GetRawTransactionVerboseAsync returns an instance of a type that can be used // to get the result of the RPC at some future time by invoking the Receive // function on the returned instance. // // See GetRawTransactionVerbose for the blocking version and more details.
[ "GetRawTransactionVerboseAsync", "returns", "an", "instance", "of", "a", "type", "that", "can", "be", "used", "to", "get", "the", "result", "of", "the", "RPC", "at", "some", "future", "time", "by", "invoking", "the", "Receive", "function", "on", "the", "returned", "instance", ".", "See", "GetRawTransactionVerbose", "for", "the", "blocking", "version", "and", "more", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/rawtransactions.go#L145-L153
train
btcsuite/btcd
rpcclient/rawtransactions.go
GetRawTransactionVerbose
func (c *Client) GetRawTransactionVerbose(txHash *chainhash.Hash) (*btcjson.TxRawResult, error) { return c.GetRawTransactionVerboseAsync(txHash).Receive() }
go
func (c *Client) GetRawTransactionVerbose(txHash *chainhash.Hash) (*btcjson.TxRawResult, error) { return c.GetRawTransactionVerboseAsync(txHash).Receive() }
[ "func", "(", "c", "*", "Client", ")", "GetRawTransactionVerbose", "(", "txHash", "*", "chainhash", ".", "Hash", ")", "(", "*", "btcjson", ".", "TxRawResult", ",", "error", ")", "{", "return", "c", ".", "GetRawTransactionVerboseAsync", "(", "txHash", ")", ".", "Receive", "(", ")", "\n", "}" ]
// GetRawTransactionVerbose returns information about a transaction given // its hash. // // See GetRawTransaction to obtain only the transaction already deserialized.
[ "GetRawTransactionVerbose", "returns", "information", "about", "a", "transaction", "given", "its", "hash", ".", "See", "GetRawTransaction", "to", "obtain", "only", "the", "transaction", "already", "deserialized", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/rawtransactions.go#L159-L161
train
btcsuite/btcd
rpcclient/rawtransactions.go
Receive
func (r FutureDecodeRawTransactionResult) Receive() (*btcjson.TxRawResult, error) { res, err := receiveFuture(r) if err != nil { return nil, err } // Unmarshal result as a decoderawtransaction result object. var rawTxResult btcjson.TxRawResult err = json.Unmarshal(res, &rawTxResult) if err != nil { return nil, err } return &rawTxResult, nil }
go
func (r FutureDecodeRawTransactionResult) Receive() (*btcjson.TxRawResult, error) { res, err := receiveFuture(r) if err != nil { return nil, err } // Unmarshal result as a decoderawtransaction result object. var rawTxResult btcjson.TxRawResult err = json.Unmarshal(res, &rawTxResult) if err != nil { return nil, err } return &rawTxResult, nil }
[ "func", "(", "r", "FutureDecodeRawTransactionResult", ")", "Receive", "(", ")", "(", "*", "btcjson", ".", "TxRawResult", ",", "error", ")", "{", "res", ",", "err", ":=", "receiveFuture", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Unmarshal result as a decoderawtransaction result object.", "var", "rawTxResult", "btcjson", ".", "TxRawResult", "\n", "err", "=", "json", ".", "Unmarshal", "(", "res", ",", "&", "rawTxResult", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "rawTxResult", ",", "nil", "\n", "}" ]
// Receive waits for the response promised by the future and returns information // about a transaction given its serialized bytes.
[ "Receive", "waits", "for", "the", "response", "promised", "by", "the", "future", "and", "returns", "information", "about", "a", "transaction", "given", "its", "serialized", "bytes", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/rawtransactions.go#L169-L183
train
btcsuite/btcd
rpcclient/rawtransactions.go
DecodeRawTransactionAsync
func (c *Client) DecodeRawTransactionAsync(serializedTx []byte) FutureDecodeRawTransactionResult { txHex := hex.EncodeToString(serializedTx) cmd := btcjson.NewDecodeRawTransactionCmd(txHex) return c.sendCmd(cmd) }
go
func (c *Client) DecodeRawTransactionAsync(serializedTx []byte) FutureDecodeRawTransactionResult { txHex := hex.EncodeToString(serializedTx) cmd := btcjson.NewDecodeRawTransactionCmd(txHex) return c.sendCmd(cmd) }
[ "func", "(", "c", "*", "Client", ")", "DecodeRawTransactionAsync", "(", "serializedTx", "[", "]", "byte", ")", "FutureDecodeRawTransactionResult", "{", "txHex", ":=", "hex", ".", "EncodeToString", "(", "serializedTx", ")", "\n", "cmd", ":=", "btcjson", ".", "NewDecodeRawTransactionCmd", "(", "txHex", ")", "\n", "return", "c", ".", "sendCmd", "(", "cmd", ")", "\n", "}" ]
// DecodeRawTransactionAsync returns an instance of a type that can be used to // get the result of the RPC at some future time by invoking the Receive // function on the returned instance. // // See DecodeRawTransaction for the blocking version and more details.
[ "DecodeRawTransactionAsync", "returns", "an", "instance", "of", "a", "type", "that", "can", "be", "used", "to", "get", "the", "result", "of", "the", "RPC", "at", "some", "future", "time", "by", "invoking", "the", "Receive", "function", "on", "the", "returned", "instance", ".", "See", "DecodeRawTransaction", "for", "the", "blocking", "version", "and", "more", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/rawtransactions.go#L190-L194
train
btcsuite/btcd
rpcclient/rawtransactions.go
DecodeRawTransaction
func (c *Client) DecodeRawTransaction(serializedTx []byte) (*btcjson.TxRawResult, error) { return c.DecodeRawTransactionAsync(serializedTx).Receive() }
go
func (c *Client) DecodeRawTransaction(serializedTx []byte) (*btcjson.TxRawResult, error) { return c.DecodeRawTransactionAsync(serializedTx).Receive() }
[ "func", "(", "c", "*", "Client", ")", "DecodeRawTransaction", "(", "serializedTx", "[", "]", "byte", ")", "(", "*", "btcjson", ".", "TxRawResult", ",", "error", ")", "{", "return", "c", ".", "DecodeRawTransactionAsync", "(", "serializedTx", ")", ".", "Receive", "(", ")", "\n", "}" ]
// DecodeRawTransaction returns information about a transaction given its // serialized bytes.
[ "DecodeRawTransaction", "returns", "information", "about", "a", "transaction", "given", "its", "serialized", "bytes", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/rawtransactions.go#L198-L200
train
btcsuite/btcd
rpcclient/rawtransactions.go
CreateRawTransactionAsync
func (c *Client) CreateRawTransactionAsync(inputs []btcjson.TransactionInput, amounts map[btcutil.Address]btcutil.Amount, lockTime *int64) FutureCreateRawTransactionResult { convertedAmts := make(map[string]float64, len(amounts)) for addr, amount := range amounts { convertedAmts[addr.String()] = amount.ToBTC() } cmd := btcjson.NewCreateRawTransactionCmd(inputs, convertedAmts, lockTime) return c.sendCmd(cmd) }
go
func (c *Client) CreateRawTransactionAsync(inputs []btcjson.TransactionInput, amounts map[btcutil.Address]btcutil.Amount, lockTime *int64) FutureCreateRawTransactionResult { convertedAmts := make(map[string]float64, len(amounts)) for addr, amount := range amounts { convertedAmts[addr.String()] = amount.ToBTC() } cmd := btcjson.NewCreateRawTransactionCmd(inputs, convertedAmts, lockTime) return c.sendCmd(cmd) }
[ "func", "(", "c", "*", "Client", ")", "CreateRawTransactionAsync", "(", "inputs", "[", "]", "btcjson", ".", "TransactionInput", ",", "amounts", "map", "[", "btcutil", ".", "Address", "]", "btcutil", ".", "Amount", ",", "lockTime", "*", "int64", ")", "FutureCreateRawTransactionResult", "{", "convertedAmts", ":=", "make", "(", "map", "[", "string", "]", "float64", ",", "len", "(", "amounts", ")", ")", "\n", "for", "addr", ",", "amount", ":=", "range", "amounts", "{", "convertedAmts", "[", "addr", ".", "String", "(", ")", "]", "=", "amount", ".", "ToBTC", "(", ")", "\n", "}", "\n", "cmd", ":=", "btcjson", ".", "NewCreateRawTransactionCmd", "(", "inputs", ",", "convertedAmts", ",", "lockTime", ")", "\n", "return", "c", ".", "sendCmd", "(", "cmd", ")", "\n", "}" ]
// CreateRawTransactionAsync returns an instance of a type that can be used to // get the result of the RPC at some future time by invoking the Receive // function on the returned instance. // // See CreateRawTransaction for the blocking version and more details.
[ "CreateRawTransactionAsync", "returns", "an", "instance", "of", "a", "type", "that", "can", "be", "used", "to", "get", "the", "result", "of", "the", "RPC", "at", "some", "future", "time", "by", "invoking", "the", "Receive", "function", "on", "the", "returned", "instance", ".", "See", "CreateRawTransaction", "for", "the", "blocking", "version", "and", "more", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/rawtransactions.go#L241-L250
train
btcsuite/btcd
rpcclient/rawtransactions.go
CreateRawTransaction
func (c *Client) CreateRawTransaction(inputs []btcjson.TransactionInput, amounts map[btcutil.Address]btcutil.Amount, lockTime *int64) (*wire.MsgTx, error) { return c.CreateRawTransactionAsync(inputs, amounts, lockTime).Receive() }
go
func (c *Client) CreateRawTransaction(inputs []btcjson.TransactionInput, amounts map[btcutil.Address]btcutil.Amount, lockTime *int64) (*wire.MsgTx, error) { return c.CreateRawTransactionAsync(inputs, amounts, lockTime).Receive() }
[ "func", "(", "c", "*", "Client", ")", "CreateRawTransaction", "(", "inputs", "[", "]", "btcjson", ".", "TransactionInput", ",", "amounts", "map", "[", "btcutil", ".", "Address", "]", "btcutil", ".", "Amount", ",", "lockTime", "*", "int64", ")", "(", "*", "wire", ".", "MsgTx", ",", "error", ")", "{", "return", "c", ".", "CreateRawTransactionAsync", "(", "inputs", ",", "amounts", ",", "lockTime", ")", ".", "Receive", "(", ")", "\n", "}" ]
// CreateRawTransaction returns a new transaction spending the provided inputs // and sending to the provided addresses.
[ "CreateRawTransaction", "returns", "a", "new", "transaction", "spending", "the", "provided", "inputs", "and", "sending", "to", "the", "provided", "addresses", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/rawtransactions.go#L254-L258
train
btcsuite/btcd
rpcclient/rawtransactions.go
Receive
func (r FutureSendRawTransactionResult) Receive() (*chainhash.Hash, error) { res, err := receiveFuture(r) if err != nil { return nil, err } // Unmarshal result as a string. var txHashStr string err = json.Unmarshal(res, &txHashStr) if err != nil { return nil, err } return chainhash.NewHashFromStr(txHashStr) }
go
func (r FutureSendRawTransactionResult) Receive() (*chainhash.Hash, error) { res, err := receiveFuture(r) if err != nil { return nil, err } // Unmarshal result as a string. var txHashStr string err = json.Unmarshal(res, &txHashStr) if err != nil { return nil, err } return chainhash.NewHashFromStr(txHashStr) }
[ "func", "(", "r", "FutureSendRawTransactionResult", ")", "Receive", "(", ")", "(", "*", "chainhash", ".", "Hash", ",", "error", ")", "{", "res", ",", "err", ":=", "receiveFuture", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Unmarshal result as a string.", "var", "txHashStr", "string", "\n", "err", "=", "json", ".", "Unmarshal", "(", "res", ",", "&", "txHashStr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "chainhash", ".", "NewHashFromStr", "(", "txHashStr", ")", "\n", "}" ]
// Receive waits for the response promised by the future and returns the result // of submitting the encoded transaction to the server which then relays it to // the network.
[ "Receive", "waits", "for", "the", "response", "promised", "by", "the", "future", "and", "returns", "the", "result", "of", "submitting", "the", "encoded", "transaction", "to", "the", "server", "which", "then", "relays", "it", "to", "the", "network", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/rawtransactions.go#L267-L281
train
btcsuite/btcd
rpcclient/rawtransactions.go
SendRawTransactionAsync
func (c *Client) SendRawTransactionAsync(tx *wire.MsgTx, allowHighFees bool) FutureSendRawTransactionResult { txHex := "" if tx != nil { // Serialize the transaction and convert to hex string. buf := bytes.NewBuffer(make([]byte, 0, tx.SerializeSize())) if err := tx.Serialize(buf); err != nil { return newFutureError(err) } txHex = hex.EncodeToString(buf.Bytes()) } cmd := btcjson.NewSendRawTransactionCmd(txHex, &allowHighFees) return c.sendCmd(cmd) }
go
func (c *Client) SendRawTransactionAsync(tx *wire.MsgTx, allowHighFees bool) FutureSendRawTransactionResult { txHex := "" if tx != nil { // Serialize the transaction and convert to hex string. buf := bytes.NewBuffer(make([]byte, 0, tx.SerializeSize())) if err := tx.Serialize(buf); err != nil { return newFutureError(err) } txHex = hex.EncodeToString(buf.Bytes()) } cmd := btcjson.NewSendRawTransactionCmd(txHex, &allowHighFees) return c.sendCmd(cmd) }
[ "func", "(", "c", "*", "Client", ")", "SendRawTransactionAsync", "(", "tx", "*", "wire", ".", "MsgTx", ",", "allowHighFees", "bool", ")", "FutureSendRawTransactionResult", "{", "txHex", ":=", "\"", "\"", "\n", "if", "tx", "!=", "nil", "{", "// Serialize the transaction and convert to hex string.", "buf", ":=", "bytes", ".", "NewBuffer", "(", "make", "(", "[", "]", "byte", ",", "0", ",", "tx", ".", "SerializeSize", "(", ")", ")", ")", "\n", "if", "err", ":=", "tx", ".", "Serialize", "(", "buf", ")", ";", "err", "!=", "nil", "{", "return", "newFutureError", "(", "err", ")", "\n", "}", "\n", "txHex", "=", "hex", ".", "EncodeToString", "(", "buf", ".", "Bytes", "(", ")", ")", "\n", "}", "\n\n", "cmd", ":=", "btcjson", ".", "NewSendRawTransactionCmd", "(", "txHex", ",", "&", "allowHighFees", ")", "\n", "return", "c", ".", "sendCmd", "(", "cmd", ")", "\n", "}" ]
// SendRawTransactionAsync returns an instance of a type that can be used to get // the result of the RPC at some future time by invoking the Receive function on // the returned instance. // // See SendRawTransaction for the blocking version and more details.
[ "SendRawTransactionAsync", "returns", "an", "instance", "of", "a", "type", "that", "can", "be", "used", "to", "get", "the", "result", "of", "the", "RPC", "at", "some", "future", "time", "by", "invoking", "the", "Receive", "function", "on", "the", "returned", "instance", ".", "See", "SendRawTransaction", "for", "the", "blocking", "version", "and", "more", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/rawtransactions.go#L288-L301
train
btcsuite/btcd
rpcclient/rawtransactions.go
SendRawTransaction
func (c *Client) SendRawTransaction(tx *wire.MsgTx, allowHighFees bool) (*chainhash.Hash, error) { return c.SendRawTransactionAsync(tx, allowHighFees).Receive() }
go
func (c *Client) SendRawTransaction(tx *wire.MsgTx, allowHighFees bool) (*chainhash.Hash, error) { return c.SendRawTransactionAsync(tx, allowHighFees).Receive() }
[ "func", "(", "c", "*", "Client", ")", "SendRawTransaction", "(", "tx", "*", "wire", ".", "MsgTx", ",", "allowHighFees", "bool", ")", "(", "*", "chainhash", ".", "Hash", ",", "error", ")", "{", "return", "c", ".", "SendRawTransactionAsync", "(", "tx", ",", "allowHighFees", ")", ".", "Receive", "(", ")", "\n", "}" ]
// SendRawTransaction submits the encoded transaction to the server which will // then relay it to the network.
[ "SendRawTransaction", "submits", "the", "encoded", "transaction", "to", "the", "server", "which", "will", "then", "relay", "it", "to", "the", "network", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/rawtransactions.go#L305-L307
train
btcsuite/btcd
rpcclient/rawtransactions.go
Receive
func (r FutureSignRawTransactionResult) Receive() (*wire.MsgTx, bool, error) { res, err := receiveFuture(r) if err != nil { return nil, false, err } // Unmarshal as a signrawtransaction result. var signRawTxResult btcjson.SignRawTransactionResult err = json.Unmarshal(res, &signRawTxResult) if err != nil { return nil, false, err } // Decode the serialized transaction hex to raw bytes. serializedTx, err := hex.DecodeString(signRawTxResult.Hex) if err != nil { return nil, false, err } // Deserialize the transaction and return it. var msgTx wire.MsgTx if err := msgTx.Deserialize(bytes.NewReader(serializedTx)); err != nil { return nil, false, err } return &msgTx, signRawTxResult.Complete, nil }
go
func (r FutureSignRawTransactionResult) Receive() (*wire.MsgTx, bool, error) { res, err := receiveFuture(r) if err != nil { return nil, false, err } // Unmarshal as a signrawtransaction result. var signRawTxResult btcjson.SignRawTransactionResult err = json.Unmarshal(res, &signRawTxResult) if err != nil { return nil, false, err } // Decode the serialized transaction hex to raw bytes. serializedTx, err := hex.DecodeString(signRawTxResult.Hex) if err != nil { return nil, false, err } // Deserialize the transaction and return it. var msgTx wire.MsgTx if err := msgTx.Deserialize(bytes.NewReader(serializedTx)); err != nil { return nil, false, err } return &msgTx, signRawTxResult.Complete, nil }
[ "func", "(", "r", "FutureSignRawTransactionResult", ")", "Receive", "(", ")", "(", "*", "wire", ".", "MsgTx", ",", "bool", ",", "error", ")", "{", "res", ",", "err", ":=", "receiveFuture", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "false", ",", "err", "\n", "}", "\n\n", "// Unmarshal as a signrawtransaction result.", "var", "signRawTxResult", "btcjson", ".", "SignRawTransactionResult", "\n", "err", "=", "json", ".", "Unmarshal", "(", "res", ",", "&", "signRawTxResult", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "false", ",", "err", "\n", "}", "\n\n", "// Decode the serialized transaction hex to raw bytes.", "serializedTx", ",", "err", ":=", "hex", ".", "DecodeString", "(", "signRawTxResult", ".", "Hex", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "false", ",", "err", "\n", "}", "\n\n", "// Deserialize the transaction and return it.", "var", "msgTx", "wire", ".", "MsgTx", "\n", "if", "err", ":=", "msgTx", ".", "Deserialize", "(", "bytes", ".", "NewReader", "(", "serializedTx", ")", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "false", ",", "err", "\n", "}", "\n\n", "return", "&", "msgTx", ",", "signRawTxResult", ".", "Complete", ",", "nil", "\n", "}" ]
// Receive waits for the response promised by the future and returns the // signed transaction as well as whether or not all inputs are now signed.
[ "Receive", "waits", "for", "the", "response", "promised", "by", "the", "future", "and", "returns", "the", "signed", "transaction", "as", "well", "as", "whether", "or", "not", "all", "inputs", "are", "now", "signed", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/rawtransactions.go#L316-L342
train
btcsuite/btcd
rpcclient/rawtransactions.go
SignRawTransaction2
func (c *Client) SignRawTransaction2(tx *wire.MsgTx, inputs []btcjson.RawTxInput) (*wire.MsgTx, bool, error) { return c.SignRawTransaction2Async(tx, inputs).Receive() }
go
func (c *Client) SignRawTransaction2(tx *wire.MsgTx, inputs []btcjson.RawTxInput) (*wire.MsgTx, bool, error) { return c.SignRawTransaction2Async(tx, inputs).Receive() }
[ "func", "(", "c", "*", "Client", ")", "SignRawTransaction2", "(", "tx", "*", "wire", ".", "MsgTx", ",", "inputs", "[", "]", "btcjson", ".", "RawTxInput", ")", "(", "*", "wire", ".", "MsgTx", ",", "bool", ",", "error", ")", "{", "return", "c", ".", "SignRawTransaction2Async", "(", "tx", ",", "inputs", ")", ".", "Receive", "(", ")", "\n", "}" ]
// SignRawTransaction2 signs inputs for the passed transaction given the list // of information about the input transactions needed to perform the signing // process. // // This only input transactions that need to be specified are ones the // RPC server does not already know. Already known input transactions will be // merged with the specified transactions. // // See SignRawTransaction if the RPC server already knows the input // transactions.
[ "SignRawTransaction2", "signs", "inputs", "for", "the", "passed", "transaction", "given", "the", "list", "of", "information", "about", "the", "input", "transactions", "needed", "to", "perform", "the", "signing", "process", ".", "This", "only", "input", "transactions", "that", "need", "to", "be", "specified", "are", "ones", "the", "RPC", "server", "does", "not", "already", "know", ".", "Already", "known", "input", "transactions", "will", "be", "merged", "with", "the", "specified", "transactions", ".", "See", "SignRawTransaction", "if", "the", "RPC", "server", "already", "knows", "the", "input", "transactions", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/rawtransactions.go#L405-L407
train
btcsuite/btcd
rpcclient/rawtransactions.go
SignRawTransaction3Async
func (c *Client) SignRawTransaction3Async(tx *wire.MsgTx, inputs []btcjson.RawTxInput, privKeysWIF []string) FutureSignRawTransactionResult { txHex := "" if tx != nil { // Serialize the transaction and convert to hex string. buf := bytes.NewBuffer(make([]byte, 0, tx.SerializeSize())) if err := tx.Serialize(buf); err != nil { return newFutureError(err) } txHex = hex.EncodeToString(buf.Bytes()) } cmd := btcjson.NewSignRawTransactionCmd(txHex, &inputs, &privKeysWIF, nil) return c.sendCmd(cmd) }
go
func (c *Client) SignRawTransaction3Async(tx *wire.MsgTx, inputs []btcjson.RawTxInput, privKeysWIF []string) FutureSignRawTransactionResult { txHex := "" if tx != nil { // Serialize the transaction and convert to hex string. buf := bytes.NewBuffer(make([]byte, 0, tx.SerializeSize())) if err := tx.Serialize(buf); err != nil { return newFutureError(err) } txHex = hex.EncodeToString(buf.Bytes()) } cmd := btcjson.NewSignRawTransactionCmd(txHex, &inputs, &privKeysWIF, nil) return c.sendCmd(cmd) }
[ "func", "(", "c", "*", "Client", ")", "SignRawTransaction3Async", "(", "tx", "*", "wire", ".", "MsgTx", ",", "inputs", "[", "]", "btcjson", ".", "RawTxInput", ",", "privKeysWIF", "[", "]", "string", ")", "FutureSignRawTransactionResult", "{", "txHex", ":=", "\"", "\"", "\n", "if", "tx", "!=", "nil", "{", "// Serialize the transaction and convert to hex string.", "buf", ":=", "bytes", ".", "NewBuffer", "(", "make", "(", "[", "]", "byte", ",", "0", ",", "tx", ".", "SerializeSize", "(", ")", ")", ")", "\n", "if", "err", ":=", "tx", ".", "Serialize", "(", "buf", ")", ";", "err", "!=", "nil", "{", "return", "newFutureError", "(", "err", ")", "\n", "}", "\n", "txHex", "=", "hex", ".", "EncodeToString", "(", "buf", ".", "Bytes", "(", ")", ")", "\n", "}", "\n\n", "cmd", ":=", "btcjson", ".", "NewSignRawTransactionCmd", "(", "txHex", ",", "&", "inputs", ",", "&", "privKeysWIF", ",", "nil", ")", "\n", "return", "c", ".", "sendCmd", "(", "cmd", ")", "\n", "}" ]
// SignRawTransaction3Async returns an instance of a type that can be used to // get the result of the RPC at some future time by invoking the Receive // function on the returned instance. // // See SignRawTransaction3 for the blocking version and more details.
[ "SignRawTransaction3Async", "returns", "an", "instance", "of", "a", "type", "that", "can", "be", "used", "to", "get", "the", "result", "of", "the", "RPC", "at", "some", "future", "time", "by", "invoking", "the", "Receive", "function", "on", "the", "returned", "instance", ".", "See", "SignRawTransaction3", "for", "the", "blocking", "version", "and", "more", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/rawtransactions.go#L414-L431
train
btcsuite/btcd
rpcclient/rawtransactions.go
SearchRawTransactionsAsync
func (c *Client) SearchRawTransactionsAsync(address btcutil.Address, skip, count int, reverse bool, filterAddrs []string) FutureSearchRawTransactionsResult { addr := address.EncodeAddress() verbose := btcjson.Int(0) cmd := btcjson.NewSearchRawTransactionsCmd(addr, verbose, &skip, &count, nil, &reverse, &filterAddrs) return c.sendCmd(cmd) }
go
func (c *Client) SearchRawTransactionsAsync(address btcutil.Address, skip, count int, reverse bool, filterAddrs []string) FutureSearchRawTransactionsResult { addr := address.EncodeAddress() verbose := btcjson.Int(0) cmd := btcjson.NewSearchRawTransactionsCmd(addr, verbose, &skip, &count, nil, &reverse, &filterAddrs) return c.sendCmd(cmd) }
[ "func", "(", "c", "*", "Client", ")", "SearchRawTransactionsAsync", "(", "address", "btcutil", ".", "Address", ",", "skip", ",", "count", "int", ",", "reverse", "bool", ",", "filterAddrs", "[", "]", "string", ")", "FutureSearchRawTransactionsResult", "{", "addr", ":=", "address", ".", "EncodeAddress", "(", ")", "\n", "verbose", ":=", "btcjson", ".", "Int", "(", "0", ")", "\n", "cmd", ":=", "btcjson", ".", "NewSearchRawTransactionsCmd", "(", "addr", ",", "verbose", ",", "&", "skip", ",", "&", "count", ",", "nil", ",", "&", "reverse", ",", "&", "filterAddrs", ")", "\n", "return", "c", ".", "sendCmd", "(", "cmd", ")", "\n", "}" ]
// SearchRawTransactionsAsync returns an instance of a type that can be used to // get the result of the RPC at some future time by invoking the Receive // function on the returned instance. // // See SearchRawTransactions for the blocking version and more details.
[ "SearchRawTransactionsAsync", "returns", "an", "instance", "of", "a", "type", "that", "can", "be", "used", "to", "get", "the", "result", "of", "the", "RPC", "at", "some", "future", "time", "by", "invoking", "the", "Receive", "function", "on", "the", "returned", "instance", ".", "See", "SearchRawTransactions", "for", "the", "blocking", "version", "and", "more", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/rawtransactions.go#L553-L559
train
btcsuite/btcd
rpcclient/rawtransactions.go
SearchRawTransactionsVerboseAsync
func (c *Client) SearchRawTransactionsVerboseAsync(address btcutil.Address, skip, count int, includePrevOut, reverse bool, filterAddrs *[]string) FutureSearchRawTransactionsVerboseResult { addr := address.EncodeAddress() verbose := btcjson.Int(1) var prevOut *int if includePrevOut { prevOut = btcjson.Int(1) } cmd := btcjson.NewSearchRawTransactionsCmd(addr, verbose, &skip, &count, prevOut, &reverse, filterAddrs) return c.sendCmd(cmd) }
go
func (c *Client) SearchRawTransactionsVerboseAsync(address btcutil.Address, skip, count int, includePrevOut, reverse bool, filterAddrs *[]string) FutureSearchRawTransactionsVerboseResult { addr := address.EncodeAddress() verbose := btcjson.Int(1) var prevOut *int if includePrevOut { prevOut = btcjson.Int(1) } cmd := btcjson.NewSearchRawTransactionsCmd(addr, verbose, &skip, &count, prevOut, &reverse, filterAddrs) return c.sendCmd(cmd) }
[ "func", "(", "c", "*", "Client", ")", "SearchRawTransactionsVerboseAsync", "(", "address", "btcutil", ".", "Address", ",", "skip", ",", "count", "int", ",", "includePrevOut", ",", "reverse", "bool", ",", "filterAddrs", "*", "[", "]", "string", ")", "FutureSearchRawTransactionsVerboseResult", "{", "addr", ":=", "address", ".", "EncodeAddress", "(", ")", "\n", "verbose", ":=", "btcjson", ".", "Int", "(", "1", ")", "\n", "var", "prevOut", "*", "int", "\n", "if", "includePrevOut", "{", "prevOut", "=", "btcjson", ".", "Int", "(", "1", ")", "\n", "}", "\n", "cmd", ":=", "btcjson", ".", "NewSearchRawTransactionsCmd", "(", "addr", ",", "verbose", ",", "&", "skip", ",", "&", "count", ",", "prevOut", ",", "&", "reverse", ",", "filterAddrs", ")", "\n", "return", "c", ".", "sendCmd", "(", "cmd", ")", "\n", "}" ]
// SearchRawTransactionsVerboseAsync returns an instance of a type that can be // used to get the result of the RPC at some future time by invoking the Receive // function on the returned instance. // // See SearchRawTransactionsVerbose for the blocking version and more details.
[ "SearchRawTransactionsVerboseAsync", "returns", "an", "instance", "of", "a", "type", "that", "can", "be", "used", "to", "get", "the", "result", "of", "the", "RPC", "at", "some", "future", "time", "by", "invoking", "the", "Receive", "function", "on", "the", "returned", "instance", ".", "See", "SearchRawTransactionsVerbose", "for", "the", "blocking", "version", "and", "more", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/rawtransactions.go#L600-L612
train
btcsuite/btcd
rpcclient/rawtransactions.go
Receive
func (r FutureDecodeScriptResult) Receive() (*btcjson.DecodeScriptResult, error) { res, err := receiveFuture(r) if err != nil { return nil, err } // Unmarshal result as a decodescript result object. var decodeScriptResult btcjson.DecodeScriptResult err = json.Unmarshal(res, &decodeScriptResult) if err != nil { return nil, err } return &decodeScriptResult, nil }
go
func (r FutureDecodeScriptResult) Receive() (*btcjson.DecodeScriptResult, error) { res, err := receiveFuture(r) if err != nil { return nil, err } // Unmarshal result as a decodescript result object. var decodeScriptResult btcjson.DecodeScriptResult err = json.Unmarshal(res, &decodeScriptResult) if err != nil { return nil, err } return &decodeScriptResult, nil }
[ "func", "(", "r", "FutureDecodeScriptResult", ")", "Receive", "(", ")", "(", "*", "btcjson", ".", "DecodeScriptResult", ",", "error", ")", "{", "res", ",", "err", ":=", "receiveFuture", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Unmarshal result as a decodescript result object.", "var", "decodeScriptResult", "btcjson", ".", "DecodeScriptResult", "\n", "err", "=", "json", ".", "Unmarshal", "(", "res", ",", "&", "decodeScriptResult", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "decodeScriptResult", ",", "nil", "\n", "}" ]
// Receive waits for the response promised by the future and returns information // about a script given its serialized bytes.
[ "Receive", "waits", "for", "the", "response", "promised", "by", "the", "future", "and", "returns", "information", "about", "a", "script", "given", "its", "serialized", "bytes", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/rawtransactions.go#L634-L648
train
btcsuite/btcd
rpcclient/rawtransactions.go
DecodeScriptAsync
func (c *Client) DecodeScriptAsync(serializedScript []byte) FutureDecodeScriptResult { scriptHex := hex.EncodeToString(serializedScript) cmd := btcjson.NewDecodeScriptCmd(scriptHex) return c.sendCmd(cmd) }
go
func (c *Client) DecodeScriptAsync(serializedScript []byte) FutureDecodeScriptResult { scriptHex := hex.EncodeToString(serializedScript) cmd := btcjson.NewDecodeScriptCmd(scriptHex) return c.sendCmd(cmd) }
[ "func", "(", "c", "*", "Client", ")", "DecodeScriptAsync", "(", "serializedScript", "[", "]", "byte", ")", "FutureDecodeScriptResult", "{", "scriptHex", ":=", "hex", ".", "EncodeToString", "(", "serializedScript", ")", "\n", "cmd", ":=", "btcjson", ".", "NewDecodeScriptCmd", "(", "scriptHex", ")", "\n", "return", "c", ".", "sendCmd", "(", "cmd", ")", "\n", "}" ]
// DecodeScriptAsync returns an instance of a type that can be used to // get the result of the RPC at some future time by invoking the Receive // function on the returned instance. // // See DecodeScript for the blocking version and more details.
[ "DecodeScriptAsync", "returns", "an", "instance", "of", "a", "type", "that", "can", "be", "used", "to", "get", "the", "result", "of", "the", "RPC", "at", "some", "future", "time", "by", "invoking", "the", "Receive", "function", "on", "the", "returned", "instance", ".", "See", "DecodeScript", "for", "the", "blocking", "version", "and", "more", "details", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/rawtransactions.go#L655-L659
train
btcsuite/btcd
rpcclient/rawtransactions.go
DecodeScript
func (c *Client) DecodeScript(serializedScript []byte) (*btcjson.DecodeScriptResult, error) { return c.DecodeScriptAsync(serializedScript).Receive() }
go
func (c *Client) DecodeScript(serializedScript []byte) (*btcjson.DecodeScriptResult, error) { return c.DecodeScriptAsync(serializedScript).Receive() }
[ "func", "(", "c", "*", "Client", ")", "DecodeScript", "(", "serializedScript", "[", "]", "byte", ")", "(", "*", "btcjson", ".", "DecodeScriptResult", ",", "error", ")", "{", "return", "c", ".", "DecodeScriptAsync", "(", "serializedScript", ")", ".", "Receive", "(", ")", "\n", "}" ]
// DecodeScript returns information about a script given its serialized bytes.
[ "DecodeScript", "returns", "information", "about", "a", "script", "given", "its", "serialized", "bytes", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/rpcclient/rawtransactions.go#L662-L664
train
btcsuite/btcd
database/ffldb/dbcache.go
newLdbCacheIter
func newLdbCacheIter(snap *dbCacheSnapshot, slice *util.Range) *ldbCacheIter { iter := snap.pendingKeys.Iterator(slice.Start, slice.Limit) return &ldbCacheIter{Iterator: iter} }
go
func newLdbCacheIter(snap *dbCacheSnapshot, slice *util.Range) *ldbCacheIter { iter := snap.pendingKeys.Iterator(slice.Start, slice.Limit) return &ldbCacheIter{Iterator: iter} }
[ "func", "newLdbCacheIter", "(", "snap", "*", "dbCacheSnapshot", ",", "slice", "*", "util", ".", "Range", ")", "*", "ldbCacheIter", "{", "iter", ":=", "snap", ".", "pendingKeys", ".", "Iterator", "(", "slice", ".", "Start", ",", "slice", ".", "Limit", ")", "\n", "return", "&", "ldbCacheIter", "{", "Iterator", ":", "iter", "}", "\n", "}" ]
// newLdbCacheIter creates a new treap iterator for the given slice against the // pending keys for the passed cache snapshot and returns it wrapped in an // ldbCacheIter so it can be used as a leveldb iterator.
[ "newLdbCacheIter", "creates", "a", "new", "treap", "iterator", "for", "the", "given", "slice", "against", "the", "pending", "keys", "for", "the", "passed", "cache", "snapshot", "and", "returns", "it", "wrapped", "in", "an", "ldbCacheIter", "so", "it", "can", "be", "used", "as", "a", "leveldb", "iterator", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/dbcache.go#L75-L78
train
btcsuite/btcd
database/ffldb/dbcache.go
skipPendingUpdates
func (iter *dbCacheIterator) skipPendingUpdates(forwards bool) { for iter.dbIter.Valid() { var skip bool key := iter.dbIter.Key() if iter.cacheSnapshot.pendingRemove.Has(key) { skip = true } else if iter.cacheSnapshot.pendingKeys.Has(key) { skip = true } if !skip { break } if forwards { iter.dbIter.Next() } else { iter.dbIter.Prev() } } }
go
func (iter *dbCacheIterator) skipPendingUpdates(forwards bool) { for iter.dbIter.Valid() { var skip bool key := iter.dbIter.Key() if iter.cacheSnapshot.pendingRemove.Has(key) { skip = true } else if iter.cacheSnapshot.pendingKeys.Has(key) { skip = true } if !skip { break } if forwards { iter.dbIter.Next() } else { iter.dbIter.Prev() } } }
[ "func", "(", "iter", "*", "dbCacheIterator", ")", "skipPendingUpdates", "(", "forwards", "bool", ")", "{", "for", "iter", ".", "dbIter", ".", "Valid", "(", ")", "{", "var", "skip", "bool", "\n", "key", ":=", "iter", ".", "dbIter", ".", "Key", "(", ")", "\n", "if", "iter", ".", "cacheSnapshot", ".", "pendingRemove", ".", "Has", "(", "key", ")", "{", "skip", "=", "true", "\n", "}", "else", "if", "iter", ".", "cacheSnapshot", ".", "pendingKeys", ".", "Has", "(", "key", ")", "{", "skip", "=", "true", "\n", "}", "\n", "if", "!", "skip", "{", "break", "\n", "}", "\n\n", "if", "forwards", "{", "iter", ".", "dbIter", ".", "Next", "(", ")", "\n", "}", "else", "{", "iter", ".", "dbIter", ".", "Prev", "(", ")", "\n", "}", "\n", "}", "\n", "}" ]
// skipPendingUpdates skips any keys at the current database iterator position // that are being updated by the cache. The forwards flag indicates the // direction the iterator is moving.
[ "skipPendingUpdates", "skips", "any", "keys", "at", "the", "current", "database", "iterator", "position", "that", "are", "being", "updated", "by", "the", "cache", ".", "The", "forwards", "flag", "indicates", "the", "direction", "the", "iterator", "is", "moving", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/dbcache.go#L96-L115
train
btcsuite/btcd
database/ffldb/dbcache.go
chooseIterator
func (iter *dbCacheIterator) chooseIterator(forwards bool) bool { // Skip any keys at the current database iterator position that are // being updated by the cache. iter.skipPendingUpdates(forwards) // When both iterators are exhausted, the iterator is exhausted too. if !iter.dbIter.Valid() && !iter.cacheIter.Valid() { iter.currentIter = nil return false } // Choose the database iterator when the cache iterator is exhausted. if !iter.cacheIter.Valid() { iter.currentIter = iter.dbIter return true } // Choose the cache iterator when the database iterator is exhausted. if !iter.dbIter.Valid() { iter.currentIter = iter.cacheIter return true } // Both iterators are valid, so choose the iterator with either the // smaller or larger key depending on the forwards flag. compare := bytes.Compare(iter.dbIter.Key(), iter.cacheIter.Key()) if (forwards && compare > 0) || (!forwards && compare < 0) { iter.currentIter = iter.cacheIter } else { iter.currentIter = iter.dbIter } return true }
go
func (iter *dbCacheIterator) chooseIterator(forwards bool) bool { // Skip any keys at the current database iterator position that are // being updated by the cache. iter.skipPendingUpdates(forwards) // When both iterators are exhausted, the iterator is exhausted too. if !iter.dbIter.Valid() && !iter.cacheIter.Valid() { iter.currentIter = nil return false } // Choose the database iterator when the cache iterator is exhausted. if !iter.cacheIter.Valid() { iter.currentIter = iter.dbIter return true } // Choose the cache iterator when the database iterator is exhausted. if !iter.dbIter.Valid() { iter.currentIter = iter.cacheIter return true } // Both iterators are valid, so choose the iterator with either the // smaller or larger key depending on the forwards flag. compare := bytes.Compare(iter.dbIter.Key(), iter.cacheIter.Key()) if (forwards && compare > 0) || (!forwards && compare < 0) { iter.currentIter = iter.cacheIter } else { iter.currentIter = iter.dbIter } return true }
[ "func", "(", "iter", "*", "dbCacheIterator", ")", "chooseIterator", "(", "forwards", "bool", ")", "bool", "{", "// Skip any keys at the current database iterator position that are", "// being updated by the cache.", "iter", ".", "skipPendingUpdates", "(", "forwards", ")", "\n\n", "// When both iterators are exhausted, the iterator is exhausted too.", "if", "!", "iter", ".", "dbIter", ".", "Valid", "(", ")", "&&", "!", "iter", ".", "cacheIter", ".", "Valid", "(", ")", "{", "iter", ".", "currentIter", "=", "nil", "\n", "return", "false", "\n", "}", "\n\n", "// Choose the database iterator when the cache iterator is exhausted.", "if", "!", "iter", ".", "cacheIter", ".", "Valid", "(", ")", "{", "iter", ".", "currentIter", "=", "iter", ".", "dbIter", "\n", "return", "true", "\n", "}", "\n\n", "// Choose the cache iterator when the database iterator is exhausted.", "if", "!", "iter", ".", "dbIter", ".", "Valid", "(", ")", "{", "iter", ".", "currentIter", "=", "iter", ".", "cacheIter", "\n", "return", "true", "\n", "}", "\n\n", "// Both iterators are valid, so choose the iterator with either the", "// smaller or larger key depending on the forwards flag.", "compare", ":=", "bytes", ".", "Compare", "(", "iter", ".", "dbIter", ".", "Key", "(", ")", ",", "iter", ".", "cacheIter", ".", "Key", "(", ")", ")", "\n", "if", "(", "forwards", "&&", "compare", ">", "0", ")", "||", "(", "!", "forwards", "&&", "compare", "<", "0", ")", "{", "iter", ".", "currentIter", "=", "iter", ".", "cacheIter", "\n", "}", "else", "{", "iter", ".", "currentIter", "=", "iter", ".", "dbIter", "\n", "}", "\n", "return", "true", "\n", "}" ]
// chooseIterator first skips any entries in the database iterator that are // being updated by the cache and sets the current iterator to the appropriate // iterator depending on their validity and the order they compare in while taking // into account the direction flag. When the iterator is being moved forwards // and both iterators are valid, the iterator with the smaller key is chosen and // vice versa when the iterator is being moved backwards.
[ "chooseIterator", "first", "skips", "any", "entries", "in", "the", "database", "iterator", "that", "are", "being", "updated", "by", "the", "cache", "and", "sets", "the", "current", "iterator", "to", "the", "appropriate", "iterator", "depending", "on", "their", "validity", "and", "the", "order", "they", "compare", "in", "while", "taking", "into", "account", "the", "direction", "flag", ".", "When", "the", "iterator", "is", "being", "moved", "forwards", "and", "both", "iterators", "are", "valid", "the", "iterator", "with", "the", "smaller", "key", "is", "chosen", "and", "vice", "versa", "when", "the", "iterator", "is", "being", "moved", "backwards", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/dbcache.go#L123-L155
train
btcsuite/btcd
database/ffldb/dbcache.go
Key
func (iter *dbCacheIterator) Key() []byte { // Nothing to return if iterator is exhausted. if iter.currentIter == nil { return nil } return iter.currentIter.Key() }
go
func (iter *dbCacheIterator) Key() []byte { // Nothing to return if iterator is exhausted. if iter.currentIter == nil { return nil } return iter.currentIter.Key() }
[ "func", "(", "iter", "*", "dbCacheIterator", ")", "Key", "(", ")", "[", "]", "byte", "{", "// Nothing to return if iterator is exhausted.", "if", "iter", ".", "currentIter", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "return", "iter", ".", "currentIter", ".", "Key", "(", ")", "\n", "}" ]
// Key returns the current key the iterator is pointing to. // // This is part of the leveldb iterator.Iterator interface implementation.
[ "Key", "returns", "the", "current", "key", "the", "iterator", "is", "pointing", "to", ".", "This", "is", "part", "of", "the", "leveldb", "iterator", ".", "Iterator", "interface", "implementation", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/dbcache.go#L236-L243
train
btcsuite/btcd
database/ffldb/dbcache.go
Value
func (iter *dbCacheIterator) Value() []byte { // Nothing to return if iterator is exhausted. if iter.currentIter == nil { return nil } return iter.currentIter.Value() }
go
func (iter *dbCacheIterator) Value() []byte { // Nothing to return if iterator is exhausted. if iter.currentIter == nil { return nil } return iter.currentIter.Value() }
[ "func", "(", "iter", "*", "dbCacheIterator", ")", "Value", "(", ")", "[", "]", "byte", "{", "// Nothing to return if iterator is exhausted.", "if", "iter", ".", "currentIter", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "return", "iter", ".", "currentIter", ".", "Value", "(", ")", "\n", "}" ]
// Value returns the current value the iterator is pointing to. // // This is part of the leveldb iterator.Iterator interface implementation.
[ "Value", "returns", "the", "current", "value", "the", "iterator", "is", "pointing", "to", ".", "This", "is", "part", "of", "the", "leveldb", "iterator", ".", "Iterator", "interface", "implementation", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/dbcache.go#L248-L255
train
btcsuite/btcd
database/ffldb/dbcache.go
Release
func (snap *dbCacheSnapshot) Release() { snap.dbSnapshot.Release() snap.pendingKeys = nil snap.pendingRemove = nil }
go
func (snap *dbCacheSnapshot) Release() { snap.dbSnapshot.Release() snap.pendingKeys = nil snap.pendingRemove = nil }
[ "func", "(", "snap", "*", "dbCacheSnapshot", ")", "Release", "(", ")", "{", "snap", ".", "dbSnapshot", ".", "Release", "(", ")", "\n", "snap", ".", "pendingKeys", "=", "nil", "\n", "snap", ".", "pendingRemove", "=", "nil", "\n", "}" ]
// Release releases the snapshot.
[ "Release", "releases", "the", "snapshot", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/dbcache.go#L328-L332
train
btcsuite/btcd
database/ffldb/dbcache.go
NewIterator
func (snap *dbCacheSnapshot) NewIterator(slice *util.Range) *dbCacheIterator { return &dbCacheIterator{ dbIter: snap.dbSnapshot.NewIterator(slice, nil), cacheIter: newLdbCacheIter(snap, slice), cacheSnapshot: snap, } }
go
func (snap *dbCacheSnapshot) NewIterator(slice *util.Range) *dbCacheIterator { return &dbCacheIterator{ dbIter: snap.dbSnapshot.NewIterator(slice, nil), cacheIter: newLdbCacheIter(snap, slice), cacheSnapshot: snap, } }
[ "func", "(", "snap", "*", "dbCacheSnapshot", ")", "NewIterator", "(", "slice", "*", "util", ".", "Range", ")", "*", "dbCacheIterator", "{", "return", "&", "dbCacheIterator", "{", "dbIter", ":", "snap", ".", "dbSnapshot", ".", "NewIterator", "(", "slice", ",", "nil", ")", ",", "cacheIter", ":", "newLdbCacheIter", "(", "snap", ",", "slice", ")", ",", "cacheSnapshot", ":", "snap", ",", "}", "\n", "}" ]
// NewIterator returns a new iterator for the snapshot. The newly returned // iterator is not pointing to a valid item until a call to one of the methods // to position it is made. // // The slice parameter allows the iterator to be limited to a range of keys. // The start key is inclusive and the limit key is exclusive. Either or both // can be nil if the functionality is not desired.
[ "NewIterator", "returns", "a", "new", "iterator", "for", "the", "snapshot", ".", "The", "newly", "returned", "iterator", "is", "not", "pointing", "to", "a", "valid", "item", "until", "a", "call", "to", "one", "of", "the", "methods", "to", "position", "it", "is", "made", ".", "The", "slice", "parameter", "allows", "the", "iterator", "to", "be", "limited", "to", "a", "range", "of", "keys", ".", "The", "start", "key", "is", "inclusive", "and", "the", "limit", "key", "is", "exclusive", ".", "Either", "or", "both", "can", "be", "nil", "if", "the", "functionality", "is", "not", "desired", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/dbcache.go#L341-L347
train
btcsuite/btcd
database/ffldb/dbcache.go
Snapshot
func (c *dbCache) Snapshot() (*dbCacheSnapshot, error) { dbSnapshot, err := c.ldb.GetSnapshot() if err != nil { str := "failed to open transaction" return nil, convertErr(str, err) } // Since the cached keys to be added and removed use an immutable treap, // a snapshot is simply obtaining the root of the tree under the lock // which is used to atomically swap the root. c.cacheLock.RLock() cacheSnapshot := &dbCacheSnapshot{ dbSnapshot: dbSnapshot, pendingKeys: c.cachedKeys, pendingRemove: c.cachedRemove, } c.cacheLock.RUnlock() return cacheSnapshot, nil }
go
func (c *dbCache) Snapshot() (*dbCacheSnapshot, error) { dbSnapshot, err := c.ldb.GetSnapshot() if err != nil { str := "failed to open transaction" return nil, convertErr(str, err) } // Since the cached keys to be added and removed use an immutable treap, // a snapshot is simply obtaining the root of the tree under the lock // which is used to atomically swap the root. c.cacheLock.RLock() cacheSnapshot := &dbCacheSnapshot{ dbSnapshot: dbSnapshot, pendingKeys: c.cachedKeys, pendingRemove: c.cachedRemove, } c.cacheLock.RUnlock() return cacheSnapshot, nil }
[ "func", "(", "c", "*", "dbCache", ")", "Snapshot", "(", ")", "(", "*", "dbCacheSnapshot", ",", "error", ")", "{", "dbSnapshot", ",", "err", ":=", "c", ".", "ldb", ".", "GetSnapshot", "(", ")", "\n", "if", "err", "!=", "nil", "{", "str", ":=", "\"", "\"", "\n", "return", "nil", ",", "convertErr", "(", "str", ",", "err", ")", "\n", "}", "\n\n", "// Since the cached keys to be added and removed use an immutable treap,", "// a snapshot is simply obtaining the root of the tree under the lock", "// which is used to atomically swap the root.", "c", ".", "cacheLock", ".", "RLock", "(", ")", "\n", "cacheSnapshot", ":=", "&", "dbCacheSnapshot", "{", "dbSnapshot", ":", "dbSnapshot", ",", "pendingKeys", ":", "c", ".", "cachedKeys", ",", "pendingRemove", ":", "c", ".", "cachedRemove", ",", "}", "\n", "c", ".", "cacheLock", ".", "RUnlock", "(", ")", "\n", "return", "cacheSnapshot", ",", "nil", "\n", "}" ]
// Snapshot returns a snapshot of the database cache and underlying database at // a particular point in time. // // The snapshot must be released after use by calling Release.
[ "Snapshot", "returns", "a", "snapshot", "of", "the", "database", "cache", "and", "underlying", "database", "at", "a", "particular", "point", "in", "time", ".", "The", "snapshot", "must", "be", "released", "after", "use", "by", "calling", "Release", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/dbcache.go#L398-L416
train
btcsuite/btcd
database/ffldb/dbcache.go
updateDB
func (c *dbCache) updateDB(fn func(ldbTx *leveldb.Transaction) error) error { // Start a leveldb transaction. ldbTx, err := c.ldb.OpenTransaction() if err != nil { return convertErr("failed to open ldb transaction", err) } if err := fn(ldbTx); err != nil { ldbTx.Discard() return err } // Commit the leveldb transaction and convert any errors as needed. if err := ldbTx.Commit(); err != nil { return convertErr("failed to commit leveldb transaction", err) } return nil }
go
func (c *dbCache) updateDB(fn func(ldbTx *leveldb.Transaction) error) error { // Start a leveldb transaction. ldbTx, err := c.ldb.OpenTransaction() if err != nil { return convertErr("failed to open ldb transaction", err) } if err := fn(ldbTx); err != nil { ldbTx.Discard() return err } // Commit the leveldb transaction and convert any errors as needed. if err := ldbTx.Commit(); err != nil { return convertErr("failed to commit leveldb transaction", err) } return nil }
[ "func", "(", "c", "*", "dbCache", ")", "updateDB", "(", "fn", "func", "(", "ldbTx", "*", "leveldb", ".", "Transaction", ")", "error", ")", "error", "{", "// Start a leveldb transaction.", "ldbTx", ",", "err", ":=", "c", ".", "ldb", ".", "OpenTransaction", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "convertErr", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "fn", "(", "ldbTx", ")", ";", "err", "!=", "nil", "{", "ldbTx", ".", "Discard", "(", ")", "\n", "return", "err", "\n", "}", "\n\n", "// Commit the leveldb transaction and convert any errors as needed.", "if", "err", ":=", "ldbTx", ".", "Commit", "(", ")", ";", "err", "!=", "nil", "{", "return", "convertErr", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// updateDB invokes the passed function in the context of a managed leveldb // transaction. Any errors returned from the user-supplied function will cause // the transaction to be rolled back and are returned from this function. // Otherwise, the transaction is committed when the user-supplied function // returns a nil error.
[ "updateDB", "invokes", "the", "passed", "function", "in", "the", "context", "of", "a", "managed", "leveldb", "transaction", ".", "Any", "errors", "returned", "from", "the", "user", "-", "supplied", "function", "will", "cause", "the", "transaction", "to", "be", "rolled", "back", "and", "are", "returned", "from", "this", "function", ".", "Otherwise", "the", "transaction", "is", "committed", "when", "the", "user", "-", "supplied", "function", "returns", "a", "nil", "error", "." ]
96897255fd17525dd12426345d279533780bc4e1
https://github.com/btcsuite/btcd/blob/96897255fd17525dd12426345d279533780bc4e1/database/ffldb/dbcache.go#L423-L440
train