Compare commits
17 commits
lbry
...
test-rebas
Author | SHA1 | Date | |
---|---|---|---|
|
da9486f408 | ||
|
be580c28b7 | ||
|
38a9f69d1e | ||
|
44869b8b01 | ||
|
ee79ce7992 | ||
|
bea5c62644 | ||
|
0ef993d30c | ||
|
9c4bbabe7a | ||
|
9cdf59f60c | ||
|
12d7d04b31 | ||
|
97c3fdfaa2 | ||
|
c5b2b0b979 | ||
|
4a0c04f989 | ||
|
43b172ec93 | ||
|
23db973afa | ||
|
14f90e5946 | ||
|
3ecfc35771 |
39 changed files with 1033 additions and 421 deletions
8
.github/workflows/go.yml
vendored
8
.github/workflows/go.yml
vendored
|
@ -6,21 +6,23 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
go: [1.16]
|
||||
go: [1.17]
|
||||
steps:
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: ${{ matrix.go }}
|
||||
|
||||
- name: Check out source
|
||||
uses: actions/checkout@v2
|
||||
- name: Install Linters
|
||||
run: "curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $(go env GOPATH)/bin v1.31.0"
|
||||
|
||||
- name: Build
|
||||
run: go build ./...
|
||||
|
||||
- name: Test
|
||||
run: |
|
||||
sh ./goclean.sh
|
||||
|
||||
- name: Send lbcutil coverage
|
||||
uses: shogo82148/actions-goveralls@v1
|
||||
with:
|
||||
|
|
57
.github/workflows/golangci-lint.yml
vendored
Normal file
57
.github/workflows/golangci-lint.yml
vendored
Normal file
|
@ -0,0 +1,57 @@
|
|||
name: golangci-lint
|
||||
|
||||
env:
|
||||
# go needs absolute directories, using the $HOME variable doesn't work here.
|
||||
GOCACHE: /home/runner/work/go/pkg/build
|
||||
GOPATH: /home/runner/work/go
|
||||
GO_VERSION: '^1.17.0'
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- v*
|
||||
branches:
|
||||
- "*"
|
||||
pull_request:
|
||||
branches:
|
||||
- "*"
|
||||
|
||||
jobs:
|
||||
golangci:
|
||||
name: lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: setup go ${{ env.GO_VERSION }}
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: '${{ env.GO_VERSION }}'
|
||||
|
||||
- name: checkout source
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: compile code
|
||||
run: go install -v ./...
|
||||
|
||||
- name: golangci-lint
|
||||
uses: golangci/golangci-lint-action@v2
|
||||
with:
|
||||
# Optional: version of golangci-lint to use in form of v1.2 or v1.2.3 or `latest` to use the latest version
|
||||
version: latest
|
||||
|
||||
# Optional: working directory, useful for monorepos
|
||||
# working-directory: somedir
|
||||
|
||||
# Optional: golangci-lint command line arguments.
|
||||
# args: --issues-exit-code=0
|
||||
|
||||
# Optional: show only new issues if it's a pull request. The default value is `false`.
|
||||
# only-new-issues: true
|
||||
|
||||
# Optional: if set to true then the action will use pre-installed Go.
|
||||
skip-go-installation: true
|
||||
|
||||
# Optional: if set to true then the action don't cache or restore ~/go/pkg.
|
||||
# skip-pkg-cache: true
|
||||
|
||||
# Optional: if set to true then the action don't cache or restore ~/.cache/go-build.
|
||||
# skip-build-cache: true
|
2
.gitignore
vendored
2
.gitignore
vendored
|
@ -26,3 +26,5 @@ _cgo_export.*
|
|||
_testmain.go
|
||||
|
||||
*.exe
|
||||
coverage.txt
|
||||
psbt/coverage.txt
|
||||
|
|
152
.golangci.yml
Normal file
152
.golangci.yml
Normal file
|
@ -0,0 +1,152 @@
|
|||
linters-settings:
|
||||
depguard:
|
||||
list-type: blacklist
|
||||
packages:
|
||||
# logging is allowed only by logutils.Log, logrus
|
||||
# is allowed to use only in logutils package
|
||||
- github.com/sirupsen/logrus
|
||||
packages-with-error-message:
|
||||
- github.com/sirupsen/logrus: "logging is allowed only by logutils.Log"
|
||||
dupl:
|
||||
threshold: 100
|
||||
funlen:
|
||||
lines: 100
|
||||
statements: 50
|
||||
gci:
|
||||
local-prefixes: github.com/golangci/golangci-lint
|
||||
goconst:
|
||||
min-len: 2
|
||||
min-occurrences: 2
|
||||
gocritic:
|
||||
enabled-tags:
|
||||
- diagnostic
|
||||
- experimental
|
||||
- opinionated
|
||||
- performance
|
||||
- style
|
||||
disabled-checks:
|
||||
- dupImport # https://github.com/go-critic/go-critic/issues/845
|
||||
- ifElseChain
|
||||
- octalLiteral
|
||||
- whyNoLint
|
||||
- wrapperFunc
|
||||
gocyclo:
|
||||
min-complexity: 15
|
||||
goimports:
|
||||
local-prefixes: github.com/golangci/golangci-lint
|
||||
gomnd:
|
||||
settings:
|
||||
mnd:
|
||||
# don't include the "operation" and "assign"
|
||||
checks:
|
||||
- argument
|
||||
- case
|
||||
- condition
|
||||
- return
|
||||
govet:
|
||||
check-shadowing: true
|
||||
settings:
|
||||
printf:
|
||||
funcs:
|
||||
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof
|
||||
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf
|
||||
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf
|
||||
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf
|
||||
lll:
|
||||
line-length: 140
|
||||
maligned:
|
||||
suggest-new: true
|
||||
misspell:
|
||||
locale: US
|
||||
nolintlint:
|
||||
allow-leading-space: true # don't require machine-readable nolint directives (i.e. with no leading space)
|
||||
allow-unused: false # report any unused nolint directives
|
||||
require-explanation: false # don't require an explanation for nolint directives
|
||||
require-specific: false # don't require nolint directives to be specific about which linter is being skipped
|
||||
|
||||
linters:
|
||||
disable-all: true
|
||||
enable:
|
||||
- asciicheck
|
||||
- bodyclose
|
||||
# - deadcode
|
||||
- depguard
|
||||
# - dogsled
|
||||
# - dupl
|
||||
# - errcheck
|
||||
# - exhaustive
|
||||
- exportloopref
|
||||
# - funlen
|
||||
# - gochecknoglobals
|
||||
# - gochecknoinits
|
||||
# - gocognit
|
||||
# - goconst
|
||||
# - gocritic
|
||||
# - gocyclo
|
||||
# - godot
|
||||
# - godox
|
||||
# - goerr113
|
||||
- gofmt
|
||||
- goimports
|
||||
# - gomnd
|
||||
- goprintffuncname
|
||||
# - gosec
|
||||
# - gosimple
|
||||
# - govet
|
||||
# - ineffassign
|
||||
# - interfacer
|
||||
# - lll
|
||||
# - maligned
|
||||
# - misspell
|
||||
- nakedret
|
||||
# - nestif
|
||||
# - noctx
|
||||
# - nolintlint
|
||||
# - prealloc
|
||||
- rowserrcheck
|
||||
# - revive
|
||||
# - scopelint
|
||||
# - staticcheck
|
||||
# - structcheck
|
||||
# - stylecheck
|
||||
# - testpackage
|
||||
# - typecheck
|
||||
- unconvert
|
||||
# - unparam
|
||||
# - unused
|
||||
# - varcheck
|
||||
# - whitespace
|
||||
# - wsl
|
||||
|
||||
issues:
|
||||
# Excluding configuration per-path, per-linter, per-text and per-source
|
||||
exclude-rules:
|
||||
- path: _test\.go
|
||||
linters:
|
||||
- gomnd
|
||||
|
||||
- path: pkg/golinters/errcheck.go
|
||||
text: "SA1019: errCfg.Exclude is deprecated: use ExcludeFunctions instead"
|
||||
- path: pkg/commands/run.go
|
||||
text: "SA1019: lsc.Errcheck.Exclude is deprecated: use ExcludeFunctions instead"
|
||||
|
||||
# TODO must be removed after the release of the next version (v1.41.0)
|
||||
- path: pkg/commands/run.go
|
||||
linters:
|
||||
- gomnd
|
||||
# TODO must be removed after the release of the next version (v1.41.0)
|
||||
- path: pkg/golinters/nolintlint/nolintlint.go
|
||||
linters:
|
||||
- gomnd
|
||||
# TODO must be removed after the release of the next version (v1.41.0)
|
||||
- path: pkg/printers/tab.go
|
||||
linters:
|
||||
- gomnd
|
||||
|
||||
|
||||
run:
|
||||
skip-dirs:
|
||||
- test/testdata_etc
|
||||
- internal/cache
|
||||
- internal/renameio
|
||||
- internal/robustio
|
116
Makefile
Normal file
116
Makefile
Normal file
|
@ -0,0 +1,116 @@
|
|||
PKG := github.com/btcsuite/btcutil
|
||||
|
||||
LINT_PKG := github.com/golangci/golangci-lint/cmd/golangci-lint
|
||||
GOACC_PKG := github.com/ory/go-acc
|
||||
GOIMPORTS_PKG := golang.org/x/tools/cmd/goimports
|
||||
|
||||
GO_BIN := ${GOPATH}/bin
|
||||
LINT_BIN := $(GO_BIN)/golangci-lint
|
||||
GOACC_BIN := $(GO_BIN)/go-acc
|
||||
|
||||
LINT_COMMIT := v1.18.0
|
||||
GOACC_COMMIT := 80342ae2e0fcf265e99e76bcc4efd022c7c3811b
|
||||
|
||||
DEPGET := cd /tmp && GO111MODULE=on go get -v
|
||||
GOBUILD := GO111MODULE=on go build -v
|
||||
GOINSTALL := GO111MODULE=on go install -v
|
||||
GOTEST := GO111MODULE=on go test
|
||||
|
||||
GOFILES_NOVENDOR = $(shell find . -type f -name '*.go' -not -path "./vendor/*")
|
||||
|
||||
RM := rm -f
|
||||
CP := cp
|
||||
MAKE := make
|
||||
XARGS := xargs -L 1
|
||||
|
||||
# Linting uses a lot of memory, so keep it under control by limiting the number
|
||||
# of workers if requested.
|
||||
ifneq ($(workers),)
|
||||
LINT_WORKERS = --concurrency=$(workers)
|
||||
endif
|
||||
|
||||
LINT = $(LINT_BIN) run -v $(LINT_WORKERS)
|
||||
|
||||
GREEN := "\\033[0;32m"
|
||||
NC := "\\033[0m"
|
||||
define print
|
||||
echo $(GREEN)$1$(NC)
|
||||
endef
|
||||
|
||||
default: build
|
||||
|
||||
all: build check
|
||||
|
||||
# ============
|
||||
# DEPENDENCIES
|
||||
# ============
|
||||
|
||||
$(LINT_BIN):
|
||||
@$(call print, "Fetching linter")
|
||||
$(DEPGET) $(LINT_PKG)@$(LINT_COMMIT)
|
||||
|
||||
$(GOACC_BIN):
|
||||
@$(call print, "Fetching go-acc")
|
||||
$(DEPGET) $(GOACC_PKG)@$(GOACC_COMMIT)
|
||||
|
||||
goimports:
|
||||
@$(call print, "Installing goimports.")
|
||||
$(DEPGET) $(GOIMPORTS_PKG)
|
||||
|
||||
# ============
|
||||
# INSTALLATION
|
||||
# ============
|
||||
|
||||
build:
|
||||
@$(call print, "Compiling btcutil.")
|
||||
$(GOBUILD) $(PKG)/...
|
||||
|
||||
# =======
|
||||
# TESTING
|
||||
# =======
|
||||
|
||||
check: unit
|
||||
|
||||
unit:
|
||||
@$(call print, "Running unit tests.")
|
||||
$(GOTEST) ./... -test.timeout=20m
|
||||
cd psbt; $(GOTEST) ./... -test.timeout=20m
|
||||
|
||||
unit-cover: $(GOACC_BIN)
|
||||
@$(call print, "Running unit coverage tests.")
|
||||
$(GOACC_BIN) ./...
|
||||
cd psbt; $(GOACC_BIN) ./...
|
||||
|
||||
unit-race:
|
||||
@$(call print, "Running unit race tests.")
|
||||
env CGO_ENABLED=1 GORACE="history_size=7 halt_on_errors=1" $(GOTEST) -race -test.timeout=20m ./...
|
||||
cd psbt; env CGO_ENABLED=1 GORACE="history_size=7 halt_on_errors=1" $(GOTEST) -race -test.timeout=20m ./...
|
||||
|
||||
# =========
|
||||
# UTILITIES
|
||||
# =========
|
||||
|
||||
fmt: goimports
|
||||
@$(call print, "Fixing imports.")
|
||||
goimports -w $(GOFILES_NOVENDOR)
|
||||
@$(call print, "Formatting source.")
|
||||
gofmt -l -w -s $(GOFILES_NOVENDOR)
|
||||
|
||||
lint: $(LINT_BIN)
|
||||
@$(call print, "Linting source.")
|
||||
$(LINT)
|
||||
|
||||
clean:
|
||||
@$(call print, "Cleaning source.$(NC)")
|
||||
$(RM) coverage.txt psbt/coverage.txt
|
||||
|
||||
.PHONY: all \
|
||||
default \
|
||||
build \
|
||||
check \
|
||||
unit \
|
||||
unit-cover \
|
||||
unit-race \
|
||||
fmt \
|
||||
lint \
|
||||
clean
|
283
address.go
283
address.go
|
@ -41,7 +41,7 @@ var (
|
|||
|
||||
// ErrUnknownAddressType describes an error where an address can not
|
||||
// decoded as a specific address type due to the string encoding
|
||||
// begining with an identifier byte unknown to any standard or
|
||||
// beginning with an identifier byte unknown to any standard or
|
||||
// registered (via chaincfg.Register) network.
|
||||
ErrUnknownAddressType = errors.New("unknown address type")
|
||||
|
||||
|
@ -64,8 +64,8 @@ func encodeAddress(hash160 []byte, netID byte) string {
|
|||
return base58.CheckEncode(hash160[:ripemd160.Size], netID)
|
||||
}
|
||||
|
||||
// encodeSegWitAddress creates a bech32 encoded address string representation
|
||||
// from witness version and witness program.
|
||||
// encodeSegWitAddress creates a bech32 (or bech32m for SegWit v1) encoded
|
||||
// address string representation from witness version and witness program.
|
||||
func encodeSegWitAddress(hrp string, witnessVersion byte, witnessProgram []byte) (string, error) {
|
||||
// Group the address bytes into 5 bit groups, as this is what is used to
|
||||
// encode each character in the address string.
|
||||
|
@ -79,7 +79,19 @@ func encodeSegWitAddress(hrp string, witnessVersion byte, witnessProgram []byte)
|
|||
combined := make([]byte, len(converted)+1)
|
||||
combined[0] = witnessVersion
|
||||
copy(combined[1:], converted)
|
||||
bech, err := bech32.Encode(hrp, combined)
|
||||
|
||||
var bech string
|
||||
switch witnessVersion {
|
||||
case 0:
|
||||
bech, err = bech32.Encode(hrp, combined)
|
||||
|
||||
case 1:
|
||||
bech, err = bech32.EncodeM(hrp, combined)
|
||||
|
||||
default:
|
||||
return "", fmt.Errorf("unsupported witness version %d",
|
||||
witnessVersion)
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
@ -149,8 +161,9 @@ func DecodeAddress(addr string, defaultNet *chaincfg.Params) (Address, error) {
|
|||
}
|
||||
|
||||
// We currently only support P2WPKH and P2WSH, which is
|
||||
// witness version 0.
|
||||
if witnessVer != 0 {
|
||||
// witness version 0 and P2TR which is witness version
|
||||
// 1.
|
||||
if witnessVer != 0 && witnessVer != 1 {
|
||||
return nil, UnsupportedWitnessVerError(witnessVer)
|
||||
}
|
||||
|
||||
|
@ -161,6 +174,10 @@ func DecodeAddress(addr string, defaultNet *chaincfg.Params) (Address, error) {
|
|||
case 20:
|
||||
return newAddressWitnessPubKeyHash(hrp, witnessProg)
|
||||
case 32:
|
||||
if witnessVer == 1 {
|
||||
return newAddressTaproot(hrp, witnessProg)
|
||||
}
|
||||
|
||||
return newAddressWitnessScriptHash(hrp, witnessProg)
|
||||
default:
|
||||
return nil, UnsupportedWitnessProgLenError(len(witnessProg))
|
||||
|
@ -210,7 +227,7 @@ func DecodeAddress(addr string, defaultNet *chaincfg.Params) (Address, error) {
|
|||
// returns the witness version and witness program byte representation.
|
||||
func decodeSegWitAddress(address string) (byte, []byte, error) {
|
||||
// Decode the bech32 encoded address.
|
||||
_, data, err := bech32.Decode(address)
|
||||
_, data, bech32version, err := bech32.DecodeGeneric(address)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
|
@ -246,6 +263,18 @@ func decodeSegWitAddress(address string) (byte, []byte, error) {
|
|||
"version 0: %v", len(regrouped))
|
||||
}
|
||||
|
||||
// For witness version 0, the bech32 encoding must be used.
|
||||
if version == 0 && bech32version != bech32.Version0 {
|
||||
return 0, nil, fmt.Errorf("invalid checksum expected bech32 " +
|
||||
"encoding for address with witness version 0")
|
||||
}
|
||||
|
||||
// For witness version 1, the bech32m encoding must be used.
|
||||
if version == 1 && bech32version != bech32.VersionM {
|
||||
return 0, nil, fmt.Errorf("invalid checksum expected bech32m " +
|
||||
"encoding for address with witness version 1")
|
||||
}
|
||||
|
||||
return version, regrouped, nil
|
||||
}
|
||||
|
||||
|
@ -265,7 +294,7 @@ func NewAddressPubKeyHash(pkHash []byte, net *chaincfg.Params) (*AddressPubKeyHa
|
|||
// newAddressPubKeyHash is the internal API to create a pubkey hash address
|
||||
// with a known leading identifier byte for a network, rather than looking
|
||||
// it up through its parameters. This is useful when creating a new address
|
||||
// structure from a string encoding where the identifer byte is already
|
||||
// structure from a string encoding where the identifier byte is already
|
||||
// known.
|
||||
func newAddressPubKeyHash(pkHash []byte, netID byte) (*AddressPubKeyHash, error) {
|
||||
// Check for a valid pubkey hash length.
|
||||
|
@ -304,7 +333,7 @@ func (a *AddressPubKeyHash) String() string {
|
|||
}
|
||||
|
||||
// Hash160 returns the underlying array of the pubkey hash. This can be useful
|
||||
// when an array is more appropiate than a slice (for example, when used as map
|
||||
// when an array is more appropriate than a slice (for example, when used as map
|
||||
// keys).
|
||||
func (a *AddressPubKeyHash) Hash160() *[ripemd160.Size]byte {
|
||||
return &a.hash
|
||||
|
@ -332,7 +361,7 @@ func NewAddressScriptHashFromHash(scriptHash []byte, net *chaincfg.Params) (*Add
|
|||
// newAddressScriptHashFromHash is the internal API to create a script hash
|
||||
// address with a known leading identifier byte for a network, rather than
|
||||
// looking it up through its parameters. This is useful when creating a new
|
||||
// address structure from a string encoding where the identifer byte is already
|
||||
// address structure from a string encoding where the identifier byte is already
|
||||
// known.
|
||||
func newAddressScriptHashFromHash(scriptHash []byte, netID byte) (*AddressScriptHash, error) {
|
||||
// Check for a valid script hash length.
|
||||
|
@ -371,7 +400,7 @@ func (a *AddressScriptHash) String() string {
|
|||
}
|
||||
|
||||
// Hash160 returns the underlying array of the script hash. This can be useful
|
||||
// when an array is more appropiate than a slice (for example, when used as map
|
||||
// when an array is more appropriate than a slice (for example, when used as map
|
||||
// keys).
|
||||
func (a *AddressScriptHash) Hash160() *[ripemd160.Size]byte {
|
||||
return &a.hash
|
||||
|
@ -506,25 +535,88 @@ func (a *AddressPubKey) PubKey() *btcec.PublicKey {
|
|||
return a.pubKey
|
||||
}
|
||||
|
||||
// AddressSegWit is the base address type for all SegWit addresses.
|
||||
type AddressSegWit struct {
|
||||
hrp string
|
||||
witnessVersion byte
|
||||
witnessProgram []byte
|
||||
}
|
||||
|
||||
// EncodeAddress returns the bech32 (or bech32m for SegWit v1) string encoding
|
||||
// of an AddressSegWit.
|
||||
//
|
||||
// NOTE: This method is part of the Address interface.
|
||||
func (a *AddressSegWit) EncodeAddress() string {
|
||||
str, err := encodeSegWitAddress(
|
||||
a.hrp, a.witnessVersion, a.witnessProgram[:],
|
||||
)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return str
|
||||
}
|
||||
|
||||
// ScriptAddress returns the witness program for this address.
|
||||
//
|
||||
// NOTE: This method is part of the Address interface.
|
||||
func (a *AddressSegWit) ScriptAddress() []byte {
|
||||
return a.witnessProgram[:]
|
||||
}
|
||||
|
||||
// IsForNet returns whether the AddressSegWit is associated with the passed
|
||||
// bitcoin network.
|
||||
//
|
||||
// NOTE: This method is part of the Address interface.
|
||||
func (a *AddressSegWit) IsForNet(net *chaincfg.Params) bool {
|
||||
return a.hrp == net.Bech32HRPSegwit
|
||||
}
|
||||
|
||||
// String returns a human-readable string for the AddressWitnessPubKeyHash.
|
||||
// This is equivalent to calling EncodeAddress, but is provided so the type
|
||||
// can be used as a fmt.Stringer.
|
||||
//
|
||||
// NOTE: This method is part of the Address interface.
|
||||
func (a *AddressSegWit) String() string {
|
||||
return a.EncodeAddress()
|
||||
}
|
||||
|
||||
// Hrp returns the human-readable part of the bech32 (or bech32m for SegWit v1)
|
||||
// encoded AddressSegWit.
|
||||
func (a *AddressSegWit) Hrp() string {
|
||||
return a.hrp
|
||||
}
|
||||
|
||||
// WitnessVersion returns the witness version of the AddressSegWit.
|
||||
func (a *AddressSegWit) WitnessVersion() byte {
|
||||
return a.witnessVersion
|
||||
}
|
||||
|
||||
// WitnessProgram returns the witness program of the AddressSegWit.
|
||||
func (a *AddressSegWit) WitnessProgram() []byte {
|
||||
return a.witnessProgram[:]
|
||||
}
|
||||
|
||||
// AddressWitnessPubKeyHash is an Address for a pay-to-witness-pubkey-hash
|
||||
// (P2WPKH) output. See BIP 173 for further details regarding native segregated
|
||||
// witness address encoding:
|
||||
// https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki
|
||||
type AddressWitnessPubKeyHash struct {
|
||||
hrp string
|
||||
witnessVersion byte
|
||||
witnessProgram [20]byte
|
||||
AddressSegWit
|
||||
}
|
||||
|
||||
// NewAddressWitnessPubKeyHash returns a new AddressWitnessPubKeyHash.
|
||||
func NewAddressWitnessPubKeyHash(witnessProg []byte, net *chaincfg.Params) (*AddressWitnessPubKeyHash, error) {
|
||||
func NewAddressWitnessPubKeyHash(witnessProg []byte,
|
||||
net *chaincfg.Params) (*AddressWitnessPubKeyHash, error) {
|
||||
|
||||
return newAddressWitnessPubKeyHash(net.Bech32HRPSegwit, witnessProg)
|
||||
}
|
||||
|
||||
// newAddressWitnessPubKeyHash is an internal helper function to create an
|
||||
// AddressWitnessPubKeyHash with a known human-readable part, rather than
|
||||
// looking it up through its parameters.
|
||||
func newAddressWitnessPubKeyHash(hrp string, witnessProg []byte) (*AddressWitnessPubKeyHash, error) {
|
||||
func newAddressWitnessPubKeyHash(hrp string,
|
||||
witnessProg []byte) (*AddressWitnessPubKeyHash, error) {
|
||||
|
||||
// Check for valid program length for witness version 0, which is 20
|
||||
// for P2WPKH.
|
||||
if len(witnessProg) != 20 {
|
||||
|
@ -533,68 +625,22 @@ func newAddressWitnessPubKeyHash(hrp string, witnessProg []byte) (*AddressWitnes
|
|||
}
|
||||
|
||||
addr := &AddressWitnessPubKeyHash{
|
||||
hrp: strings.ToLower(hrp),
|
||||
witnessVersion: 0x00,
|
||||
AddressSegWit{
|
||||
hrp: strings.ToLower(hrp),
|
||||
witnessVersion: 0x00,
|
||||
witnessProgram: witnessProg,
|
||||
},
|
||||
}
|
||||
|
||||
copy(addr.witnessProgram[:], witnessProg)
|
||||
|
||||
return addr, nil
|
||||
}
|
||||
|
||||
// EncodeAddress returns the bech32 string encoding of an
|
||||
// AddressWitnessPubKeyHash.
|
||||
// Part of the Address interface.
|
||||
func (a *AddressWitnessPubKeyHash) EncodeAddress() string {
|
||||
str, err := encodeSegWitAddress(a.hrp, a.witnessVersion,
|
||||
a.witnessProgram[:])
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return str
|
||||
}
|
||||
|
||||
// ScriptAddress returns the witness program for this address.
|
||||
// Part of the Address interface.
|
||||
func (a *AddressWitnessPubKeyHash) ScriptAddress() []byte {
|
||||
return a.witnessProgram[:]
|
||||
}
|
||||
|
||||
// IsForNet returns whether or not the AddressWitnessPubKeyHash is associated
|
||||
// with the passed bitcoin network.
|
||||
// Part of the Address interface.
|
||||
func (a *AddressWitnessPubKeyHash) IsForNet(net *chaincfg.Params) bool {
|
||||
return a.hrp == net.Bech32HRPSegwit
|
||||
}
|
||||
|
||||
// String returns a human-readable string for the AddressWitnessPubKeyHash.
|
||||
// This is equivalent to calling EncodeAddress, but is provided so the type
|
||||
// can be used as a fmt.Stringer.
|
||||
// Part of the Address interface.
|
||||
func (a *AddressWitnessPubKeyHash) String() string {
|
||||
return a.EncodeAddress()
|
||||
}
|
||||
|
||||
// Hrp returns the human-readable part of the bech32 encoded
|
||||
// AddressWitnessPubKeyHash.
|
||||
func (a *AddressWitnessPubKeyHash) Hrp() string {
|
||||
return a.hrp
|
||||
}
|
||||
|
||||
// WitnessVersion returns the witness version of the AddressWitnessPubKeyHash.
|
||||
func (a *AddressWitnessPubKeyHash) WitnessVersion() byte {
|
||||
return a.witnessVersion
|
||||
}
|
||||
|
||||
// WitnessProgram returns the witness program of the AddressWitnessPubKeyHash.
|
||||
func (a *AddressWitnessPubKeyHash) WitnessProgram() []byte {
|
||||
return a.witnessProgram[:]
|
||||
}
|
||||
|
||||
// Hash160 returns the witness program of the AddressWitnessPubKeyHash as a
|
||||
// byte array.
|
||||
func (a *AddressWitnessPubKeyHash) Hash160() *[20]byte {
|
||||
return &a.witnessProgram
|
||||
var pubKeyHashWitnessProgram [20]byte
|
||||
copy(pubKeyHashWitnessProgram[:], a.witnessProgram)
|
||||
return &pubKeyHashWitnessProgram
|
||||
}
|
||||
|
||||
// AddressWitnessScriptHash is an Address for a pay-to-witness-script-hash
|
||||
|
@ -602,20 +648,22 @@ func (a *AddressWitnessPubKeyHash) Hash160() *[20]byte {
|
|||
// witness address encoding:
|
||||
// https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki
|
||||
type AddressWitnessScriptHash struct {
|
||||
hrp string
|
||||
witnessVersion byte
|
||||
witnessProgram [32]byte
|
||||
AddressSegWit
|
||||
}
|
||||
|
||||
// NewAddressWitnessScriptHash returns a new AddressWitnessPubKeyHash.
|
||||
func NewAddressWitnessScriptHash(witnessProg []byte, net *chaincfg.Params) (*AddressWitnessScriptHash, error) {
|
||||
func NewAddressWitnessScriptHash(witnessProg []byte,
|
||||
net *chaincfg.Params) (*AddressWitnessScriptHash, error) {
|
||||
|
||||
return newAddressWitnessScriptHash(net.Bech32HRPSegwit, witnessProg)
|
||||
}
|
||||
|
||||
// newAddressWitnessScriptHash is an internal helper function to create an
|
||||
// AddressWitnessScriptHash with a known human-readable part, rather than
|
||||
// looking it up through its parameters.
|
||||
func newAddressWitnessScriptHash(hrp string, witnessProg []byte) (*AddressWitnessScriptHash, error) {
|
||||
func newAddressWitnessScriptHash(hrp string,
|
||||
witnessProg []byte) (*AddressWitnessScriptHash, error) {
|
||||
|
||||
// Check for valid program length for witness version 0, which is 32
|
||||
// for P2WSH.
|
||||
if len(witnessProg) != 32 {
|
||||
|
@ -624,60 +672,49 @@ func newAddressWitnessScriptHash(hrp string, witnessProg []byte) (*AddressWitnes
|
|||
}
|
||||
|
||||
addr := &AddressWitnessScriptHash{
|
||||
hrp: strings.ToLower(hrp),
|
||||
witnessVersion: 0x00,
|
||||
AddressSegWit{
|
||||
hrp: strings.ToLower(hrp),
|
||||
witnessVersion: 0x00,
|
||||
witnessProgram: witnessProg,
|
||||
},
|
||||
}
|
||||
|
||||
copy(addr.witnessProgram[:], witnessProg)
|
||||
|
||||
return addr, nil
|
||||
}
|
||||
|
||||
// EncodeAddress returns the bech32 string encoding of an
|
||||
// AddressWitnessScriptHash.
|
||||
// Part of the Address interface.
|
||||
func (a *AddressWitnessScriptHash) EncodeAddress() string {
|
||||
str, err := encodeSegWitAddress(a.hrp, a.witnessVersion,
|
||||
a.witnessProgram[:])
|
||||
if err != nil {
|
||||
return ""
|
||||
// AddressTaproot is an Address for a pay-to-taproot (P2TR) output. See BIP 341
|
||||
// for further details.
|
||||
type AddressTaproot struct {
|
||||
AddressSegWit
|
||||
}
|
||||
|
||||
// NewAddressTaproot returns a new AddressTaproot.
|
||||
func NewAddressTaproot(witnessProg []byte,
|
||||
net *chaincfg.Params) (*AddressTaproot, error) {
|
||||
|
||||
return newAddressTaproot(net.Bech32HRPSegwit, witnessProg)
|
||||
}
|
||||
|
||||
// newAddressWitnessScriptHash is an internal helper function to create an
|
||||
// AddressWitnessScriptHash with a known human-readable part, rather than
|
||||
// looking it up through its parameters.
|
||||
func newAddressTaproot(hrp string,
|
||||
witnessProg []byte) (*AddressTaproot, error) {
|
||||
|
||||
// Check for valid program length for witness version 1, which is 32
|
||||
// for P2TR.
|
||||
if len(witnessProg) != 32 {
|
||||
return nil, errors.New("witness program must be 32 bytes for " +
|
||||
"p2tr")
|
||||
}
|
||||
return str
|
||||
}
|
||||
|
||||
// ScriptAddress returns the witness program for this address.
|
||||
// Part of the Address interface.
|
||||
func (a *AddressWitnessScriptHash) ScriptAddress() []byte {
|
||||
return a.witnessProgram[:]
|
||||
}
|
||||
addr := &AddressTaproot{
|
||||
AddressSegWit{
|
||||
hrp: strings.ToLower(hrp),
|
||||
witnessVersion: 0x01,
|
||||
witnessProgram: witnessProg,
|
||||
},
|
||||
}
|
||||
|
||||
// IsForNet returns whether or not the AddressWitnessScriptHash is associated
|
||||
// with the passed bitcoin network.
|
||||
// Part of the Address interface.
|
||||
func (a *AddressWitnessScriptHash) IsForNet(net *chaincfg.Params) bool {
|
||||
return a.hrp == net.Bech32HRPSegwit
|
||||
}
|
||||
|
||||
// String returns a human-readable string for the AddressWitnessScriptHash.
|
||||
// This is equivalent to calling EncodeAddress, but is provided so the type
|
||||
// can be used as a fmt.Stringer.
|
||||
// Part of the Address interface.
|
||||
func (a *AddressWitnessScriptHash) String() string {
|
||||
return a.EncodeAddress()
|
||||
}
|
||||
|
||||
// Hrp returns the human-readable part of the bech32 encoded
|
||||
// AddressWitnessScriptHash.
|
||||
func (a *AddressWitnessScriptHash) Hrp() string {
|
||||
return a.hrp
|
||||
}
|
||||
|
||||
// WitnessVersion returns the witness version of the AddressWitnessScriptHash.
|
||||
func (a *AddressWitnessScriptHash) WitnessVersion() byte {
|
||||
return a.witnessVersion
|
||||
}
|
||||
|
||||
// WitnessProgram returns the witness program of the AddressWitnessScriptHash.
|
||||
func (a *AddressWitnessScriptHash) WitnessProgram() []byte {
|
||||
return a.witnessProgram[:]
|
||||
return addr, nil
|
||||
}
|
||||
|
|
120
address_test.go
120
address_test.go
|
@ -655,13 +655,123 @@ func TestAddresses(t *testing.T) {
|
|||
},
|
||||
net: &customParams,
|
||||
},
|
||||
// Unsupported witness versions (version 0 only supported at this point)
|
||||
|
||||
// P2TR address tests.
|
||||
{
|
||||
name: "segwit mainnet witness v1",
|
||||
addr: "bc1pw508d6qejxtdg4y5r3zarvary0c5xw7kw508d6qejxtdg4y5r3zarvary0c5xw7k7grplx",
|
||||
name: "segwit v1 mainnet p2tr",
|
||||
addr: "bc1paardr2nczq0rx5rqpfwnvpzm497zvux64y0f7wjgcs7xuuuh2nnqwr2d5c",
|
||||
encoded: "bc1paardr2nczq0rx5rqpfwnvpzm497zvux64y0f7wjgcs7xuuuh2nnqwr2d5c",
|
||||
valid: true,
|
||||
result: lbcutil.TstAddressTaproot(
|
||||
1, [32]byte{
|
||||
0xef, 0x46, 0xd1, 0xaa, 0x78, 0x10, 0x1e, 0x33,
|
||||
0x50, 0x60, 0x0a, 0x5d, 0x36, 0x04, 0x5b, 0xa9,
|
||||
0x7c, 0x26, 0x70, 0xda, 0xa9, 0x1e, 0x9f, 0x3a,
|
||||
0x48, 0xc4, 0x3c, 0x6e, 0x73, 0x97, 0x54, 0xe6,
|
||||
}, chaincfg.MainNetParams.Bech32HRPSegwit,
|
||||
),
|
||||
f: func() (lbcutil.Address, error) {
|
||||
scriptHash := []byte{
|
||||
0xef, 0x46, 0xd1, 0xaa, 0x78, 0x10, 0x1e, 0x33,
|
||||
0x50, 0x60, 0x0a, 0x5d, 0x36, 0x04, 0x5b, 0xa9,
|
||||
0x7c, 0x26, 0x70, 0xda, 0xa9, 0x1e, 0x9f, 0x3a,
|
||||
0x48, 0xc4, 0x3c, 0x6e, 0x73, 0x97, 0x54, 0xe6,
|
||||
}
|
||||
return lbcutil.NewAddressTaproot(
|
||||
scriptHash, &chaincfg.MainNetParams,
|
||||
)
|
||||
},
|
||||
net: &chaincfg.MainNetParams,
|
||||
},
|
||||
|
||||
// Invalid bech32m tests. Source:
|
||||
// https://github.com/bitcoin/bips/blob/master/bip-0350.mediawiki
|
||||
{
|
||||
name: "segwit v1 invalid human-readable part",
|
||||
addr: "tc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vq5zuyut",
|
||||
valid: false,
|
||||
net: &chaincfg.MainNetParams,
|
||||
},
|
||||
{
|
||||
name: "segwit v1 mainnet bech32 instead of bech32m",
|
||||
addr: "bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqh2y7hd",
|
||||
valid: false,
|
||||
net: &chaincfg.MainNetParams,
|
||||
},
|
||||
{
|
||||
name: "segwit v1 testnet bech32 instead of bech32m",
|
||||
addr: "tb1z0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqglt7rf",
|
||||
valid: false,
|
||||
net: &chaincfg.TestNet3Params,
|
||||
},
|
||||
{
|
||||
name: "segwit v1 mainnet bech32 instead of bech32m upper case",
|
||||
addr: "BC1S0XLXVLHEMJA6C4DQV22UAPCTQUPFHLXM9H8Z3K2E72Q4K9HCZ7VQ54WELL",
|
||||
valid: false,
|
||||
net: &chaincfg.MainNetParams,
|
||||
},
|
||||
{
|
||||
name: "segwit v0 mainnet bech32m instead of bech32",
|
||||
addr: "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kemeawh",
|
||||
valid: false,
|
||||
net: &chaincfg.MainNetParams,
|
||||
},
|
||||
{
|
||||
name: "segwit v1 testnet bech32 instead of bech32m second test",
|
||||
addr: "tb1q0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vq24jc47",
|
||||
valid: false,
|
||||
net: &chaincfg.TestNet3Params,
|
||||
},
|
||||
{
|
||||
name: "segwit v1 mainnet bech32m invalid character in checksum",
|
||||
addr: "bc1p38j9r5y49hruaue7wxjce0updqjuyyx0kh56v8s25huc6995vvpql3jow4",
|
||||
valid: false,
|
||||
net: &chaincfg.MainNetParams,
|
||||
},
|
||||
{
|
||||
name: "segwit mainnet witness v17",
|
||||
addr: "BC130XLXVLHEMJA6C4DQV22UAPCTQUPFHLXM9H8Z3K2E72Q4K9HCZ7VQ7ZWS8R",
|
||||
valid: false,
|
||||
net: &chaincfg.MainNetParams,
|
||||
},
|
||||
{
|
||||
name: "segwit v1 mainnet bech32m invalid program length (1 byte)",
|
||||
addr: "bc1pw5dgrnzv",
|
||||
valid: false,
|
||||
net: &chaincfg.MainNetParams,
|
||||
},
|
||||
{
|
||||
name: "segwit v1 mainnet bech32m invalid program length (41 bytes)",
|
||||
addr: "bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7v8n0nx0muaewav253zgeav",
|
||||
valid: false,
|
||||
net: &chaincfg.MainNetParams,
|
||||
},
|
||||
{
|
||||
name: "segwit v1 testnet bech32m mixed case",
|
||||
addr: "tb1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vq47Zagq",
|
||||
valid: false,
|
||||
net: &chaincfg.TestNet3Params,
|
||||
},
|
||||
{
|
||||
name: "segwit v1 mainnet bech32m zero padding of more than 4 bits",
|
||||
addr: "bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7v07qwwzcrf",
|
||||
valid: false,
|
||||
net: &chaincfg.MainNetParams,
|
||||
},
|
||||
{
|
||||
name: "segwit v1 mainnet bech32m non-zero padding in 8-to-5-conversion",
|
||||
addr: "tb1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vpggkg4j",
|
||||
valid: false,
|
||||
net: &chaincfg.TestNet3Params,
|
||||
},
|
||||
{
|
||||
name: "segwit v1 mainnet bech32m empty data section",
|
||||
addr: "bc1gmk9yu",
|
||||
valid: false,
|
||||
net: &chaincfg.MainNetParams,
|
||||
},
|
||||
|
||||
// Unsupported witness versions (version 0 and 1 only supported at this point)
|
||||
{
|
||||
name: "segwit mainnet witness v16",
|
||||
addr: "BC1SW50QA3JX3S",
|
||||
|
@ -766,7 +876,7 @@ func TestAddresses(t *testing.T) {
|
|||
// Encode again and compare against the original.
|
||||
encoded := decoded.EncodeAddress()
|
||||
if test.encoded != encoded {
|
||||
t.Errorf("%v: decoding and encoding produced different addressess: %v != %v",
|
||||
t.Errorf("%v: decoding and encoding produced different addresses: %v != %v",
|
||||
test.name, test.encoded, encoded)
|
||||
return
|
||||
}
|
||||
|
@ -788,6 +898,8 @@ func TestAddresses(t *testing.T) {
|
|||
saddr = lbcutil.TstAddressSegwitSAddr(encoded)
|
||||
case *lbcutil.AddressWitnessScriptHash:
|
||||
saddr = lbcutil.TstAddressSegwitSAddr(encoded)
|
||||
case *lbcutil.AddressTaproot:
|
||||
saddr = lbcutil.TstAddressTaprootSAddr(encoded)
|
||||
}
|
||||
|
||||
// Check script address, as well as the Hash160 method for P2PKH and
|
||||
|
|
|
@ -82,7 +82,7 @@ func NewAmount(f float64) (Amount, error) {
|
|||
case math.IsInf(f, 1):
|
||||
fallthrough
|
||||
case math.IsInf(f, -1):
|
||||
return 0, errors.New("invalid bitcoin amount")
|
||||
return 0, errors.New("invalid coin amount")
|
||||
}
|
||||
|
||||
return round(f * SatoshiPerBitcoin), nil
|
||||
|
@ -101,7 +101,7 @@ func (a Amount) ToBTC() float64 {
|
|||
|
||||
// Format formats a monetary amount counted in bitcoin base units as a
|
||||
// string for a given unit. The conversion will succeed for any unit,
|
||||
// however, known units will be formated with an appended label describing
|
||||
// however, known units will be formatted with an appended label describing
|
||||
// the units with SI notation, or "Satoshi" for the base unit.
|
||||
func (a Amount) Format(u AmountUnit) string {
|
||||
units := " " + u.String()
|
||||
|
|
|
@ -27,25 +27,25 @@ func TestAmountCreation(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "max producible",
|
||||
amount: 21e6,
|
||||
amount: 21e9,
|
||||
valid: true,
|
||||
expected: MaxSatoshi,
|
||||
},
|
||||
{
|
||||
name: "min producible",
|
||||
amount: -21e6,
|
||||
amount: -21e9,
|
||||
valid: true,
|
||||
expected: -MaxSatoshi,
|
||||
},
|
||||
{
|
||||
name: "exceeds max producible",
|
||||
amount: 21e6 + 1e-8,
|
||||
amount: 21e9 + 1e-8,
|
||||
valid: true,
|
||||
expected: MaxSatoshi + 1,
|
||||
},
|
||||
{
|
||||
name: "exceeds min producible",
|
||||
amount: -21e6 - 1e-8,
|
||||
amount: -21e9 - 1e-8,
|
||||
valid: true,
|
||||
expected: -MaxSatoshi - 1,
|
||||
},
|
||||
|
@ -122,8 +122,8 @@ func TestAmountUnitConversions(t *testing.T) {
|
|||
name: "MLBC",
|
||||
amount: MaxSatoshi,
|
||||
unit: AmountMegaBTC,
|
||||
converted: 21,
|
||||
s: "21 MLBC",
|
||||
converted: 21000,
|
||||
s: "21000 MLBC",
|
||||
},
|
||||
{
|
||||
name: "kLBC",
|
||||
|
|
|
@ -28,7 +28,7 @@ func checksum(input []byte) (cksum [4]byte) {
|
|||
func CheckEncode(input []byte, version byte) string {
|
||||
b := make([]byte, 0, 1+len(input)+4)
|
||||
b = append(b, version)
|
||||
b = append(b, input[:]...)
|
||||
b = append(b, input...)
|
||||
cksum := checksum(b)
|
||||
b = append(b, cksum[:]...)
|
||||
return Encode(b)
|
||||
|
|
|
@ -37,11 +37,14 @@ func TestBase58Check(t *testing.T) {
|
|||
|
||||
// test decoding
|
||||
res, version, err := base58.CheckDecode(test.out)
|
||||
if err != nil {
|
||||
switch {
|
||||
case err != nil:
|
||||
t.Errorf("CheckDecode test #%d failed with err: %v", x, err)
|
||||
} else if version != test.version {
|
||||
|
||||
case version != test.version:
|
||||
t.Errorf("CheckDecode test #%d failed: got version: %d want: %d", x, version, test.version)
|
||||
} else if string(res) != test.in {
|
||||
|
||||
case string(res) != test.in:
|
||||
t.Errorf("CheckDecode test #%d failed: got: %s want: %s", x, res, test.in)
|
||||
}
|
||||
}
|
||||
|
@ -56,7 +59,7 @@ func TestBase58Check(t *testing.T) {
|
|||
// bytes are missing).
|
||||
testString := ""
|
||||
for len := 0; len < 4; len++ {
|
||||
testString = testString + "x"
|
||||
testString += "x"
|
||||
_, _, err = base58.CheckDecode(testString)
|
||||
if err != base58.ErrInvalidFormat {
|
||||
t.Error("Checkdecode test failed, expected ErrInvalidFormat")
|
||||
|
|
142
bech32/bech32.go
142
bech32/bech32.go
|
@ -123,8 +123,11 @@ func bech32Polymod(hrp string, values, checksum []byte) int {
|
|||
// and 126), otherwise the results are undefined.
|
||||
//
|
||||
// For more details on the checksum calculation, please refer to BIP 173.
|
||||
func writeBech32Checksum(hrp string, data []byte, bldr *strings.Builder) {
|
||||
polymod := bech32Polymod(hrp, data, nil) ^ 1
|
||||
func writeBech32Checksum(hrp string, data []byte, bldr *strings.Builder,
|
||||
version Version) {
|
||||
|
||||
bech32Const := int(VersionToConsts[version])
|
||||
polymod := bech32Polymod(hrp, data, nil) ^ bech32Const
|
||||
for i := 0; i < 6; i++ {
|
||||
b := byte((polymod >> uint(5*(5-i))) & 31)
|
||||
|
||||
|
@ -137,38 +140,47 @@ func writeBech32Checksum(hrp string, data []byte, bldr *strings.Builder) {
|
|||
|
||||
// bech32VerifyChecksum verifies whether the bech32 string specified by the
|
||||
// provided hrp and payload data (encoded as 5 bits per element byte slice) has
|
||||
// the correct checksum suffix.
|
||||
// the correct checksum suffix. The version of bech32 used (bech32 OG, or
|
||||
// bech32m) is also returned to allow the caller to perform proper address
|
||||
// validation (segwitv0 should use bech32, v1+ should use bech32m).
|
||||
//
|
||||
// Data MUST have more than 6 elements, otherwise this function panics.
|
||||
//
|
||||
// For more details on the checksum verification, please refer to BIP 173.
|
||||
func bech32VerifyChecksum(hrp string, data []byte) bool {
|
||||
func bech32VerifyChecksum(hrp string, data []byte) (Version, bool) {
|
||||
checksum := data[len(data)-6:]
|
||||
values := data[:len(data)-6]
|
||||
polymod := bech32Polymod(hrp, values, checksum)
|
||||
return polymod == 1
|
||||
|
||||
// Before BIP-350, we'd always check this against a static constant of
|
||||
// 1 to know if the checksum was computed properly. As we want to
|
||||
// generically support decoding for bech32m as well as bech32, we'll
|
||||
// look up the returned value and compare it to the set of defined
|
||||
// constants.
|
||||
bech32Version, ok := ConstsToVersion[ChecksumConst(polymod)]
|
||||
if ok {
|
||||
return bech32Version, true
|
||||
}
|
||||
|
||||
return VersionUnknown, false
|
||||
}
|
||||
|
||||
// DecodeNoLimit decodes a bech32 encoded string, returning the human-readable
|
||||
// part and the data part excluding the checksum. This function does NOT
|
||||
// validate against the BIP-173 maximum length allowed for bech32 strings and
|
||||
// is meant for use in custom applications (such as lightning network payment
|
||||
// requests), NOT on-chain addresses.
|
||||
//
|
||||
// Note that the returned data is 5-bit (base32) encoded and the human-readable
|
||||
// part will be lowercase.
|
||||
func DecodeNoLimit(bech string) (string, []byte, error) {
|
||||
// DecodeNoLimit is a bech32 checksum version aware arbitrary string length
|
||||
// decoder. This function will return the version of the decoded checksum
|
||||
// constant so higher level validation can be performed to ensure the correct
|
||||
// version of bech32 was used when encoding.
|
||||
func decodeNoLimit(bech string) (string, []byte, Version, error) {
|
||||
// The minimum allowed size of a bech32 string is 8 characters, since it
|
||||
// needs a non-empty HRP, a separator, and a 6 character checksum.
|
||||
if len(bech) < 8 {
|
||||
return "", nil, ErrInvalidLength(len(bech))
|
||||
return "", nil, VersionUnknown, ErrInvalidLength(len(bech))
|
||||
}
|
||||
|
||||
// Only ASCII characters between 33 and 126 are allowed.
|
||||
var hasLower, hasUpper bool
|
||||
for i := 0; i < len(bech); i++ {
|
||||
if bech[i] < 33 || bech[i] > 126 {
|
||||
return "", nil, ErrInvalidCharacter(bech[i])
|
||||
return "", nil, VersionUnknown, ErrInvalidCharacter(bech[i])
|
||||
}
|
||||
|
||||
// The characters must be either all lowercase or all uppercase. Testing
|
||||
|
@ -176,7 +188,7 @@ func DecodeNoLimit(bech string) (string, []byte, error) {
|
|||
hasLower = hasLower || (bech[i] >= 97 && bech[i] <= 122)
|
||||
hasUpper = hasUpper || (bech[i] >= 65 && bech[i] <= 90)
|
||||
if hasLower && hasUpper {
|
||||
return "", nil, ErrMixedCase{}
|
||||
return "", nil, VersionUnknown, ErrMixedCase{}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -191,7 +203,7 @@ func DecodeNoLimit(bech string) (string, []byte, error) {
|
|||
// last 6 characters of the string (since checksum cannot contain '1').
|
||||
one := strings.LastIndexByte(bech, '1')
|
||||
if one < 1 || one+7 > len(bech) {
|
||||
return "", nil, ErrInvalidSeparatorIndex(one)
|
||||
return "", nil, VersionUnknown, ErrInvalidSeparatorIndex(one)
|
||||
}
|
||||
|
||||
// The human-readable part is everything before the last '1'.
|
||||
|
@ -202,12 +214,13 @@ func DecodeNoLimit(bech string) (string, []byte, error) {
|
|||
// 'charset'.
|
||||
decoded, err := toBytes(data)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
return "", nil, VersionUnknown, err
|
||||
}
|
||||
|
||||
// Verify if the checksum (stored inside decoded[:]) is valid, given the
|
||||
// previously decoded hrp.
|
||||
if !bech32VerifyChecksum(hrp, decoded) {
|
||||
bech32Version, ok := bech32VerifyChecksum(hrp, decoded)
|
||||
if !ok {
|
||||
// Invalid checksum. Calculate what it should have been, so that the
|
||||
// error contains this information.
|
||||
|
||||
|
@ -215,21 +228,42 @@ func DecodeNoLimit(bech string) (string, []byte, error) {
|
|||
actual := bech[len(bech)-6:]
|
||||
payload := decoded[:len(decoded)-6]
|
||||
|
||||
// Calculate the expected checksum, given the hrp and payload data.
|
||||
// Calculate the expected checksum, given the hrp and payload
|
||||
// data. We'll actually compute _both_ possibly valid checksum
|
||||
// to further aide in debugging.
|
||||
var expectedBldr strings.Builder
|
||||
expectedBldr.Grow(6)
|
||||
writeBech32Checksum(hrp, payload, &expectedBldr)
|
||||
expected := expectedBldr.String()
|
||||
writeBech32Checksum(hrp, payload, &expectedBldr, Version0)
|
||||
expectedVersion0 := expectedBldr.String()
|
||||
|
||||
var b strings.Builder
|
||||
b.Grow(6)
|
||||
writeBech32Checksum(hrp, payload, &expectedBldr, VersionM)
|
||||
expectedVersionM := expectedBldr.String()
|
||||
|
||||
err = ErrInvalidChecksum{
|
||||
Expected: expected,
|
||||
Actual: actual,
|
||||
Expected: expectedVersion0,
|
||||
ExpectedM: expectedVersionM,
|
||||
Actual: actual,
|
||||
}
|
||||
return "", nil, err
|
||||
return "", nil, VersionUnknown, err
|
||||
}
|
||||
|
||||
// We exclude the last 6 bytes, which is the checksum.
|
||||
return hrp, decoded[:len(decoded)-6], nil
|
||||
return hrp, decoded[:len(decoded)-6], bech32Version, nil
|
||||
}
|
||||
|
||||
// DecodeNoLimit decodes a bech32 encoded string, returning the human-readable
|
||||
// part and the data part excluding the checksum. This function does NOT
|
||||
// validate against the BIP-173 maximum length allowed for bech32 strings and
|
||||
// is meant for use in custom applications (such as lightning network payment
|
||||
// requests), NOT on-chain addresses.
|
||||
//
|
||||
// Note that the returned data is 5-bit (base32) encoded and the human-readable
|
||||
// part will be lowercase.
|
||||
func DecodeNoLimit(bech string) (string, []byte, error) {
|
||||
hrp, data, _, err := decodeNoLimit(bech)
|
||||
return hrp, data, err
|
||||
}
|
||||
|
||||
// Decode decodes a bech32 encoded string, returning the human-readable part and
|
||||
|
@ -243,16 +277,31 @@ func Decode(bech string) (string, []byte, error) {
|
|||
return "", nil, ErrInvalidLength(len(bech))
|
||||
}
|
||||
|
||||
return DecodeNoLimit(bech)
|
||||
hrp, data, _, err := decodeNoLimit(bech)
|
||||
return hrp, data, err
|
||||
}
|
||||
|
||||
// Encode encodes a byte slice into a bech32 string with the given
|
||||
// human-readable part (HRP). The HRP will be converted to lowercase if needed
|
||||
// since mixed cased encodings are not permitted and lowercase is used for
|
||||
// checksum purposes. Note that the bytes must each encode 5 bits (base32).
|
||||
func Encode(hrp string, data []byte) (string, error) {
|
||||
// The resulting bech32 string is the concatenation of the lowercase hrp,
|
||||
// the separator 1, data and the 6-byte checksum.
|
||||
// DecodeGeneric is identical to the existing Decode method, but will also
|
||||
// return bech32 version that matches the decoded checksum. This method should
|
||||
// be used when decoding segwit addresses, as it enables additional
|
||||
// verification to ensure the proper checksum is used.
|
||||
func DecodeGeneric(bech string) (string, []byte, Version, error) {
|
||||
// The maximum allowed length for a bech32 string is 90.
|
||||
if len(bech) > 90 {
|
||||
return "", nil, VersionUnknown, ErrInvalidLength(len(bech))
|
||||
}
|
||||
|
||||
return decodeNoLimit(bech)
|
||||
}
|
||||
|
||||
// encodeGeneric is the base bech32 encoding function that is aware of the
|
||||
// existence of the checksum versions. This method is private, as the Encode
|
||||
// and EncodeM methods are intended to be used instead.
|
||||
func encodeGeneric(hrp string, data []byte,
|
||||
version Version) (string, error) {
|
||||
|
||||
// The resulting bech32 string is the concatenation of the lowercase
|
||||
// hrp, the separator 1, data and the 6-byte checksum.
|
||||
hrp = strings.ToLower(hrp)
|
||||
var bldr strings.Builder
|
||||
bldr.Grow(len(hrp) + 1 + len(data) + 6)
|
||||
|
@ -268,11 +317,26 @@ func Encode(hrp string, data []byte) (string, error) {
|
|||
}
|
||||
|
||||
// Calculate and write the checksum of the data.
|
||||
writeBech32Checksum(hrp, data, &bldr)
|
||||
writeBech32Checksum(hrp, data, &bldr, version)
|
||||
|
||||
return bldr.String(), nil
|
||||
}
|
||||
|
||||
// Encode encodes a byte slice into a bech32 string with the given
|
||||
// human-readable part (HRP). The HRP will be converted to lowercase if needed
|
||||
// since mixed cased encodings are not permitted and lowercase is used for
|
||||
// checksum purposes. Note that the bytes must each encode 5 bits (base32).
|
||||
func Encode(hrp string, data []byte) (string, error) {
|
||||
return encodeGeneric(hrp, data, Version0)
|
||||
}
|
||||
|
||||
// EncodeM is the exactly same as the Encode method, but it uses the new
|
||||
// bech32m constant instead of the original one. It should be used whenever one
|
||||
// attempts to encode a segwit address of v1 and beyond.
|
||||
func EncodeM(hrp string, data []byte) (string, error) {
|
||||
return encodeGeneric(hrp, data, VersionM)
|
||||
}
|
||||
|
||||
// ConvertBits converts a byte slice where each byte is encoding fromBits bits,
|
||||
// to a byte slice where each byte is encoding toBits bits.
|
||||
func ConvertBits(data []byte, fromBits, toBits uint8, pad bool) ([]byte, error) {
|
||||
|
@ -298,7 +362,7 @@ func ConvertBits(data []byte, fromBits, toBits uint8, pad bool) ([]byte, error)
|
|||
for _, b := range data {
|
||||
|
||||
// Discard unused bits.
|
||||
b = b << (8 - fromBits)
|
||||
b <<= 8 - fromBits
|
||||
|
||||
// How many bits remaining to extract from the input data.
|
||||
remFromBits := fromBits
|
||||
|
@ -319,7 +383,7 @@ func ConvertBits(data []byte, fromBits, toBits uint8, pad bool) ([]byte, error)
|
|||
|
||||
// Discard the bits we just extracted and get ready for
|
||||
// next iteration.
|
||||
b = b << toExtract
|
||||
b <<= toExtract
|
||||
remFromBits -= toExtract
|
||||
filledBits += toExtract
|
||||
|
||||
|
@ -335,7 +399,7 @@ func ConvertBits(data []byte, fromBits, toBits uint8, pad bool) ([]byte, error)
|
|||
|
||||
// We pad any unfinished group if specified.
|
||||
if pad && filledBits > 0 {
|
||||
nextByte = nextByte << (toBits - filledBits)
|
||||
nextByte <<= toBits - filledBits
|
||||
regrouped = append(regrouped, nextByte)
|
||||
filledBits = 0
|
||||
nextByte = 0
|
||||
|
|
|
@ -22,17 +22,18 @@ func TestBech32(t *testing.T) {
|
|||
expectedError error
|
||||
}{
|
||||
{"A12UEL5L", nil},
|
||||
{"a12uel5l", nil},
|
||||
{"an83characterlonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1tt5tgs", nil},
|
||||
{"abcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lmqqqxw", nil},
|
||||
{"11qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqc8247j", nil},
|
||||
{"split1checkupstagehandshakeupstreamerranterredcaperred2y9e3w", nil},
|
||||
{"split1checkupstagehandshakeupstreamerranterredcaperred2y9e2w", ErrInvalidChecksum{"2y9e3w", "2y9e2w"}}, // invalid checksum
|
||||
{"s lit1checkupstagehandshakeupstreamerranterredcaperredp8hs2p", ErrInvalidCharacter(' ')}, // invalid character (space) in hrp
|
||||
{"spl\x7Ft1checkupstagehandshakeupstreamerranterredcaperred2y9e3w", ErrInvalidCharacter(127)}, // invalid character (DEL) in hrp
|
||||
{"split1cheo2y9e2w", ErrNonCharsetChar('o')}, // invalid character (o) in data part
|
||||
{"split1a2y9w", ErrInvalidSeparatorIndex(5)}, // too short data part
|
||||
{"1checkupstagehandshakeupstreamerranterredcaperred2y9e3w", ErrInvalidSeparatorIndex(0)}, // empty hrp
|
||||
{"11qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqsqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqc8247j", ErrInvalidLength(91)}, // too long
|
||||
{"split1checkupstagehandshakeupstreamerranterredcaperred2y9e2w", ErrInvalidChecksum{"2y9e3w", "2y9e3wlc445v", "2y9e2w"}}, // invalid checksum
|
||||
{"s lit1checkupstagehandshakeupstreamerranterredcaperredp8hs2p", ErrInvalidCharacter(' ')}, // invalid character (space) in hrp
|
||||
{"spl\x7Ft1checkupstagehandshakeupstreamerranterredcaperred2y9e3w", ErrInvalidCharacter(127)}, // invalid character (DEL) in hrp
|
||||
{"split1cheo2y9e2w", ErrNonCharsetChar('o')}, // invalid character (o) in data part
|
||||
{"split1a2y9w", ErrInvalidSeparatorIndex(5)}, // too short data part
|
||||
{"1checkupstagehandshakeupstreamerranterredcaperred2y9e3w", ErrInvalidSeparatorIndex(0)}, // empty hrp
|
||||
{"11qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqsqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqc8247j", ErrInvalidLength(91)}, // too long
|
||||
|
||||
// Additional test vectors used in bitcoin core
|
||||
{" 1nwldj5", ErrInvalidCharacter(' ')},
|
||||
|
@ -44,7 +45,7 @@ func TestBech32(t *testing.T) {
|
|||
{"x1b4n0q5v", ErrNonCharsetChar(98)},
|
||||
{"li1dgmt3", ErrInvalidSeparatorIndex(2)},
|
||||
{"de1lg7wt\xff", ErrInvalidCharacter(0xff)},
|
||||
{"A1G7SGD8", ErrInvalidChecksum{"2uel5l", "g7sgd8"}},
|
||||
{"A1G7SGD8", ErrInvalidChecksum{"2uel5l", "2uel5llqfn3a", "g7sgd8"}},
|
||||
{"10a06t8", ErrInvalidLength(7)},
|
||||
{"1qzzfhee", ErrInvalidSeparatorIndex(0)},
|
||||
{"a12UEL5L", ErrMixedCase{}},
|
||||
|
@ -86,6 +87,127 @@ func TestBech32(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestBech32M tests that the following set of strings, based on the test
|
||||
// vectors in BIP-350 are either valid or invalid using the new bech32m
|
||||
// checksum algo. Some of these strings are similar to the set of above test
|
||||
// vectors, but end up with different checksums.
|
||||
func TestBech32M(t *testing.T) {
|
||||
tests := []struct {
|
||||
str string
|
||||
expectedError error
|
||||
}{
|
||||
{"A1LQFN3A", nil},
|
||||
{"a1lqfn3a", nil},
|
||||
{"an83characterlonghumanreadablepartthatcontainsthetheexcludedcharactersbioandnumber11sg7hg6", nil},
|
||||
{"abcdef1l7aum6echk45nj3s0wdvt2fg8x9yrzpqzd3ryx", nil},
|
||||
{"11llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllludsr8", nil},
|
||||
{"split1checkupstagehandshakeupstreamerranterredcaperredlc445v", nil},
|
||||
{"?1v759aa", nil},
|
||||
|
||||
// Additional test vectors used in bitcoin core
|
||||
{"\x201xj0phk", ErrInvalidCharacter('\x20')},
|
||||
{"\x7f1g6xzxy", ErrInvalidCharacter('\x7f')},
|
||||
{"\x801vctc34", ErrInvalidCharacter('\x80')},
|
||||
{"an84characterslonghumanreadablepartthatcontainsthetheexcludedcharactersbioandnumber11d6pts4", ErrInvalidLength(91)},
|
||||
{"qyrz8wqd2c9m", ErrInvalidSeparatorIndex(-1)},
|
||||
{"1qyrz8wqd2c9m", ErrInvalidSeparatorIndex(0)},
|
||||
{"y1b0jsk6g", ErrNonCharsetChar(98)},
|
||||
{"lt1igcx5c0", ErrNonCharsetChar(105)},
|
||||
{"in1muywd", ErrInvalidSeparatorIndex(2)},
|
||||
{"mm1crxm3i", ErrNonCharsetChar(105)},
|
||||
{"au1s5cgom", ErrNonCharsetChar(111)},
|
||||
{"M1VUXWEZ", ErrInvalidChecksum{"mzl49c", "mzl49cw70eq6", "vuxwez"}},
|
||||
{"16plkw9", ErrInvalidLength(7)},
|
||||
{"1p2gdwpf", ErrInvalidSeparatorIndex(0)},
|
||||
|
||||
{" 1nwldj5", ErrInvalidCharacter(' ')},
|
||||
{"\x7f" + "1axkwrx", ErrInvalidCharacter(0x7f)},
|
||||
{"\x801eym55h", ErrInvalidCharacter(0x80)},
|
||||
}
|
||||
|
||||
for i, test := range tests {
|
||||
str := test.str
|
||||
hrp, decoded, err := Decode(str)
|
||||
if test.expectedError != err {
|
||||
t.Errorf("%d: (%v) expected decoding error %v "+
|
||||
"instead got %v", i, str, test.expectedError,
|
||||
err)
|
||||
continue
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
// End test case here if a decoding error was expected.
|
||||
continue
|
||||
}
|
||||
|
||||
// Check that it encodes to the same string, using bech32 m.
|
||||
encoded, err := EncodeM(hrp, decoded)
|
||||
if err != nil {
|
||||
t.Errorf("encoding failed: %v", err)
|
||||
}
|
||||
|
||||
if encoded != strings.ToLower(str) {
|
||||
t.Errorf("expected data to encode to %v, but got %v",
|
||||
str, encoded)
|
||||
}
|
||||
|
||||
// Flip a bit in the string an make sure it is caught.
|
||||
pos := strings.LastIndexAny(str, "1")
|
||||
flipped := str[:pos+1] + string((str[pos+1] ^ 1)) + str[pos+2:]
|
||||
_, _, err = Decode(flipped)
|
||||
if err == nil {
|
||||
t.Error("expected decoding to fail")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestBech32DecodeGeneric tests that given a bech32 string, or a bech32m
|
||||
// string, the proper checksum version is returned so that callers can perform
|
||||
// segwit addr validation.
|
||||
func TestBech32DecodeGeneric(t *testing.T) {
|
||||
tests := []struct {
|
||||
str string
|
||||
version Version
|
||||
}{
|
||||
{"A1LQFN3A", VersionM},
|
||||
{"a1lqfn3a", VersionM},
|
||||
{"an83characterlonghumanreadablepartthatcontainsthetheexcludedcharactersbioandnumber11sg7hg6", VersionM},
|
||||
{"abcdef1l7aum6echk45nj3s0wdvt2fg8x9yrzpqzd3ryx", VersionM},
|
||||
{"11llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllludsr8", VersionM},
|
||||
{"split1checkupstagehandshakeupstreamerranterredcaperredlc445v", VersionM},
|
||||
{"?1v759aa", VersionM},
|
||||
|
||||
{"A12UEL5L", Version0},
|
||||
{"a12uel5l", Version0},
|
||||
{"an83characterlonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1tt5tgs", Version0},
|
||||
{"abcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lmqqqxw", Version0},
|
||||
{"11qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqc8247j", Version0},
|
||||
{"split1checkupstagehandshakeupstreamerranterredcaperred2y9e3w", Version0},
|
||||
|
||||
{"BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4", Version0},
|
||||
{"tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7", Version0},
|
||||
{"bc1pw508d6qejxtdg4y5r3zarvary0c5xw7kw508d6qejxtdg4y5r3zarvary0c5xw7kt5nd6y", VersionM},
|
||||
{"BC1SW50QGDZ25J", VersionM},
|
||||
{"bc1zw508d6qejxtdg4y5r3zarvaryvaxxpcs", VersionM},
|
||||
{"tb1qqqqqp399et2xygdj5xreqhjjvcmzhxw4aywxecjdzew6hylgvsesrxh6hy", Version0},
|
||||
{"tb1pqqqqp399et2xygdj5xreqhjjvcmzhxw4aywxecjdzew6hylgvsesf3hn0c", VersionM},
|
||||
{"bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqzk5jj0", VersionM},
|
||||
}
|
||||
for i, test := range tests {
|
||||
_, _, version, err := DecodeGeneric(test.str)
|
||||
if err != nil {
|
||||
t.Errorf("%d: (%v) unexpected error during "+
|
||||
"decoding: %v", i, test.str, err)
|
||||
continue
|
||||
}
|
||||
|
||||
if version != test.version {
|
||||
t.Errorf("(%v): invalid version: expected %v, got %v",
|
||||
test.str, test.version, version)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestMixedCaseEncode ensures mixed case HRPs are converted to lowercase as
|
||||
// expected when encoding and that decoding the produced encoding when converted
|
||||
// to all uppercase produces the lowercase HRP and original data.
|
||||
|
@ -242,7 +364,7 @@ func TestBech32Base256(t *testing.T) {
|
|||
}, {
|
||||
name: "same as previous but with checksum invalidated",
|
||||
encoded: "split1checkupstagehandshakeupstreamerranterredcaperred2y9e2w",
|
||||
err: ErrInvalidChecksum{"2y9e3w", "2y9e2w"},
|
||||
err: ErrInvalidChecksum{"2y9e3w", "2y9e3wlc445v", "2y9e2w"},
|
||||
}, {
|
||||
name: "hrp with invalid character (space)",
|
||||
encoded: "s lit1checkupstagehandshakeupstreamerranterredcaperredp8hs2p",
|
||||
|
|
|
@ -65,15 +65,17 @@ func (e ErrNonCharsetChar) Error() string {
|
|||
}
|
||||
|
||||
// ErrInvalidChecksum is returned when the extracted checksum of the string
|
||||
// is different than what was expected.
|
||||
// is different than what was expected. Both the original version, as well as
|
||||
// the new bech32m checksum may be specified.
|
||||
type ErrInvalidChecksum struct {
|
||||
Expected string
|
||||
Actual string
|
||||
Expected string
|
||||
ExpectedM string
|
||||
Actual string
|
||||
}
|
||||
|
||||
func (e ErrInvalidChecksum) Error() string {
|
||||
return fmt.Sprintf("invalid checksum (expected %v got %v)",
|
||||
e.Expected, e.Actual)
|
||||
return fmt.Sprintf("invalid checksum (expected (bech32=%v, "+
|
||||
"bech32m=%v), got %v)", e.Expected, e.ExpectedM, e.Actual)
|
||||
}
|
||||
|
||||
// ErrInvalidDataByte is returned when a byte outside the range required for
|
||||
|
|
43
bech32/version.go
Normal file
43
bech32/version.go
Normal file
|
@ -0,0 +1,43 @@
|
|||
package bech32
|
||||
|
||||
// ChecksumConst is a type that represents the currently defined bech32
|
||||
// checksum constants.
|
||||
type ChecksumConst int
|
||||
|
||||
const (
|
||||
// Version0Const is the original constant used in the checksum
|
||||
// verification for bech32.
|
||||
Version0Const ChecksumConst = 1
|
||||
|
||||
// VersionMConst is the new constant used for bech32m checksum
|
||||
// verification.
|
||||
VersionMConst ChecksumConst = 0x2bc830a3
|
||||
)
|
||||
|
||||
// Version defines the current set of bech32 versions.
|
||||
type Version uint8
|
||||
|
||||
const (
|
||||
// Version0 defines the original bech version.
|
||||
Version0 Version = iota
|
||||
|
||||
// VersionM is the new bech32 version defined in BIP-350, also known as
|
||||
// bech32m.
|
||||
VersionM
|
||||
|
||||
// VersionUnknown denotes an unknown bech version.
|
||||
VersionUnknown
|
||||
)
|
||||
|
||||
// VersionToConsts maps bech32 versions to the checksum constant to be used
|
||||
// when encoding, and asserting a particular version when decoding.
|
||||
var VersionToConsts = map[Version]ChecksumConst{
|
||||
Version0: Version0Const,
|
||||
VersionM: VersionMConst,
|
||||
}
|
||||
|
||||
// ConstsToVersion maps a bech32 constant to the version it's associated with.
|
||||
var ConstsToVersion = map[ChecksumConst]Version{
|
||||
Version0Const: Version0,
|
||||
VersionMConst: VersionM,
|
||||
}
|
|
@ -11,10 +11,10 @@ import (
|
|||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/davecgh/go-spew/spew"
|
||||
"github.com/lbryio/lbcd/chaincfg/chainhash"
|
||||
"github.com/lbryio/lbcd/wire"
|
||||
"github.com/lbryio/lbcutil"
|
||||
"github.com/davecgh/go-spew/spew"
|
||||
)
|
||||
|
||||
// TestBlock tests the API for Block.
|
||||
|
|
|
@ -492,158 +492,6 @@ func TestFilterInsertUpdateNone(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestFilterInsertP2PubKeyOnly(t *testing.T) {
|
||||
blockStr := "0100000082bb869cf3a793432a66e826e05a6fc37469f8efb7421dc" +
|
||||
"880670100000000007f16c5962e8bd963659c793ce370d95f093bc7e367" +
|
||||
"117b3c30c1f8fdd0d9728776381b4d4c86041b554b85290701000000010" +
|
||||
"00000000000000000000000000000000000000000000000000000000000" +
|
||||
"0000ffffffff07044c86041b0136ffffffff0100f2052a0100000043410" +
|
||||
"4eaafc2314def4ca98ac970241bcab022b9c1e1f4ea423a20f134c876f2" +
|
||||
"c01ec0f0dd5b2e86e7168cefe0d81113c3807420ce13ad1357231a22522" +
|
||||
"47d97a46a91ac000000000100000001bcad20a6a29827d1424f08989255" +
|
||||
"120bf7f3e9e3cdaaa6bb31b0737fe048724300000000494830450220356" +
|
||||
"e834b046cadc0f8ebb5a8a017b02de59c86305403dad52cd77b55af062e" +
|
||||
"a10221009253cd6c119d4729b77c978e1e2aa19f5ea6e0e52b3f16e32fa" +
|
||||
"608cd5bab753901ffffffff02008d380c010000001976a9142b4b8072ec" +
|
||||
"bba129b6453c63e129e643207249ca88ac0065cd1d000000001976a9141" +
|
||||
"b8dd13b994bcfc787b32aeadf58ccb3615cbd5488ac0000000001000000" +
|
||||
"03fdacf9b3eb077412e7a968d2e4f11b9a9dee312d666187ed77ee7d26a" +
|
||||
"f16cb0b000000008c493046022100ea1608e70911ca0de5af51ba57ad23" +
|
||||
"b9a51db8d28f82c53563c56a05c20f5a87022100a8bdc8b4a8acc8634c6" +
|
||||
"b420410150775eb7f2474f5615f7fccd65af30f310fbf01410465fdf49e" +
|
||||
"29b06b9a1582287b6279014f834edc317695d125ef623c1cc3aaece245b" +
|
||||
"d69fcad7508666e9c74a49dc9056d5fc14338ef38118dc4afae5fe2c585" +
|
||||
"caffffffff309e1913634ecb50f3c4f83e96e70b2df071b497b8973a3e7" +
|
||||
"5429df397b5af83000000004948304502202bdb79c596a9ffc24e96f438" +
|
||||
"6199aba386e9bc7b6071516e2b51dda942b3a1ed022100c53a857e76b72" +
|
||||
"4fc14d45311eac5019650d415c3abb5428f3aae16d8e69bec2301ffffff" +
|
||||
"ff2089e33491695080c9edc18a428f7d834db5b6d372df13ce2b1b0e0cb" +
|
||||
"cb1e6c10000000049483045022100d4ce67c5896ee251c810ac1ff9cecc" +
|
||||
"d328b497c8f553ab6e08431e7d40bad6b5022033119c0c2b7d792d31f11" +
|
||||
"87779c7bd95aefd93d90a715586d73801d9b47471c601ffffffff010071" +
|
||||
"4460030000001976a914c7b55141d097ea5df7a0ed330cf794376e53ec8" +
|
||||
"d88ac0000000001000000045bf0e214aa4069a3e792ecee1e1bf0c1d397" +
|
||||
"cde8dd08138f4b72a00681743447000000008b48304502200c45de8c4f3" +
|
||||
"e2c1821f2fc878cba97b1e6f8807d94930713aa1c86a67b9bf1e4022100" +
|
||||
"8581abfef2e30f957815fc89978423746b2086375ca8ecf359c85c2a5b7" +
|
||||
"c88ad01410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf64852" +
|
||||
"61c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d" +
|
||||
"3ae37079b794a92d7ec95ffffffffd669f7d7958d40fc59d2253d88e0f2" +
|
||||
"48e29b599c80bbcec344a83dda5f9aa72c000000008a473044022078124" +
|
||||
"c8beeaa825f9e0b30bff96e564dd859432f2d0cb3b72d3d5d93d38d7e93" +
|
||||
"0220691d233b6c0f995be5acb03d70a7f7a65b6bc9bdd426260f38a1346" +
|
||||
"669507a3601410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6" +
|
||||
"485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270e" +
|
||||
"fb1d3ae37079b794a92d7ec95fffffffff878af0d93f5229a68166cf051" +
|
||||
"fd372bb7a537232946e0a46f53636b4dafdaa4000000008c49304602210" +
|
||||
"0c717d1714551663f69c3c5759bdbb3a0fcd3fab023abc0e522fe6440de" +
|
||||
"35d8290221008d9cbe25bffc44af2b18e81c58eb37293fd7fe1c2e7b46f" +
|
||||
"c37ee8c96c50ab1e201410462bb73f76ca0994fcb8b4271e6fb7561f5c0" +
|
||||
"f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f" +
|
||||
"4d87270efb1d3ae37079b794a92d7ec95ffffffff27f2b668859cd7f2f8" +
|
||||
"94aa0fd2d9e60963bcd07c88973f425f999b8cbfd7a1e2000000008c493" +
|
||||
"046022100e00847147cbf517bcc2f502f3ddc6d284358d102ed20d47a8a" +
|
||||
"a788a62f0db780022100d17b2d6fa84dcaf1c95d88d7e7c30385aecf415" +
|
||||
"588d749afd3ec81f6022cecd701410462bb73f76ca0994fcb8b4271e6fb" +
|
||||
"7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018" +
|
||||
"ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffff0100c817a8" +
|
||||
"040000001976a914b6efd80d99179f4f4ff6f4dd0a007d018c385d2188a" +
|
||||
"c000000000100000001834537b2f1ce8ef9373a258e10545ce5a50b758d" +
|
||||
"f616cd4356e0032554ebd3c4000000008b483045022100e68f422dd7c34" +
|
||||
"fdce11eeb4509ddae38201773dd62f284e8aa9d96f85099d0b002202243" +
|
||||
"bd399ff96b649a0fad05fa759d6a882f0af8c90cf7632c2840c29070aec" +
|
||||
"20141045e58067e815c2f464c6a2a15f987758374203895710c2d452442" +
|
||||
"e28496ff38ba8f5fd901dc20e29e88477167fe4fc299bf818fd0d9e1632" +
|
||||
"d467b2a3d9503b1aaffffffff0280d7e636030000001976a914f34c3e10" +
|
||||
"eb387efe872acb614c89e78bfca7815d88ac404b4c00000000001976a91" +
|
||||
"4a84e272933aaf87e1715d7786c51dfaeb5b65a6f88ac00000000010000" +
|
||||
"000143ac81c8e6f6ef307dfe17f3d906d999e23e0189fda838c5510d850" +
|
||||
"927e03ae7000000008c4930460221009c87c344760a64cb8ae6685a3eec" +
|
||||
"2c1ac1bed5b88c87de51acd0e124f266c16602210082d07c037359c3a25" +
|
||||
"7b5c63ebd90f5a5edf97b2ac1c434b08ca998839f346dd40141040ba7e5" +
|
||||
"21fa7946d12edbb1d1e95a15c34bd4398195e86433c92b431cd315f455f" +
|
||||
"e30032ede69cad9d1e1ed6c3c4ec0dbfced53438c625462afb792dcb098" +
|
||||
"544bffffffff0240420f00000000001976a9144676d1b820d63ec272f19" +
|
||||
"00d59d43bc6463d96f888ac40420f00000000001976a914648d04341d00" +
|
||||
"d7968b3405c034adc38d4d8fb9bd88ac00000000010000000248cc91750" +
|
||||
"1ea5c55f4a8d2009c0567c40cfe037c2e71af017d0a452ff705e3f10000" +
|
||||
"00008b483045022100bf5fdc86dc5f08a5d5c8e43a8c9d5b1ed8c65562e" +
|
||||
"280007b52b133021acd9acc02205e325d613e555f772802bf413d36ba80" +
|
||||
"7892ed1a690a77811d3033b3de226e0a01410429fa713b124484cb2bd7b" +
|
||||
"5557b2c0b9df7b2b1fee61825eadc5ae6c37a9920d38bfccdc7dc3cb0c4" +
|
||||
"7d7b173dbc9db8d37db0a33ae487982c59c6f8606e9d1791ffffffff41e" +
|
||||
"d70551dd7e841883ab8f0b16bf04176b7d1480e4f0af9f3d4c3595768d0" +
|
||||
"68000000008b4830450221008513ad65187b903aed1102d1d0c47688127" +
|
||||
"658c51106753fed0151ce9c16b80902201432b9ebcb87bd04ceb2de6603" +
|
||||
"5fbbaf4bf8b00d1cfe41f1a1f7338f9ad79d210141049d4cf80125bf50b" +
|
||||
"e1709f718c07ad15d0fc612b7da1f5570dddc35f2a352f0f27c978b0682" +
|
||||
"0edca9ef982c35fda2d255afba340068c5035552368bc7200c1488fffff" +
|
||||
"fff0100093d00000000001976a9148edb68822f1ad580b043c7b3df2e40" +
|
||||
"0f8699eb4888ac00000000"
|
||||
blockBytes, err := hex.DecodeString(blockStr)
|
||||
if err != nil {
|
||||
t.Errorf("TestFilterInsertP2PubKeyOnly DecodeString failed: %v", err)
|
||||
return
|
||||
}
|
||||
block, err := lbcutil.NewBlockFromBytes(blockBytes)
|
||||
if err != nil {
|
||||
t.Errorf("TestFilterInsertP2PubKeyOnly NewBlockFromBytes failed: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
f := bloom.NewFilter(10, 0, 0.000001, wire.BloomUpdateP2PubkeyOnly)
|
||||
|
||||
// Generation pubkey
|
||||
inputStr := "04eaafc2314def4ca98ac970241bcab022b9c1e1f4ea423a20f134c" +
|
||||
"876f2c01ec0f0dd5b2e86e7168cefe0d81113c3807420ce13ad1357231a" +
|
||||
"2252247d97a46a91"
|
||||
inputBytes, err := hex.DecodeString(inputStr)
|
||||
if err != nil {
|
||||
t.Errorf("TestFilterInsertP2PubKeyOnly DecodeString failed: %v", err)
|
||||
return
|
||||
}
|
||||
f.Add(inputBytes)
|
||||
|
||||
// Output address of 4th transaction
|
||||
inputStr = "b6efd80d99179f4f4ff6f4dd0a007d018c385d21"
|
||||
inputBytes, err = hex.DecodeString(inputStr)
|
||||
if err != nil {
|
||||
t.Errorf("TestFilterInsertP2PubKeyOnly DecodeString failed: %v", err)
|
||||
return
|
||||
}
|
||||
f.Add(inputBytes)
|
||||
|
||||
// Ignore return value -- this is just used to update the filter.
|
||||
_, _ = bloom.NewMerkleBlock(block, f)
|
||||
|
||||
// We should match the generation pubkey
|
||||
inputStr = "147caa76786596590baa4e98f5d9f48b86c7765e489f7a6ff3360fe5c674360b"
|
||||
hash, err := chainhash.NewHashFromStr(inputStr)
|
||||
if err != nil {
|
||||
t.Errorf("TestMerkleBlockP2PubKeyOnly NewHashFromStr failed: %v", err)
|
||||
return
|
||||
}
|
||||
outpoint := wire.NewOutPoint(hash, 0)
|
||||
if !f.MatchesOutPoint(outpoint) {
|
||||
t.Errorf("TestMerkleBlockP2PubKeyOnly didn't match the generation "+
|
||||
"outpoint %s", inputStr)
|
||||
return
|
||||
}
|
||||
|
||||
// We should not match the 4th transaction, which is not p2pk
|
||||
inputStr = "02981fa052f0481dbc5868f4fc2166035a10f27a03cfd2de67326471df5bc041"
|
||||
hash, err = chainhash.NewHashFromStr(inputStr)
|
||||
if err != nil {
|
||||
t.Errorf("TestMerkleBlockP2PubKeyOnly NewHashFromStr failed: %v", err)
|
||||
return
|
||||
}
|
||||
outpoint = wire.NewOutPoint(hash, 0)
|
||||
if f.MatchesOutPoint(outpoint) {
|
||||
t.Errorf("TestMerkleBlockP2PubKeyOnly matched outpoint %s", inputStr)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterReload(t *testing.T) {
|
||||
f := bloom.NewFilter(10, 0, 0.000001, wire.BloomUpdateAll)
|
||||
|
||||
|
|
|
@ -116,7 +116,7 @@ func NewMerkleBlock(block *lbcutil.Block, filter *Filter) (*wire.MsgMerkleBlock,
|
|||
Flags: make([]byte, (len(mBlock.bits)+7)/8),
|
||||
}
|
||||
for _, hash := range mBlock.finalHashes {
|
||||
msgMerkleBlock.AddTxHash(hash)
|
||||
_ = msgMerkleBlock.AddTxHash(hash)
|
||||
}
|
||||
for i := uint32(0); i < uint32(len(mBlock.bits)); i++ {
|
||||
msgMerkleBlock.Flags[i/8] |= mBlock.bits[i] << (i % 8)
|
||||
|
|
|
@ -61,7 +61,7 @@ func NewTLSCertPair(organization string, validUntil time.Time, extraHosts []stri
|
|||
|
||||
addIP := func(ipAddr net.IP) {
|
||||
for _, ip := range ipAddresses {
|
||||
if bytes.Equal(ip, ipAddr) {
|
||||
if ip.Equal(ipAddr) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
|
|
@ -33,7 +33,7 @@ func (c *TestCoin) ValueAge() int64 { return int64(c.TxValue) * c.TxNumCon
|
|||
|
||||
func NewCoin(index int64, value lbcutil.Amount, numConfs int64) coinset.Coin {
|
||||
h := sha256.New()
|
||||
h.Write([]byte(fmt.Sprintf("%d", index)))
|
||||
_, _ = h.Write([]byte(fmt.Sprintf("%d", index)))
|
||||
hash, _ := chainhash.NewHash(h.Sum(nil))
|
||||
c := &TestCoin{
|
||||
TxHash: hash,
|
||||
|
|
|
@ -18,9 +18,9 @@ func ExampleAmount() {
|
|||
a = lbcutil.Amount(1e5)
|
||||
fmt.Println("100,000 Satoshis:", a)
|
||||
// Output:
|
||||
// Zero Satoshi: 0 BTC
|
||||
// 100,000,000 Satoshis: 1 BTC
|
||||
// 100,000 Satoshis: 0.001 BTC
|
||||
// Zero Satoshi: 0 LBC
|
||||
// 100,000,000 Satoshis: 1 LBC
|
||||
// 100,000 Satoshis: 0.001 LBC
|
||||
}
|
||||
|
||||
func ExampleNewAmount() {
|
||||
|
@ -52,25 +52,25 @@ func ExampleNewAmount() {
|
|||
}
|
||||
fmt.Println(amountNaN) //Output 4
|
||||
|
||||
// Output: 1 BTC
|
||||
// 0.01234567 BTC
|
||||
// 0 BTC
|
||||
// invalid bitcoin amount
|
||||
// Output: 1 LBC
|
||||
// 0.01234567 LBC
|
||||
// 0 LBC
|
||||
// invalid coin amount
|
||||
}
|
||||
|
||||
func ExampleAmount_unitConversions() {
|
||||
amount := lbcutil.Amount(44433322211100)
|
||||
|
||||
fmt.Println("Satoshi to kBTC:", amount.Format(lbcutil.AmountKiloBTC))
|
||||
fmt.Println("Satoshi to BTC:", amount)
|
||||
fmt.Println("Satoshi to MilliBTC:", amount.Format(lbcutil.AmountMilliBTC))
|
||||
fmt.Println("Satoshi to MicroBTC:", amount.Format(lbcutil.AmountMicroBTC))
|
||||
fmt.Println("Satoshi to kLBC:", amount.Format(lbcutil.AmountKiloBTC))
|
||||
fmt.Println("Satoshi to LBC:", amount)
|
||||
fmt.Println("Satoshi to MilliLBC:", amount.Format(lbcutil.AmountMilliBTC))
|
||||
fmt.Println("Satoshi to MicroLBC:", amount.Format(lbcutil.AmountMicroBTC))
|
||||
fmt.Println("Satoshi to Satoshi:", amount.Format(lbcutil.AmountSatoshi))
|
||||
|
||||
// Output:
|
||||
// Satoshi to kBTC: 444.333222111 kBTC
|
||||
// Satoshi to BTC: 444333.222111 BTC
|
||||
// Satoshi to MilliBTC: 444333222.111 mBTC
|
||||
// Satoshi to MicroBTC: 444333222111 μBTC
|
||||
// Satoshi to kLBC: 444.333222111 kLBC
|
||||
// Satoshi to LBC: 444333.222111 LBC
|
||||
// Satoshi to MilliLBC: 444333222.111 mLBC
|
||||
// Satoshi to MicroLBC: 444333222111 μLBC
|
||||
// Satoshi to Satoshi: 44433322211100 Satoshi
|
||||
}
|
||||
|
|
|
@ -54,7 +54,7 @@ func RandomKey() ([gcs.KeySize]byte, error) {
|
|||
}
|
||||
|
||||
// Copy the byte slice to a [gcs.KeySize]byte array and return it.
|
||||
copy(key[:], randKey[:])
|
||||
copy(key[:], randKey)
|
||||
return key, nil
|
||||
}
|
||||
|
||||
|
@ -62,7 +62,7 @@ func RandomKey() ([gcs.KeySize]byte, error) {
|
|||
// truncating the bytes of the hash to the appopriate key size.
|
||||
func DeriveKey(keyHash *chainhash.Hash) [gcs.KeySize]byte {
|
||||
var key [gcs.KeySize]byte
|
||||
copy(key[:], keyHash.CloneBytes()[:])
|
||||
copy(key[:], keyHash.CloneBytes())
|
||||
return key
|
||||
}
|
||||
|
||||
|
|
|
@ -19,9 +19,6 @@ import (
|
|||
)
|
||||
|
||||
var (
|
||||
// No need to allocate an err variable in every test
|
||||
err error
|
||||
|
||||
// List of values for building a filter
|
||||
contents = [][]byte{
|
||||
[]byte("Alex"),
|
||||
|
|
|
@ -12,8 +12,8 @@ import (
|
|||
"sort"
|
||||
|
||||
"github.com/aead/siphash"
|
||||
"github.com/lbryio/lbcd/wire"
|
||||
"github.com/kkdai/bstream"
|
||||
"github.com/lbryio/lbcd/wire"
|
||||
)
|
||||
|
||||
// Inspired by https://github.com/rasky/gcs
|
||||
|
@ -91,7 +91,7 @@ type Filter struct {
|
|||
// BuildGCSFilter builds a new GCS filter with the collision probability of
|
||||
// `1/(2**P)`, key `key`, and including every `[]byte` in `data` as a member of
|
||||
// the set.
|
||||
func BuildGCSFilter(P uint8, M uint64, key [KeySize]byte, data [][]byte) (*Filter, error) {
|
||||
func BuildGCSFilter(P uint8, M uint64, key [KeySize]byte, data [][]byte) (*Filter, error) { // nolint:gocritic
|
||||
// Some initial parameter checks: make sure we have data from which to
|
||||
// build the filter, and make sure our parameters will fit the hash
|
||||
// function we're using.
|
||||
|
@ -174,7 +174,7 @@ func BuildGCSFilter(P uint8, M uint64, key [KeySize]byte, data [][]byte) (*Filte
|
|||
|
||||
// FromBytes deserializes a GCS filter from a known N, P, and serialized filter
|
||||
// as returned by Bytes().
|
||||
func FromBytes(N uint32, P uint8, M uint64, d []byte) (*Filter, error) {
|
||||
func FromBytes(N uint32, P uint8, M uint64, d []byte) (*Filter, error) { // nolint:gocritic
|
||||
// Basic sanity check.
|
||||
if P > 32 {
|
||||
return nil, ErrPTooBig
|
||||
|
@ -200,7 +200,7 @@ func FromBytes(N uint32, P uint8, M uint64, d []byte) (*Filter, error) {
|
|||
|
||||
// FromNBytes deserializes a GCS filter from a known P, and serialized N and
|
||||
// filter as returned by NBytes().
|
||||
func FromNBytes(P uint8, M uint64, d []byte) (*Filter, error) {
|
||||
func FromNBytes(P uint8, M uint64, d []byte) (*Filter, error) { // nolint:gocritic
|
||||
buffer := bytes.NewBuffer(d)
|
||||
N, err := wire.ReadVarInt(buffer, varIntProtoVer)
|
||||
if err != nil {
|
||||
|
|
|
@ -27,7 +27,7 @@ var (
|
|||
// Filters are conserved between tests but we must define with an
|
||||
// interface which functions we're testing because the gcsFilter type
|
||||
// isn't exported
|
||||
filter, filter2, filter3, filter4, filter5 *gcs.Filter
|
||||
filter, filter2, filter3 *gcs.Filter
|
||||
|
||||
// We need to use the same key for building and querying the filters
|
||||
key [gcs.KeySize]byte
|
||||
|
@ -328,6 +328,8 @@ func TestGCSFilterMatchAnySuite(t *testing.T) {
|
|||
}
|
||||
|
||||
for _, test := range funcs {
|
||||
test := test
|
||||
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
contentsCopy := make([][]byte, len(contents2))
|
||||
copy(contentsCopy, contents2)
|
||||
|
|
|
@ -28,7 +28,6 @@ func genRandFilterElements(numElements uint) ([][]byte, error) {
|
|||
|
||||
var (
|
||||
generatedFilter *gcs.Filter
|
||||
filterErr error
|
||||
)
|
||||
|
||||
// BenchmarkGCSFilterBuild benchmarks building a filter.
|
||||
|
@ -101,7 +100,7 @@ func BenchmarkGCSFilterMatch(b *testing.B) {
|
|||
|
||||
var localMatch bool
|
||||
for i := 0; i < b.N; i++ {
|
||||
localMatch, err = filter.Match(key, []byte("Nate"))
|
||||
_, err = filter.Match(key, []byte("Nate"))
|
||||
if err != nil {
|
||||
b.Fatalf("unable to match filter: %v", err)
|
||||
}
|
||||
|
@ -115,8 +114,6 @@ func BenchmarkGCSFilterMatch(b *testing.B) {
|
|||
}
|
||||
|
||||
var (
|
||||
randElems1, _ = genRandFilterElements(1)
|
||||
randElems10, _ = genRandFilterElements(10)
|
||||
randElems100, _ = genRandFilterElements(100)
|
||||
randElems1000, _ = genRandFilterElements(1000)
|
||||
randElems10000, _ = genRandFilterElements(10000)
|
||||
|
@ -164,6 +161,8 @@ var matchAnyBenchmarks = []struct {
|
|||
// BenchmarkGCSFilterMatchAny benchmarks the sort-and-zip MatchAny impl.
|
||||
func BenchmarkGCSFilterZipMatchAny(b *testing.B) {
|
||||
for _, test := range matchAnyBenchmarks {
|
||||
test := test
|
||||
|
||||
b.Run(test.name, func(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
|
||||
|
@ -188,6 +187,8 @@ func BenchmarkGCSFilterZipMatchAny(b *testing.B) {
|
|||
// BenchmarkGCSFilterMatchAny benchmarks the hash-join MatchAny impl.
|
||||
func BenchmarkGCSFilterHashMatchAny(b *testing.B) {
|
||||
for _, test := range matchAnyBenchmarks {
|
||||
test := test
|
||||
|
||||
b.Run(test.name, func(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
|
||||
|
@ -212,6 +213,8 @@ func BenchmarkGCSFilterHashMatchAny(b *testing.B) {
|
|||
// BenchmarkGCSFilterMatchAny benchmarks the hybrid MatchAny impl.
|
||||
func BenchmarkGCSFilterMatchAny(b *testing.B) {
|
||||
for _, test := range matchAnyBenchmarks {
|
||||
test := test
|
||||
|
||||
b.Run(test.name, func(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
|
||||
|
|
26
go.mod
26
go.mod
|
@ -1,11 +1,31 @@
|
|||
module github.com/lbryio/lbcutil
|
||||
|
||||
go 1.16
|
||||
go 1.17
|
||||
|
||||
require (
|
||||
github.com/aead/siphash v1.0.1
|
||||
github.com/davecgh/go-spew v1.1.1
|
||||
github.com/kkdai/bstream v1.0.0
|
||||
github.com/lbryio/lbcd v0.22.100-beta
|
||||
golang.org/x/crypto v0.0.0-20210817164053-32db794688a5
|
||||
github.com/lbryio/lbcd v0.22.101-beta
|
||||
golang.org/x/crypto v0.0.0-20211209193657-4570a0811e8b
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/DataDog/zstd v1.4.5 // indirect
|
||||
github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f // indirect
|
||||
github.com/cespare/xxhash/v2 v2.1.1 // indirect
|
||||
github.com/cockroachdb/errors v1.8.1 // indirect
|
||||
github.com/cockroachdb/logtags v0.0.0-20190617123548-eb05cc24525f // indirect
|
||||
github.com/cockroachdb/pebble v0.0.0-20210525181856-e45797baeb78 // indirect
|
||||
github.com/cockroachdb/redact v1.0.8 // indirect
|
||||
github.com/cockroachdb/sentry-go v0.6.1-cockroachdb.2 // indirect
|
||||
github.com/gogo/protobuf v1.3.1 // indirect
|
||||
github.com/golang/snappy v0.0.2-0.20190904063534-ff6b7dc882cf // indirect
|
||||
github.com/klauspost/compress v1.11.7 // indirect
|
||||
github.com/kr/pretty v0.1.0 // indirect
|
||||
github.com/kr/text v0.1.0 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
golang.org/x/exp v0.0.0-20200513190911-00229845015e // indirect
|
||||
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c // indirect
|
||||
golang.org/x/text v0.3.6 // indirect
|
||||
)
|
||||
|
|
11
go.sum
11
go.sum
|
@ -38,12 +38,10 @@ github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+Ce
|
|||
github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs=
|
||||
github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c/go.mod h1:MKsuJmJgSg28kpZDP6UIiPt0e0Oz0kqKNGyRaWEPv84=
|
||||
github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ=
|
||||
github.com/btcsuite/btcd v0.22.0-beta h1:LTDpDKUM5EeOFBPM8IXpinEcmZ6FWfNZbE3lfrfdnWo=
|
||||
github.com/btcsuite/btcd v0.22.0-beta/go.mod h1:9n5ntfhhHQBIhUvlhDvD3Qg6fRUj4jkN0VB8L8svzOA=
|
||||
github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f h1:bAs4lUbRJpnnkd9VhRV3jjAVU7DJVjMaK+IsvSeZvFo=
|
||||
github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA=
|
||||
github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg=
|
||||
github.com/btcsuite/btcutil v1.0.3-0.20201208143702-a53e38424cce h1:YtWJF7RHm2pYCvA5t0RPmAaLUhREsKuKd+SLhxFbFeQ=
|
||||
github.com/btcsuite/btcutil v1.0.3-0.20201208143702-a53e38424cce/go.mod h1:0DVlHczLPewLcPGEIeUEzfOJhqGPQ0mJJRDBtD307+o=
|
||||
github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd/go.mod h1:HHNXQzUsZCxOoE+CPiyCTO6x34Zs86zZUiwtpXoGdtg=
|
||||
github.com/btcsuite/goleveldb v0.0.0-20160330041536-7834afc9e8cd/go.mod h1:F+uVaaLLH7j4eDXPRvw78tMflu7Ie2bzYOH4Y8rRKBY=
|
||||
|
@ -241,8 +239,10 @@ github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
|
|||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/labstack/echo/v4 v4.1.11/go.mod h1:i541M3Fj6f76NZtHSj7TXnyM8n2gaodfvfxNnFqi74g=
|
||||
github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k=
|
||||
github.com/lbryio/lbcd v0.22.100-beta h1:6nv+G+MxxWqIbBLEPkSkc2Z3qhqrP8vVDHkc8+UWyv4=
|
||||
github.com/lbryio/lbcd v0.22.100-beta/go.mod h1:u8SaFX4xdGMMR5xasBGfgApC8pvD4rnK2OujZnrq5gs=
|
||||
github.com/lbryio/lbcd v0.22.101-beta h1:umLIxhyRwPdi91vtsDfgW85viK0AV8RPtIF9zQYtXw0=
|
||||
github.com/lbryio/lbcd v0.22.101-beta/go.mod h1:K8A7dGvV4n89Oahoc5IfDb6IMRmxyZYKb7ZE+50+Jwc=
|
||||
github.com/lbryio/lbcutil v1.0.201/go.mod h1:gDHc/b+Rdz3J7+VB8e5/Bl9roVf8Q5/8FQCyuK9dXD0=
|
||||
github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
|
||||
github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
|
||||
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
|
||||
|
@ -376,8 +376,9 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U
|
|||
golang.org/x/crypto v0.0.0-20200115085410-6d4e4cb37c7d/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
|
||||
golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 h1:HWj/xjIHfjYU5nVXpTM0s39J9CbLn7Cc5a7IC5rwsMQ=
|
||||
golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.0.0-20211209193657-4570a0811e8b h1:QAqMVf3pSa6eeTsuklijukjXBlj7Es2QQplab+/RbQ4=
|
||||
golang.org/x/crypto v0.0.0-20211209193657-4570a0811e8b/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
|
||||
|
@ -420,6 +421,7 @@ golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLL
|
|||
golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
|
@ -457,6 +459,7 @@ golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7w
|
|||
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c h1:F1jZWGFhYfh0Ci55sIpILtKKK8p3i2/krTr0H1rg74I=
|
||||
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
|
|
11
goclean.sh
11
goclean.sh
|
@ -32,15 +32,4 @@ for i in $(find . -name go.mod -type f -print); do
|
|||
go tool cover -func profile.cov
|
||||
)
|
||||
|
||||
# check linters
|
||||
(cd $MODNAME && \
|
||||
go mod download && \
|
||||
golangci-lint run --deadline=10m --disable-all \
|
||||
--enable=gofmt \
|
||||
--enable=goimports \
|
||||
--enable=golint \
|
||||
--enable=govet \
|
||||
--enable=gosimple \
|
||||
--enable=unconvert
|
||||
)
|
||||
done
|
||||
|
|
|
@ -13,7 +13,7 @@ import (
|
|||
|
||||
// Calculate the hash of hasher over buf.
|
||||
func calcHash(buf []byte, hasher hash.Hash) []byte {
|
||||
hasher.Write(buf)
|
||||
_, _ = hasher.Write(buf)
|
||||
return hasher.Sum(nil)
|
||||
}
|
||||
|
||||
|
|
|
@ -26,7 +26,7 @@ func BenchmarkDeriveHardened(b *testing.B) {
|
|||
b.StartTimer()
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
masterKey.Derive(hdkeychain.HardenedKeyStart)
|
||||
_, _ = masterKey.Derive(hdkeychain.HardenedKeyStart)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -41,7 +41,7 @@ func BenchmarkDeriveNormal(b *testing.B) {
|
|||
b.StartTimer()
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
masterKey.Derive(0)
|
||||
_, _ = masterKey.Derive(0)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -56,7 +56,7 @@ func BenchmarkPrivToPub(b *testing.B) {
|
|||
b.StartTimer()
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
masterKey.Neuter()
|
||||
_, _ = masterKey.Neuter()
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -64,7 +64,7 @@ func BenchmarkPrivToPub(b *testing.B) {
|
|||
// extended key.
|
||||
func BenchmarkDeserialize(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
hdkeychain.NewKeyFromString(bip0032MasterPriv1)
|
||||
_, _ = hdkeychain.NewKeyFromString(bip0032MasterPriv1)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -132,8 +132,8 @@ func Example_defaultWalletLayout() {
|
|||
fmt.Println("Account 0 Internal Address 0:", acct0IntAddr)
|
||||
|
||||
// Output:
|
||||
// Account 0 External Address 10: 1HVccubUT8iKTapMJ5AnNA4sLRN27xzQ4F
|
||||
// Account 0 Internal Address 0: 1J5rebbkQaunJTUoNVREDbeB49DqMNFFXk
|
||||
// Account 0 External Address 10: bVDtK8vxoU6nyRfiNjUsapCjqJGCY2wwRq
|
||||
// Account 0 Internal Address 0: bVp8LpwEkvJFpJLAT9jKSFn3Z281nH4wcm
|
||||
}
|
||||
|
||||
// This example demonstrates the audits use case in BIP0032.
|
||||
|
|
|
@ -277,7 +277,7 @@ func (k *ExtendedKey) Derive(i uint32) (*ExtendedKey, error) {
|
|||
// data:
|
||||
// I = HMAC-SHA512(Key = chainCode, Data = data)
|
||||
hmac512 := hmac.New(sha512.New, k.chainCode)
|
||||
hmac512.Write(data)
|
||||
_, _ = hmac512.Write(data)
|
||||
ilr := hmac512.Sum(nil)
|
||||
|
||||
// Split "I" into two 32-byte sequences Il and Ir where:
|
||||
|
@ -380,7 +380,7 @@ func (k *ExtendedKey) DeriveNonStandard(i uint32) (*ExtendedKey, error) {
|
|||
binary.BigEndian.PutUint32(data[keyLen:], i)
|
||||
|
||||
hmac512 := hmac.New(sha512.New, k.chainCode)
|
||||
hmac512.Write(data)
|
||||
_, _ = hmac512.Write(data)
|
||||
ilr := hmac512.Sum(nil)
|
||||
|
||||
il := ilr[:len(ilr)/2]
|
||||
|
@ -610,7 +610,7 @@ func NewMaster(seed []byte, net *chaincfg.Params) (*ExtendedKey, error) {
|
|||
// First take the HMAC-SHA512 of the master key and the seed data:
|
||||
// I = HMAC-SHA512(Key = "Bitcoin seed", Data = S)
|
||||
hmac512 := hmac.New(sha512.New, masterKey)
|
||||
hmac512.Write(seed)
|
||||
_, _ = hmac512.Write(seed)
|
||||
lr := hmac512.Sum(nil)
|
||||
|
||||
// Split "I" into two 32-byte sequences Il and Ir where:
|
||||
|
|
|
@ -579,7 +579,7 @@ func TestExtendedKeyAPI(t *testing.T) {
|
|||
childNum: 0,
|
||||
privKey: "e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35",
|
||||
pubKey: "0339a36013301597daef41fbe593a02cc513d0b55527ec2df1050e2e8ff49c85c2",
|
||||
address: "15mKKb2eos1hWa6tisdPwwDC1a5J1y9nma",
|
||||
address: "bHVb1pN9ACQB2QxFoXwVAbM4WSyUVVDfbW",
|
||||
},
|
||||
{
|
||||
name: "test vector 1 chain m/0H/1/2H public",
|
||||
|
@ -590,7 +590,7 @@ func TestExtendedKeyAPI(t *testing.T) {
|
|||
childNum: 2147483650,
|
||||
privKeyErr: ErrNotPrivExtKey,
|
||||
pubKey: "0357bfe1e341d01c69fe5654309956cbea516822fba8a601743a012a7896ee8dc2",
|
||||
address: "1NjxqbA9aZWnh17q1UW3rB4EPu79wDXj7x",
|
||||
address: "baUEXpVdvtuGCqyC68p94qC6tn1LSJq1LA",
|
||||
},
|
||||
}
|
||||
|
||||
|
@ -980,10 +980,10 @@ func TestZero(t *testing.T) {
|
|||
return false
|
||||
}
|
||||
|
||||
wantAddr := "1HT7xU2Ngenf7D4yocz2SAcnNLW7rK8d4E"
|
||||
wantAddr := "bVBPehMs2zB8d3vLtHJ7epkesDQJJ9D7Ek"
|
||||
addr, err := key.Address(&chaincfg.MainNetParams)
|
||||
if err != nil {
|
||||
t.Errorf("Addres s #%d (%s): unexpected error: %v", i,
|
||||
t.Errorf("Address #%d (%s): unexpected error: %v", i,
|
||||
testName, err)
|
||||
return false
|
||||
}
|
||||
|
|
|
@ -59,9 +59,11 @@ func TstAddressWitnessPubKeyHash(version byte, program [20]byte,
|
|||
hrp string) *AddressWitnessPubKeyHash {
|
||||
|
||||
return &AddressWitnessPubKeyHash{
|
||||
hrp: hrp,
|
||||
witnessVersion: version,
|
||||
witnessProgram: program,
|
||||
AddressSegWit{
|
||||
hrp: hrp,
|
||||
witnessVersion: version,
|
||||
witnessProgram: program[:],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -71,9 +73,24 @@ func TstAddressWitnessScriptHash(version byte, program [32]byte,
|
|||
hrp string) *AddressWitnessScriptHash {
|
||||
|
||||
return &AddressWitnessScriptHash{
|
||||
hrp: hrp,
|
||||
witnessVersion: version,
|
||||
witnessProgram: program,
|
||||
AddressSegWit{
|
||||
hrp: hrp,
|
||||
witnessVersion: version,
|
||||
witnessProgram: program[:],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// TstAddressTaproot creates an AddressTaproot, initiating the fields as given.
|
||||
func TstAddressTaproot(version byte, program [32]byte,
|
||||
hrp string) *AddressTaproot {
|
||||
|
||||
return &AddressTaproot{
|
||||
AddressSegWit{
|
||||
hrp: hrp,
|
||||
witnessVersion: version,
|
||||
witnessProgram: program[:],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -112,3 +129,19 @@ func TstAddressSegwitSAddr(addr string) []byte {
|
|||
}
|
||||
return data
|
||||
}
|
||||
|
||||
// TstAddressTaprootSAddr returns the expected witness program bytes for a
|
||||
// bech32m encoded P2TR bitcoin address.
|
||||
func TstAddressTaprootSAddr(addr string) []byte {
|
||||
_, data, err := bech32.Decode(addr)
|
||||
if err != nil {
|
||||
return []byte{}
|
||||
}
|
||||
|
||||
// First byte is version, rest is base 32 encoded data.
|
||||
data, err = bech32.ConvertBits(data[1:], 5, 8, false)
|
||||
if err != nil {
|
||||
return []byte{}
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
|
1
net.go
1
net.go
|
@ -2,6 +2,7 @@
|
|||
// Use of this source code is governed by an ISC
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
//go:build !appengine
|
||||
// +build !appengine
|
||||
|
||||
package lbcutil
|
||||
|
|
|
@ -11,11 +11,11 @@ import (
|
|||
"encoding/hex"
|
||||
"testing"
|
||||
|
||||
"github.com/davecgh/go-spew/spew"
|
||||
"github.com/lbryio/lbcd/chaincfg/chainhash"
|
||||
"github.com/lbryio/lbcd/txscript"
|
||||
"github.com/lbryio/lbcd/wire"
|
||||
"github.com/lbryio/lbcutil"
|
||||
"github.com/davecgh/go-spew/spew"
|
||||
)
|
||||
|
||||
// Test vectors from:
|
||||
|
|
|
@ -10,9 +10,9 @@ import (
|
|||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/davecgh/go-spew/spew"
|
||||
"github.com/lbryio/lbcd/chaincfg/chainhash"
|
||||
"github.com/lbryio/lbcutil"
|
||||
"github.com/davecgh/go-spew/spew"
|
||||
)
|
||||
|
||||
// TestTx tests the API for Tx.
|
||||
|
|
|
@ -64,6 +64,8 @@ func TestEncodeDecodeWIF(t *testing.T) {
|
|||
}
|
||||
|
||||
for _, validCase := range validEncodeCases {
|
||||
validCase := validCase
|
||||
|
||||
t.Run(validCase.name, func(t *testing.T) {
|
||||
priv, _ := btcec.PrivKeyFromBytes(btcec.S256(), validCase.privateKey)
|
||||
wif, err := NewWIF(priv, validCase.net, validCase.compress)
|
||||
|
@ -122,6 +124,8 @@ func TestEncodeDecodeWIF(t *testing.T) {
|
|||
}
|
||||
|
||||
for _, invalidCase := range invalidDecodeCases {
|
||||
invalidCase := invalidCase
|
||||
|
||||
t.Run(invalidCase.name, func(t *testing.T) {
|
||||
decodedWif, err := DecodeWIF(invalidCase.wif)
|
||||
if decodedWif != nil {
|
||||
|
|
Loading…
Reference in a new issue