Skip to content

Commit

Permalink
txscript: Optimize PushedData.
Browse files Browse the repository at this point in the history
This converts the PushedData function to make use of the new tokenizer
instead of the far less efficient parseScript thereby significantly
optimizing the function.

Also, the comment is modified to explicitly call out the script version
semantics.

The following is a before and after comparison of extracting the data
from a very large script:

benchmark                 old ns/op     new ns/op     delta
BenchmarkPushedData-8     64837         1790          -97.24%

benchmark                 old allocs     new allocs     delta
BenchmarkPushedData-8     7              6              -14.29%

benchmark                 old bytes     new bytes     delta
BenchmarkPushedData-8     312816        1520          -99.51%
  • Loading branch information
davecgh authored and cfromknecht committed Feb 5, 2021
1 parent 5079460 commit d88103e
Showing 1 changed file with 13 additions and 8 deletions.
21 changes: 13 additions & 8 deletions txscript/standard.go
Original file line number Diff line number Diff line change
Expand Up @@ -783,20 +783,25 @@ func MultiSigScript(pubkeys []*btcutil.AddressPubKey, nrequired int) ([]byte, er

// 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.
//
// NOTE: This function is only valid for version 0 scripts. Since the function
// does not accept a script version, the results are undefined for other script
// versions.
func PushedData(script []byte) ([][]byte, error) {
pops, err := parseScript(script)
if err != nil {
return nil, err
}
const scriptVersion = 0

var data [][]byte
for _, pop := range pops {
if pop.data != nil {
data = append(data, pop.data)
} else if pop.opcode.value == OP_0 {
tokenizer := MakeScriptTokenizer(scriptVersion, script)
for tokenizer.Next() {
if tokenizer.Data() != nil {
data = append(data, tokenizer.Data())
} else if tokenizer.Opcode() == OP_0 {
data = append(data, nil)
}
}
if err := tokenizer.Err(); err != nil {
return nil, err
}
return data, nil
}

Expand Down

0 comments on commit d88103e

Please sign in to comment.