Update btcwire path import paths to new location.

This commit is contained in:
Dave Collins 2015-02-05 15:16:39 -06:00
parent 979d67627f
commit 03433dad6a
55 changed files with 1005 additions and 1005 deletions

View file

@ -23,7 +23,7 @@ import (
"sync/atomic" "sync/atomic"
"time" "time"
"github.com/btcsuite/btcwire" "github.com/btcsuite/btcd/wire"
) )
// AddrManager provides a concurrency safe address manager for caching potential // AddrManager provides a concurrency safe address manager for caching potential
@ -66,7 +66,7 @@ type serializedAddrManager struct {
} }
type localAddress struct { type localAddress struct {
na *btcwire.NetAddress na *wire.NetAddress
score AddressPriority score AddressPriority
} }
@ -161,7 +161,7 @@ const (
// updateAddress is a helper function to either update an address already known // updateAddress is a helper function to either update an address already known
// to the address manager, or to add the address if not already known. // to the address manager, or to add the address if not already known.
func (a *AddrManager) updateAddress(netAddr, srcAddr *btcwire.NetAddress) { func (a *AddrManager) updateAddress(netAddr, srcAddr *wire.NetAddress) {
// Filter out non-routable addresses. Note that non-routable // Filter out non-routable addresses. Note that non-routable
// also includes invalid and local addresses. // also includes invalid and local addresses.
if !IsRoutable(netAddr) { if !IsRoutable(netAddr) {
@ -292,7 +292,7 @@ func (a *AddrManager) pickTried(bucket int) *list.Element {
return oldestElem return oldestElem
} }
func (a *AddrManager) getNewBucket(netAddr, srcAddr *btcwire.NetAddress) int { func (a *AddrManager) getNewBucket(netAddr, srcAddr *wire.NetAddress) int {
// bitcoind: // bitcoind:
// doublesha256(key + sourcegroup + int64(doublesha256(key + group + sourcegroup))%bucket_per_source_group) % num_new_buckets // doublesha256(key + sourcegroup + int64(doublesha256(key + group + sourcegroup))%bucket_per_source_group) % num_new_buckets
@ -300,7 +300,7 @@ func (a *AddrManager) getNewBucket(netAddr, srcAddr *btcwire.NetAddress) int {
data1 = append(data1, a.key[:]...) data1 = append(data1, a.key[:]...)
data1 = append(data1, []byte(GroupKey(netAddr))...) data1 = append(data1, []byte(GroupKey(netAddr))...)
data1 = append(data1, []byte(GroupKey(srcAddr))...) data1 = append(data1, []byte(GroupKey(srcAddr))...)
hash1 := btcwire.DoubleSha256(data1) hash1 := wire.DoubleSha256(data1)
hash64 := binary.LittleEndian.Uint64(hash1) hash64 := binary.LittleEndian.Uint64(hash1)
hash64 %= newBucketsPerGroup hash64 %= newBucketsPerGroup
var hashbuf [8]byte var hashbuf [8]byte
@ -310,17 +310,17 @@ func (a *AddrManager) getNewBucket(netAddr, srcAddr *btcwire.NetAddress) int {
data2 = append(data2, GroupKey(srcAddr)...) data2 = append(data2, GroupKey(srcAddr)...)
data2 = append(data2, hashbuf[:]...) data2 = append(data2, hashbuf[:]...)
hash2 := btcwire.DoubleSha256(data2) hash2 := wire.DoubleSha256(data2)
return int(binary.LittleEndian.Uint64(hash2) % newBucketCount) return int(binary.LittleEndian.Uint64(hash2) % newBucketCount)
} }
func (a *AddrManager) getTriedBucket(netAddr *btcwire.NetAddress) int { func (a *AddrManager) getTriedBucket(netAddr *wire.NetAddress) int {
// bitcoind hashes this as: // bitcoind hashes this as:
// doublesha256(key + group + truncate_to_64bits(doublesha256(key)) % buckets_per_group) % num_buckets // doublesha256(key + group + truncate_to_64bits(doublesha256(key)) % buckets_per_group) % num_buckets
data1 := []byte{} data1 := []byte{}
data1 = append(data1, a.key[:]...) data1 = append(data1, a.key[:]...)
data1 = append(data1, []byte(NetAddressKey(netAddr))...) data1 = append(data1, []byte(NetAddressKey(netAddr))...)
hash1 := btcwire.DoubleSha256(data1) hash1 := wire.DoubleSha256(data1)
hash64 := binary.LittleEndian.Uint64(hash1) hash64 := binary.LittleEndian.Uint64(hash1)
hash64 %= triedBucketsPerGroup hash64 %= triedBucketsPerGroup
var hashbuf [8]byte var hashbuf [8]byte
@ -330,7 +330,7 @@ func (a *AddrManager) getTriedBucket(netAddr *btcwire.NetAddress) int {
data2 = append(data2, GroupKey(netAddr)...) data2 = append(data2, GroupKey(netAddr)...)
data2 = append(data2, hashbuf[:]...) data2 = append(data2, hashbuf[:]...)
hash2 := btcwire.DoubleSha256(data2) hash2 := wire.DoubleSha256(data2)
return int(binary.LittleEndian.Uint64(hash2) % triedBucketCount) return int(binary.LittleEndian.Uint64(hash2) % triedBucketCount)
} }
@ -521,8 +521,8 @@ func (a *AddrManager) deserializePeers(filePath string) error {
return nil return nil
} }
// DeserializeNetAddress converts a given address string to a *btcwire.NetAddress // DeserializeNetAddress converts a given address string to a *wire.NetAddress
func (a *AddrManager) DeserializeNetAddress(addr string) (*btcwire.NetAddress, error) { func (a *AddrManager) DeserializeNetAddress(addr string) (*wire.NetAddress, error) {
host, portStr, err := net.SplitHostPort(addr) host, portStr, err := net.SplitHostPort(addr)
if err != nil { if err != nil {
return nil, err return nil, err
@ -532,7 +532,7 @@ func (a *AddrManager) DeserializeNetAddress(addr string) (*btcwire.NetAddress, e
return nil, err return nil, err
} }
return a.HostToNetAddress(host, uint16(port), btcwire.SFNodeNetwork) return a.HostToNetAddress(host, uint16(port), wire.SFNodeNetwork)
} }
// Start begins the core address handler which manages a pool of known // Start begins the core address handler which manages a pool of known
@ -570,7 +570,7 @@ func (a *AddrManager) Stop() error {
// AddAddresses adds new addresses to the address manager. It enforces a max // AddAddresses adds new addresses to the address manager. It enforces a max
// number of addresses and silently ignores duplicate addresses. It is // number of addresses and silently ignores duplicate addresses. It is
// safe for concurrent access. // safe for concurrent access.
func (a *AddrManager) AddAddresses(addrs []*btcwire.NetAddress, srcAddr *btcwire.NetAddress) { func (a *AddrManager) AddAddresses(addrs []*wire.NetAddress, srcAddr *wire.NetAddress) {
a.mtx.Lock() a.mtx.Lock()
defer a.mtx.Unlock() defer a.mtx.Unlock()
@ -582,7 +582,7 @@ func (a *AddrManager) AddAddresses(addrs []*btcwire.NetAddress, srcAddr *btcwire
// AddAddress adds a new address to the address manager. It enforces a max // AddAddress adds a new address to the address manager. It enforces a max
// number of addresses and silently ignores duplicate addresses. It is // number of addresses and silently ignores duplicate addresses. It is
// safe for concurrent access. // safe for concurrent access.
func (a *AddrManager) AddAddress(addr, srcAddr *btcwire.NetAddress) { func (a *AddrManager) AddAddress(addr, srcAddr *wire.NetAddress) {
a.mtx.Lock() a.mtx.Lock()
defer a.mtx.Unlock() defer a.mtx.Unlock()
@ -590,15 +590,15 @@ func (a *AddrManager) AddAddress(addr, srcAddr *btcwire.NetAddress) {
} }
// AddAddressByIP adds an address where we are given an ip:port and not a // AddAddressByIP adds an address where we are given an ip:port and not a
// btcwire.NetAddress. // wire.NetAddress.
func (a *AddrManager) AddAddressByIP(addrIP string) error { func (a *AddrManager) AddAddressByIP(addrIP string) error {
// Split IP and port // Split IP and port
addr, portStr, err := net.SplitHostPort(addrIP) addr, portStr, err := net.SplitHostPort(addrIP)
if err != nil { if err != nil {
return err return err
} }
// Put it in btcwire.Netaddress // Put it in wire.Netaddress
var na btcwire.NetAddress var na wire.NetAddress
na.Timestamp = time.Now() na.Timestamp = time.Now()
na.IP = net.ParseIP(addr) na.IP = net.ParseIP(addr)
if na.IP == nil { if na.IP == nil {
@ -637,14 +637,14 @@ func (a *AddrManager) NeedMoreAddresses() bool {
// AddressCache returns the current address cache. It must be treated as // AddressCache returns the current address cache. It must be treated as
// read-only (but since it is a copy now, this is not as dangerous). // read-only (but since it is a copy now, this is not as dangerous).
func (a *AddrManager) AddressCache() []*btcwire.NetAddress { func (a *AddrManager) AddressCache() []*wire.NetAddress {
a.mtx.Lock() a.mtx.Lock()
defer a.mtx.Unlock() defer a.mtx.Unlock()
if a.nNew+a.nTried == 0 { if a.nNew+a.nTried == 0 {
return nil return nil
} }
allAddr := make([]*btcwire.NetAddress, a.nNew+a.nTried) allAddr := make([]*wire.NetAddress, a.nNew+a.nTried)
i := 0 i := 0
// Iteration order is undefined here, but we randomise it anyway. // Iteration order is undefined here, but we randomise it anyway.
for _, v := range a.addrIndex { for _, v := range a.addrIndex {
@ -688,7 +688,7 @@ func (a *AddrManager) reset() {
// HostToNetAddress returns a netaddress given a host address. If the address is // HostToNetAddress returns a netaddress given a host address. If the address is
// a tor .onion address this will be taken care of. else if the host is not an // a tor .onion address this will be taken care of. else if the host is not an
// IP address it will be resolved (via tor if required). // IP address it will be resolved (via tor if required).
func (a *AddrManager) HostToNetAddress(host string, port uint16, services btcwire.ServiceFlag) (*btcwire.NetAddress, error) { func (a *AddrManager) HostToNetAddress(host string, port uint16, services wire.ServiceFlag) (*wire.NetAddress, error) {
// tor address is 16 char base32 + ".onion" // tor address is 16 char base32 + ".onion"
var ip net.IP var ip net.IP
if len(host) == 22 && host[16:] == ".onion" { if len(host) == 22 && host[16:] == ".onion" {
@ -713,13 +713,13 @@ func (a *AddrManager) HostToNetAddress(host string, port uint16, services btcwir
ip = ips[0] ip = ips[0]
} }
return btcwire.NewNetAddressIPPort(ip, port, services), nil return wire.NewNetAddressIPPort(ip, port, services), nil
} }
// ipString returns a string for the ip from the provided NetAddress. If the // ipString returns a string for the ip from the provided NetAddress. If the
// ip is in the range used for tor addresses then it will be transformed into // ip is in the range used for tor addresses then it will be transformed into
// the relevant .onion address. // the relevant .onion address.
func ipString(na *btcwire.NetAddress) string { func ipString(na *wire.NetAddress) string {
if IsOnionCatTor(na) { if IsOnionCatTor(na) {
// We know now that na.IP is long enogh. // We know now that na.IP is long enogh.
base32 := base32.StdEncoding.EncodeToString(na.IP[6:]) base32 := base32.StdEncoding.EncodeToString(na.IP[6:])
@ -731,7 +731,7 @@ func ipString(na *btcwire.NetAddress) string {
// NetAddressKey returns a string key in the form of ip:port for IPv4 addresses // NetAddressKey returns a string key in the form of ip:port for IPv4 addresses
// or [ip]:port for IPv6 addresses. // or [ip]:port for IPv6 addresses.
func NetAddressKey(na *btcwire.NetAddress) string { func NetAddressKey(na *wire.NetAddress) string {
port := strconv.FormatUint(uint64(na.Port), 10) port := strconv.FormatUint(uint64(na.Port), 10)
return net.JoinHostPort(ipString(na), port) return net.JoinHostPort(ipString(na), port)
@ -820,13 +820,13 @@ func (a *AddrManager) GetAddress(class string, newBias int) *KnownAddress {
} }
} }
func (a *AddrManager) find(addr *btcwire.NetAddress) *KnownAddress { func (a *AddrManager) find(addr *wire.NetAddress) *KnownAddress {
return a.addrIndex[NetAddressKey(addr)] return a.addrIndex[NetAddressKey(addr)]
} }
// Attempt increases the given address' attempt counter and updates // Attempt increases the given address' attempt counter and updates
// the last attempt time. // the last attempt time.
func (a *AddrManager) Attempt(addr *btcwire.NetAddress) { func (a *AddrManager) Attempt(addr *wire.NetAddress) {
a.mtx.Lock() a.mtx.Lock()
defer a.mtx.Unlock() defer a.mtx.Unlock()
@ -844,7 +844,7 @@ func (a *AddrManager) Attempt(addr *btcwire.NetAddress) {
// Connected Marks the given address as currently connected and working at the // Connected Marks the given address as currently connected and working at the
// current time. The address must already be known to AddrManager else it will // current time. The address must already be known to AddrManager else it will
// be ignored. // be ignored.
func (a *AddrManager) Connected(addr *btcwire.NetAddress) { func (a *AddrManager) Connected(addr *wire.NetAddress) {
a.mtx.Lock() a.mtx.Lock()
defer a.mtx.Unlock() defer a.mtx.Unlock()
@ -867,7 +867,7 @@ func (a *AddrManager) Connected(addr *btcwire.NetAddress) {
// Good marks the given address as good. To be called after a successful // Good marks the given address as good. To be called after a successful
// connection and version exchange. If the address is unknown to the address // connection and version exchange. If the address is unknown to the address
// manager it will be ignored. // manager it will be ignored.
func (a *AddrManager) Good(addr *btcwire.NetAddress) { func (a *AddrManager) Good(addr *wire.NetAddress) {
a.mtx.Lock() a.mtx.Lock()
defer a.mtx.Unlock() defer a.mtx.Unlock()
@ -955,7 +955,7 @@ func (a *AddrManager) Good(addr *btcwire.NetAddress) {
// AddLocalAddress adds na to the list of known local addresses to advertise // AddLocalAddress adds na to the list of known local addresses to advertise
// with the given priority. // with the given priority.
func (a *AddrManager) AddLocalAddress(na *btcwire.NetAddress, priority AddressPriority) error { func (a *AddrManager) AddLocalAddress(na *wire.NetAddress, priority AddressPriority) error {
if !IsRoutable(na) { if !IsRoutable(na) {
return fmt.Errorf("address %s is not routable", na.IP) return fmt.Errorf("address %s is not routable", na.IP)
} }
@ -980,7 +980,7 @@ func (a *AddrManager) AddLocalAddress(na *btcwire.NetAddress, priority AddressPr
// getReachabilityFrom returns the relative reachability of the provided local // getReachabilityFrom returns the relative reachability of the provided local
// address to the provided remote address. // address to the provided remote address.
func getReachabilityFrom(localAddr, remoteAddr *btcwire.NetAddress) int { func getReachabilityFrom(localAddr, remoteAddr *wire.NetAddress) int {
const ( const (
Unreachable = 0 Unreachable = 0
Default = iota Default = iota
@ -1059,13 +1059,13 @@ func getReachabilityFrom(localAddr, remoteAddr *btcwire.NetAddress) int {
// GetBestLocalAddress returns the most appropriate local address to use // GetBestLocalAddress returns the most appropriate local address to use
// for the given remote address. // for the given remote address.
func (a *AddrManager) GetBestLocalAddress(remoteAddr *btcwire.NetAddress) *btcwire.NetAddress { func (a *AddrManager) GetBestLocalAddress(remoteAddr *wire.NetAddress) *wire.NetAddress {
a.lamtx.Lock() a.lamtx.Lock()
defer a.lamtx.Unlock() defer a.lamtx.Unlock()
bestreach := 0 bestreach := 0
var bestscore AddressPriority var bestscore AddressPriority
var bestAddress *btcwire.NetAddress var bestAddress *wire.NetAddress
for _, la := range a.localAddresses { for _, la := range a.localAddresses {
reach := getReachabilityFrom(la.na, remoteAddr) reach := getReachabilityFrom(la.na, remoteAddr)
if reach > bestreach || if reach > bestreach ||
@ -1083,9 +1083,9 @@ func (a *AddrManager) GetBestLocalAddress(remoteAddr *btcwire.NetAddress) *btcwi
remoteAddr.Port) remoteAddr.Port)
// Send something unroutable if nothing suitable. // Send something unroutable if nothing suitable.
bestAddress = &btcwire.NetAddress{ bestAddress = &wire.NetAddress{
Timestamp: time.Now(), Timestamp: time.Now(),
Services: btcwire.SFNodeNetwork, Services: wire.SFNodeNetwork,
Port: 0, Port: 0,
} }
if !IsIPv4(remoteAddr) && !IsOnionCatTor(remoteAddr) { if !IsIPv4(remoteAddr) && !IsOnionCatTor(remoteAddr) {

View file

@ -11,13 +11,13 @@ import (
"time" "time"
"github.com/btcsuite/btcd/addrmgr" "github.com/btcsuite/btcd/addrmgr"
"github.com/btcsuite/btcwire" "github.com/btcsuite/btcd/wire"
) )
// naTest is used to describe a test to be perfomed against the NetAddressKey // naTest is used to describe a test to be perfomed against the NetAddressKey
// method. // method.
type naTest struct { type naTest struct {
in btcwire.NetAddress in wire.NetAddress
want string want string
} }
@ -88,9 +88,9 @@ func addNaTests() {
func addNaTest(ip string, port uint16, want string) { func addNaTest(ip string, port uint16, want string) {
nip := net.ParseIP(ip) nip := net.ParseIP(ip)
na := btcwire.NetAddress{ na := wire.NetAddress{
Timestamp: time.Now(), Timestamp: time.Now(),
Services: btcwire.SFNodeNetwork, Services: wire.SFNodeNetwork,
IP: nip, IP: nip,
Port: port, Port: port,
} }
@ -104,27 +104,27 @@ func lookupFunc(host string) ([]net.IP, error) {
func TestAddLocalAddress(t *testing.T) { func TestAddLocalAddress(t *testing.T) {
var tests = []struct { var tests = []struct {
address btcwire.NetAddress address wire.NetAddress
valid bool valid bool
}{ }{
{ {
btcwire.NetAddress{IP: net.ParseIP("192.168.0.100")}, wire.NetAddress{IP: net.ParseIP("192.168.0.100")},
false, false,
}, },
{ {
btcwire.NetAddress{IP: net.ParseIP("204.124.1.1")}, wire.NetAddress{IP: net.ParseIP("204.124.1.1")},
true, true,
}, },
{ {
btcwire.NetAddress{IP: net.ParseIP("::1")}, wire.NetAddress{IP: net.ParseIP("::1")},
false, false,
}, },
{ {
btcwire.NetAddress{IP: net.ParseIP("fe80::1")}, wire.NetAddress{IP: net.ParseIP("fe80::1")},
false, false,
}, },
{ {
btcwire.NetAddress{IP: net.ParseIP("2620:100::1")}, wire.NetAddress{IP: net.ParseIP("2620:100::1")},
true, true,
}, },
} }
@ -152,7 +152,7 @@ func TestGetAddress(t *testing.T) {
} }
func TestGetBestLocalAddress(t *testing.T) { func TestGetBestLocalAddress(t *testing.T) {
localAddrs := []btcwire.NetAddress{ localAddrs := []wire.NetAddress{
{IP: net.ParseIP("192.168.0.100")}, {IP: net.ParseIP("192.168.0.100")},
{IP: net.ParseIP("::1")}, {IP: net.ParseIP("::1")},
{IP: net.ParseIP("fe80::1")}, {IP: net.ParseIP("fe80::1")},
@ -160,39 +160,39 @@ func TestGetBestLocalAddress(t *testing.T) {
} }
var tests = []struct { var tests = []struct {
remoteAddr btcwire.NetAddress remoteAddr wire.NetAddress
want1 btcwire.NetAddress want1 wire.NetAddress
want2 btcwire.NetAddress want2 wire.NetAddress
want3 btcwire.NetAddress want3 wire.NetAddress
}{ }{
{ {
// Remote connection from public IPv4 // Remote connection from public IPv4
btcwire.NetAddress{IP: net.ParseIP("204.124.8.1")}, wire.NetAddress{IP: net.ParseIP("204.124.8.1")},
btcwire.NetAddress{IP: net.IPv4zero}, wire.NetAddress{IP: net.IPv4zero},
btcwire.NetAddress{IP: net.ParseIP("204.124.8.100")}, wire.NetAddress{IP: net.ParseIP("204.124.8.100")},
btcwire.NetAddress{IP: net.ParseIP("fd87:d87e:eb43:25::1")}, wire.NetAddress{IP: net.ParseIP("fd87:d87e:eb43:25::1")},
}, },
{ {
// Remote connection from private IPv4 // Remote connection from private IPv4
btcwire.NetAddress{IP: net.ParseIP("172.16.0.254")}, wire.NetAddress{IP: net.ParseIP("172.16.0.254")},
btcwire.NetAddress{IP: net.IPv4zero}, wire.NetAddress{IP: net.IPv4zero},
btcwire.NetAddress{IP: net.IPv4zero}, wire.NetAddress{IP: net.IPv4zero},
btcwire.NetAddress{IP: net.IPv4zero}, wire.NetAddress{IP: net.IPv4zero},
}, },
{ {
// Remote connection from public IPv6 // Remote connection from public IPv6
btcwire.NetAddress{IP: net.ParseIP("2602:100:abcd::102")}, wire.NetAddress{IP: net.ParseIP("2602:100:abcd::102")},
btcwire.NetAddress{IP: net.ParseIP("2001:470::1")}, wire.NetAddress{IP: net.ParseIP("2001:470::1")},
btcwire.NetAddress{IP: net.ParseIP("2001:470::1")}, wire.NetAddress{IP: net.ParseIP("2001:470::1")},
btcwire.NetAddress{IP: net.ParseIP("2001:470::1")}, wire.NetAddress{IP: net.ParseIP("2001:470::1")},
}, },
/* XXX /* XXX
{ {
// Remote connection from Tor // Remote connection from Tor
btcwire.NetAddress{IP: net.ParseIP("fd87:d87e:eb43::100")}, wire.NetAddress{IP: net.ParseIP("fd87:d87e:eb43::100")},
btcwire.NetAddress{IP: net.IPv4zero}, wire.NetAddress{IP: net.IPv4zero},
btcwire.NetAddress{IP: net.ParseIP("204.124.8.100")}, wire.NetAddress{IP: net.ParseIP("204.124.8.100")},
btcwire.NetAddress{IP: net.ParseIP("fd87:d87e:eb43:25::1")}, wire.NetAddress{IP: net.ParseIP("fd87:d87e:eb43:25::1")},
}, },
*/ */
} }
@ -213,7 +213,7 @@ func TestGetBestLocalAddress(t *testing.T) {
} }
// Add a public IP to the list of local addresses. // Add a public IP to the list of local addresses.
localAddr := btcwire.NetAddress{IP: net.ParseIP("204.124.8.100")} localAddr := wire.NetAddress{IP: net.ParseIP("204.124.8.100")}
amgr.AddLocalAddress(&localAddr, addrmgr.InterfacePrio) amgr.AddLocalAddress(&localAddr, addrmgr.InterfacePrio)
// Test against want2 // Test against want2
@ -227,7 +227,7 @@ func TestGetBestLocalAddress(t *testing.T) {
} }
/* /*
// Add a tor generated IP address // Add a tor generated IP address
localAddr = btcwire.NetAddress{IP: net.ParseIP("fd87:d87e:eb43:25::1")} localAddr = wire.NetAddress{IP: net.ParseIP("fd87:d87e:eb43:25::1")}
amgr.AddLocalAddress(&localAddr, addrmgr.ManualPrio) amgr.AddLocalAddress(&localAddr, addrmgr.ManualPrio)
// Test against want3 // Test against want3

View file

@ -7,14 +7,14 @@ package addrmgr
import ( import (
"time" "time"
"github.com/btcsuite/btcwire" "github.com/btcsuite/btcd/wire"
) )
// KnownAddress tracks information about a known network address that is used // KnownAddress tracks information about a known network address that is used
// to determine how viable an address is. // to determine how viable an address is.
type KnownAddress struct { type KnownAddress struct {
na *btcwire.NetAddress na *wire.NetAddress
srcAddr *btcwire.NetAddress srcAddr *wire.NetAddress
attempts int attempts int
lastattempt time.Time lastattempt time.Time
lastsuccess time.Time lastsuccess time.Time
@ -22,9 +22,9 @@ type KnownAddress struct {
refs int // reference count of new buckets refs int // reference count of new buckets
} }
// NetAddress returns the underlying btcwire.NetAddress associated with the // NetAddress returns the underlying wire.NetAddress associated with the
// known address. // known address.
func (ka *KnownAddress) NetAddress() *btcwire.NetAddress { func (ka *KnownAddress) NetAddress() *wire.NetAddress {
return ka.na return ka.na
} }

View file

@ -8,7 +8,7 @@ import (
"fmt" "fmt"
"net" "net"
"github.com/btcsuite/btcwire" "github.com/btcsuite/btcd/wire"
) )
var ( var (
@ -100,12 +100,12 @@ func ipNet(ip string, ones, bits int) net.IPNet {
} }
// IsIPv4 returns whether or not the given address is an IPv4 address. // IsIPv4 returns whether or not the given address is an IPv4 address.
func IsIPv4(na *btcwire.NetAddress) bool { func IsIPv4(na *wire.NetAddress) bool {
return na.IP.To4() != nil return na.IP.To4() != nil
} }
// IsLocal returns whether or not the given address is a local address. // IsLocal returns whether or not the given address is a local address.
func IsLocal(na *btcwire.NetAddress) bool { func IsLocal(na *wire.NetAddress) bool {
return na.IP.IsLoopback() || zero4Net.Contains(na.IP) return na.IP.IsLoopback() || zero4Net.Contains(na.IP)
} }
@ -113,14 +113,14 @@ func IsLocal(na *btcwire.NetAddress) bool {
// used by bitcoin to support Tor (fd87:d87e:eb43::/48). Note that this range // used by bitcoin to support Tor (fd87:d87e:eb43::/48). Note that this range
// is the same range used by OnionCat, which is part of the RFC4193 unique local // is the same range used by OnionCat, which is part of the RFC4193 unique local
// IPv6 range. // IPv6 range.
func IsOnionCatTor(na *btcwire.NetAddress) bool { func IsOnionCatTor(na *wire.NetAddress) bool {
return onionCatNet.Contains(na.IP) return onionCatNet.Contains(na.IP)
} }
// IsRFC1918 returns whether or not the passed address is part of the IPv4 // IsRFC1918 returns whether or not the passed address is part of the IPv4
// private network address space as defined by RFC1918 (10.0.0.0/8, // private network address space as defined by RFC1918 (10.0.0.0/8,
// 172.16.0.0/12, or 192.168.0.0/16). // 172.16.0.0/12, or 192.168.0.0/16).
func IsRFC1918(na *btcwire.NetAddress) bool { func IsRFC1918(na *wire.NetAddress) bool {
for _, rfc := range rfc1918Nets { for _, rfc := range rfc1918Nets {
if rfc.Contains(na.IP) { if rfc.Contains(na.IP) {
return true return true
@ -131,56 +131,56 @@ func IsRFC1918(na *btcwire.NetAddress) bool {
// IsRFC2544 returns whether or not the passed address is part of the IPv4 // IsRFC2544 returns whether or not the passed address is part of the IPv4
// address space as defined by RFC2544 (198.18.0.0/15) // address space as defined by RFC2544 (198.18.0.0/15)
func IsRFC2544(na *btcwire.NetAddress) bool { func IsRFC2544(na *wire.NetAddress) bool {
return rfc2544Net.Contains(na.IP) return rfc2544Net.Contains(na.IP)
} }
// IsRFC3849 returns whether or not the passed address is part of the IPv6 // IsRFC3849 returns whether or not the passed address is part of the IPv6
// documentation range as defined by RFC3849 (2001:DB8::/32). // documentation range as defined by RFC3849 (2001:DB8::/32).
func IsRFC3849(na *btcwire.NetAddress) bool { func IsRFC3849(na *wire.NetAddress) bool {
return rfc3849Net.Contains(na.IP) return rfc3849Net.Contains(na.IP)
} }
// IsRFC3927 returns whether or not the passed address is part of the IPv4 // IsRFC3927 returns whether or not the passed address is part of the IPv4
// autoconfiguration range as defined by RFC3927 (169.254.0.0/16). // autoconfiguration range as defined by RFC3927 (169.254.0.0/16).
func IsRFC3927(na *btcwire.NetAddress) bool { func IsRFC3927(na *wire.NetAddress) bool {
return rfc3927Net.Contains(na.IP) return rfc3927Net.Contains(na.IP)
} }
// IsRFC3964 returns whether or not the passed address is part of the IPv6 to // IsRFC3964 returns whether or not the passed address is part of the IPv6 to
// IPv4 encapsulation range as defined by RFC3964 (2002::/16). // IPv4 encapsulation range as defined by RFC3964 (2002::/16).
func IsRFC3964(na *btcwire.NetAddress) bool { func IsRFC3964(na *wire.NetAddress) bool {
return rfc3964Net.Contains(na.IP) return rfc3964Net.Contains(na.IP)
} }
// IsRFC4193 returns whether or not the passed address is part of the IPv6 // IsRFC4193 returns whether or not the passed address is part of the IPv6
// unique local range as defined by RFC4193 (FC00::/7). // unique local range as defined by RFC4193 (FC00::/7).
func IsRFC4193(na *btcwire.NetAddress) bool { func IsRFC4193(na *wire.NetAddress) bool {
return rfc4193Net.Contains(na.IP) return rfc4193Net.Contains(na.IP)
} }
// IsRFC4380 returns whether or not the passed address is part of the IPv6 // IsRFC4380 returns whether or not the passed address is part of the IPv6
// teredo tunneling over UDP range as defined by RFC4380 (2001::/32). // teredo tunneling over UDP range as defined by RFC4380 (2001::/32).
func IsRFC4380(na *btcwire.NetAddress) bool { func IsRFC4380(na *wire.NetAddress) bool {
return rfc4380Net.Contains(na.IP) return rfc4380Net.Contains(na.IP)
} }
// IsRFC4843 returns whether or not the passed address is part of the IPv6 // IsRFC4843 returns whether or not the passed address is part of the IPv6
// ORCHID range as defined by RFC4843 (2001:10::/28). // ORCHID range as defined by RFC4843 (2001:10::/28).
func IsRFC4843(na *btcwire.NetAddress) bool { func IsRFC4843(na *wire.NetAddress) bool {
return rfc4843Net.Contains(na.IP) return rfc4843Net.Contains(na.IP)
} }
// IsRFC4862 returns whether or not the passed address is part of the IPv6 // IsRFC4862 returns whether or not the passed address is part of the IPv6
// stateless address autoconfiguration range as defined by RFC4862 (FE80::/64). // stateless address autoconfiguration range as defined by RFC4862 (FE80::/64).
func IsRFC4862(na *btcwire.NetAddress) bool { func IsRFC4862(na *wire.NetAddress) bool {
return rfc4862Net.Contains(na.IP) return rfc4862Net.Contains(na.IP)
} }
// IsRFC5737 returns whether or not the passed address is part of the IPv4 // IsRFC5737 returns whether or not the passed address is part of the IPv4
// documentation address space as defined by RFC5737 (192.0.2.0/24, // documentation address space as defined by RFC5737 (192.0.2.0/24,
// 198.51.100.0/24, 203.0.113.0/24) // 198.51.100.0/24, 203.0.113.0/24)
func IsRFC5737(na *btcwire.NetAddress) bool { func IsRFC5737(na *wire.NetAddress) bool {
for _, rfc := range rfc5737Net { for _, rfc := range rfc5737Net {
if rfc.Contains(na.IP) { if rfc.Contains(na.IP) {
return true return true
@ -192,19 +192,19 @@ func IsRFC5737(na *btcwire.NetAddress) bool {
// IsRFC6052 returns whether or not the passed address is part of the IPv6 // IsRFC6052 returns whether or not the passed address is part of the IPv6
// well-known prefix range as defined by RFC6052 (64:FF9B::/96). // well-known prefix range as defined by RFC6052 (64:FF9B::/96).
func IsRFC6052(na *btcwire.NetAddress) bool { func IsRFC6052(na *wire.NetAddress) bool {
return rfc6052Net.Contains(na.IP) return rfc6052Net.Contains(na.IP)
} }
// IsRFC6145 returns whether or not the passed address is part of the IPv6 to // IsRFC6145 returns whether or not the passed address is part of the IPv6 to
// IPv4 translated address range as defined by RFC6145 (::FFFF:0:0:0/96). // IPv4 translated address range as defined by RFC6145 (::FFFF:0:0:0/96).
func IsRFC6145(na *btcwire.NetAddress) bool { func IsRFC6145(na *wire.NetAddress) bool {
return rfc6145Net.Contains(na.IP) return rfc6145Net.Contains(na.IP)
} }
// IsRFC6598 returns whether or not the passed address is part of the IPv4 // IsRFC6598 returns whether or not the passed address is part of the IPv4
// shared address space specified by RFC6598 (100.64.0.0/10) // shared address space specified by RFC6598 (100.64.0.0/10)
func IsRFC6598(na *btcwire.NetAddress) bool { func IsRFC6598(na *wire.NetAddress) bool {
return rfc6598Net.Contains(na.IP) return rfc6598Net.Contains(na.IP)
} }
@ -212,7 +212,7 @@ func IsRFC6598(na *btcwire.NetAddress) bool {
// considered invalid under the following circumstances: // considered invalid under the following circumstances:
// IPv4: It is either a zero or all bits set address. // IPv4: It is either a zero or all bits set address.
// IPv6: It is either a zero or RFC3849 documentation address. // IPv6: It is either a zero or RFC3849 documentation address.
func IsValid(na *btcwire.NetAddress) bool { func IsValid(na *wire.NetAddress) bool {
// IsUnspecified returns if address is 0, so only all bits set, and // IsUnspecified returns if address is 0, so only all bits set, and
// RFC3849 need to be explicitly checked. // RFC3849 need to be explicitly checked.
return na.IP != nil && !(na.IP.IsUnspecified() || return na.IP != nil && !(na.IP.IsUnspecified() ||
@ -222,7 +222,7 @@ func IsValid(na *btcwire.NetAddress) bool {
// IsRoutable returns whether or not the passed address is routable over // IsRoutable returns whether or not the passed address is routable over
// the public internet. This is true as long as the address is valid and is not // the public internet. This is true as long as the address is valid and is not
// in any reserved ranges. // in any reserved ranges.
func IsRoutable(na *btcwire.NetAddress) bool { func IsRoutable(na *wire.NetAddress) bool {
return IsValid(na) && !(IsRFC1918(na) || IsRFC2544(na) || return IsValid(na) && !(IsRFC1918(na) || IsRFC2544(na) ||
IsRFC3927(na) || IsRFC4862(na) || IsRFC3849(na) || IsRFC3927(na) || IsRFC4862(na) || IsRFC3849(na) ||
IsRFC4843(na) || IsRFC5737(na) || IsRFC6598(na) || IsRFC4843(na) || IsRFC5737(na) || IsRFC6598(na) ||
@ -234,7 +234,7 @@ func IsRoutable(na *btcwire.NetAddress) bool {
// "local" for a local address, the string "tor:key" where key is the /4 of the // "local" for a local address, the string "tor:key" where key is the /4 of the
// onion address for tor address, and the string "unroutable" for an unroutable // onion address for tor address, and the string "unroutable" for an unroutable
// address. // address.
func GroupKey(na *btcwire.NetAddress) string { func GroupKey(na *wire.NetAddress) string {
if IsLocal(na) { if IsLocal(na) {
return "local" return "local"
} }

View file

@ -10,14 +10,14 @@ import (
"time" "time"
"github.com/btcsuite/btcd/addrmgr" "github.com/btcsuite/btcd/addrmgr"
"github.com/btcsuite/btcwire" "github.com/btcsuite/btcd/wire"
) )
// TestIPTypes ensures the various functions which determine the type of an IP // TestIPTypes ensures the various functions which determine the type of an IP
// address based on RFCs work as intended. // address based on RFCs work as intended.
func TestIPTypes(t *testing.T) { func TestIPTypes(t *testing.T) {
type ipTest struct { type ipTest struct {
in btcwire.NetAddress in wire.NetAddress
rfc1918 bool rfc1918 bool
rfc2544 bool rfc2544 bool
rfc3849 bool rfc3849 bool
@ -40,9 +40,9 @@ func TestIPTypes(t *testing.T) {
rfc4193, rfc4380, rfc4843, rfc4862, rfc5737, rfc6052, rfc6145, rfc6598, rfc4193, rfc4380, rfc4843, rfc4862, rfc5737, rfc6052, rfc6145, rfc6598,
local, valid, routable bool) ipTest { local, valid, routable bool) ipTest {
nip := net.ParseIP(ip) nip := net.ParseIP(ip)
na := btcwire.NetAddress{ na := wire.NetAddress{
Timestamp: time.Now(), Timestamp: time.Now(),
Services: btcwire.SFNodeNetwork, Services: wire.SFNodeNetwork,
IP: nip, IP: nip,
Port: 8333, Port: 8333,
} }
@ -198,9 +198,9 @@ func TestGroupKey(t *testing.T) {
for i, test := range tests { for i, test := range tests {
nip := net.ParseIP(test.ip) nip := net.ParseIP(test.ip)
na := btcwire.NetAddress{ na := wire.NetAddress{
Timestamp: time.Now(), Timestamp: time.Now(),
Services: btcwire.SFNodeNetwork, Services: wire.SFNodeNetwork,
IP: nip, IP: nip,
Port: 8333, Port: 8333,
} }

View file

@ -5,7 +5,7 @@
package blockchain package blockchain
import ( import (
"github.com/btcsuite/btcwire" "github.com/btcsuite/btcd/wire"
) )
// BlockLocator is used to help locate a specific block. The algorithm for // BlockLocator is used to help locate a specific block. The algorithm for
@ -23,7 +23,7 @@ import (
// //
// The block locator for block 17a would be the hashes of blocks: // The block locator for block 17a would be the hashes of blocks:
// [17a 16a 15 14 13 12 11 10 9 8 6 2 genesis] // [17a 16a 15 14 13 12 11 10 9 8 6 2 genesis]
type BlockLocator []*btcwire.ShaHash type BlockLocator []*wire.ShaHash
// BlockLocatorFromHash returns a block locator for the passed block hash. // BlockLocatorFromHash returns a block locator for the passed block hash.
// See BlockLocator for details on the algotirhm used to create a block locator. // See BlockLocator for details on the algotirhm used to create a block locator.
@ -35,9 +35,9 @@ type BlockLocator []*btcwire.ShaHash
// therefore the block locator will only consist of the genesis hash // therefore the block locator will only consist of the genesis hash
// - If the passed hash is not currently known, the block locator will only // - If the passed hash is not currently known, the block locator will only
// consist of the passed hash // consist of the passed hash
func (b *BlockChain) BlockLocatorFromHash(hash *btcwire.ShaHash) BlockLocator { func (b *BlockChain) BlockLocatorFromHash(hash *wire.ShaHash) BlockLocator {
// The locator contains the requested hash at the very least. // The locator contains the requested hash at the very least.
locator := make(BlockLocator, 0, btcwire.MaxBlockLocatorsPerMsg) locator := make(BlockLocator, 0, wire.MaxBlockLocatorsPerMsg)
locator = append(locator, hash) locator = append(locator, hash)
// Nothing more to do if a locator for the genesis hash was requested. // Nothing more to do if a locator for the genesis hash was requested.
@ -81,7 +81,7 @@ func (b *BlockChain) BlockLocatorFromHash(hash *btcwire.ShaHash) BlockLocator {
// final genesis hash. // final genesis hash.
iterNode := node iterNode := node
increment := int64(1) increment := int64(1)
for len(locator) < btcwire.MaxBlockLocatorsPerMsg-1 { for len(locator) < wire.MaxBlockLocatorsPerMsg-1 {
// Once there are 10 locators, exponentially increase the // Once there are 10 locators, exponentially increase the
// distance between each block locator. // distance between each block locator.
if len(locator) > 10 { if len(locator) > 10 {

View file

@ -14,9 +14,9 @@ import (
"time" "time"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcnet" "github.com/btcsuite/btcnet"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
) )
const ( const (
@ -49,13 +49,13 @@ type blockNode struct {
children []*blockNode children []*blockNode
// hash is the double sha 256 of the block. // hash is the double sha 256 of the block.
hash *btcwire.ShaHash hash *wire.ShaHash
// parentHash is the double sha 256 of the parent block. This is kept // parentHash is the double sha 256 of the parent block. This is kept
// here over simply relying on parent.hash directly since block nodes // here over simply relying on parent.hash directly since block nodes
// are sparse and the parent node might not be in memory when its hash // are sparse and the parent node might not be in memory when its hash
// is needed. // is needed.
parentHash *btcwire.ShaHash parentHash *wire.ShaHash
// height is the position in the block chain. // height is the position in the block chain.
height int64 height int64
@ -79,7 +79,7 @@ type blockNode struct {
// completely disconnected from the chain and the workSum value is just the work // completely disconnected from the chain and the workSum value is just the work
// for the passed block. The work sum is updated accordingly when the node is // for the passed block. The work sum is updated accordingly when the node is
// inserted into a chain. // inserted into a chain.
func newBlockNode(blockHeader *btcwire.BlockHeader, blockSha *btcwire.ShaHash, height int64) *blockNode { func newBlockNode(blockHeader *wire.BlockHeader, blockSha *wire.ShaHash, height int64) *blockNode {
// Make a copy of the hash so the node doesn't keep a reference to part // Make a copy of the hash so the node doesn't keep a reference to part
// of the full block/block header preventing it from being garbage // of the full block/block header preventing it from being garbage
// collected. // collected.
@ -148,13 +148,13 @@ type BlockChain struct {
notifications NotificationCallback notifications NotificationCallback
root *blockNode root *blockNode
bestChain *blockNode bestChain *blockNode
index map[btcwire.ShaHash]*blockNode index map[wire.ShaHash]*blockNode
depNodes map[btcwire.ShaHash][]*blockNode depNodes map[wire.ShaHash][]*blockNode
orphans map[btcwire.ShaHash]*orphanBlock orphans map[wire.ShaHash]*orphanBlock
prevOrphans map[btcwire.ShaHash][]*orphanBlock prevOrphans map[wire.ShaHash][]*orphanBlock
oldestOrphan *orphanBlock oldestOrphan *orphanBlock
orphanLock sync.RWMutex orphanLock sync.RWMutex
blockCache map[btcwire.ShaHash]*btcutil.Block blockCache map[wire.ShaHash]*btcutil.Block
noVerify bool noVerify bool
noCheckpoints bool noCheckpoints bool
nextCheckpoint *btcnet.Checkpoint nextCheckpoint *btcnet.Checkpoint
@ -175,7 +175,7 @@ func (b *BlockChain) DisableVerify(disable bool) {
// be like part of the main chain, on a side chain, or in the orphan pool. // be like part of the main chain, on a side chain, or in the orphan pool.
// //
// This function is NOT safe for concurrent access. // This function is NOT safe for concurrent access.
func (b *BlockChain) HaveBlock(hash *btcwire.ShaHash) (bool, error) { func (b *BlockChain) HaveBlock(hash *wire.ShaHash) (bool, error) {
exists, err := b.blockExists(hash) exists, err := b.blockExists(hash)
if err != nil { if err != nil {
return false, err return false, err
@ -193,7 +193,7 @@ func (b *BlockChain) HaveBlock(hash *btcwire.ShaHash) (bool, error) {
// duplicate orphans and react accordingly. // duplicate orphans and react accordingly.
// //
// This function is safe for concurrent access. // This function is safe for concurrent access.
func (b *BlockChain) IsKnownOrphan(hash *btcwire.ShaHash) bool { func (b *BlockChain) IsKnownOrphan(hash *wire.ShaHash) bool {
// Protect concurrent access. Using a read lock only so multiple // Protect concurrent access. Using a read lock only so multiple
// readers can query without blocking each other. // readers can query without blocking each other.
b.orphanLock.RLock() b.orphanLock.RLock()
@ -210,7 +210,7 @@ func (b *BlockChain) IsKnownOrphan(hash *btcwire.ShaHash) bool {
// map of orphan blocks. // map of orphan blocks.
// //
// This function is safe for concurrent access. // This function is safe for concurrent access.
func (b *BlockChain) GetOrphanRoot(hash *btcwire.ShaHash) *btcwire.ShaHash { func (b *BlockChain) GetOrphanRoot(hash *wire.ShaHash) *wire.ShaHash {
// Protect concurrent access. Using a read lock only so multiple // Protect concurrent access. Using a read lock only so multiple
// readers can query without blocking each other. // readers can query without blocking each other.
b.orphanLock.RLock() b.orphanLock.RLock()
@ -399,7 +399,7 @@ func (b *BlockChain) GenerateInitialIndex() error {
// creates a block node from it, and updates the memory block chain accordingly. // creates a block node from it, and updates the memory block chain accordingly.
// It is used mainly to dynamically load previous blocks from database as they // It is used mainly to dynamically load previous blocks from database as they
// are needed to avoid needing to put the entire block chain in memory. // are needed to avoid needing to put the entire block chain in memory.
func (b *BlockChain) loadBlockNode(hash *btcwire.ShaHash) (*blockNode, error) { func (b *BlockChain) loadBlockNode(hash *wire.ShaHash) (*blockNode, error) {
// Load the block header and height from the db. // Load the block header and height from the db.
blockHeader, err := b.db.FetchBlockHeaderBySha(hash) blockHeader, err := b.db.FetchBlockHeaderBySha(hash)
if err != nil { if err != nil {
@ -1087,11 +1087,11 @@ func New(db database.Db, params *btcnet.Params, c NotificationCallback) *BlockCh
notifications: c, notifications: c,
root: nil, root: nil,
bestChain: nil, bestChain: nil,
index: make(map[btcwire.ShaHash]*blockNode), index: make(map[wire.ShaHash]*blockNode),
depNodes: make(map[btcwire.ShaHash][]*blockNode), depNodes: make(map[wire.ShaHash][]*blockNode),
orphans: make(map[btcwire.ShaHash]*orphanBlock), orphans: make(map[wire.ShaHash]*orphanBlock),
prevOrphans: make(map[btcwire.ShaHash][]*orphanBlock), prevOrphans: make(map[wire.ShaHash][]*orphanBlock),
blockCache: make(map[btcwire.ShaHash]*btcutil.Block), blockCache: make(map[wire.ShaHash]*btcutil.Block),
} }
return &b return &b
} }

View file

@ -8,9 +8,9 @@ import (
"testing" "testing"
"github.com/btcsuite/btcd/blockchain" "github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcnet" "github.com/btcsuite/btcnet"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
) )
// TestHaveBlock tests the HaveBlock API to ensure proper functionality. // TestHaveBlock tests the HaveBlock API to ensure proper functionality.
@ -94,7 +94,7 @@ func TestHaveBlock(t *testing.T) {
} }
for i, test := range tests { for i, test := range tests {
hash, err := btcwire.NewShaHashFromStr(test.hash) hash, err := wire.NewShaHashFromStr(test.hash)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
continue continue

View file

@ -8,9 +8,9 @@ import (
"fmt" "fmt"
"github.com/btcsuite/btcd/txscript" "github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcnet" "github.com/btcsuite/btcnet"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
) )
// CheckpointConfirmations is the number of blocks before the end of the current // CheckpointConfirmations is the number of blocks before the end of the current
@ -18,11 +18,11 @@ import (
const CheckpointConfirmations = 2016 const CheckpointConfirmations = 2016
// newShaHashFromStr converts the passed big-endian hex string into a // newShaHashFromStr converts the passed big-endian hex string into a
// btcwire.ShaHash. It only differs from the one available in btcwire in that // wire.ShaHash. It only differs from the one available in btcwire in that
// it ignores the error since it will only (and must only) be called with // it ignores the error since it will only (and must only) be called with
// hard-coded, and therefore known good, hashes. // hard-coded, and therefore known good, hashes.
func newShaHashFromStr(hexStr string) *btcwire.ShaHash { func newShaHashFromStr(hexStr string) *wire.ShaHash {
sha, _ := btcwire.NewShaHashFromStr(hexStr) sha, _ := wire.NewShaHashFromStr(hexStr)
return sha return sha
} }
@ -59,7 +59,7 @@ func (b *BlockChain) LatestCheckpoint() *btcnet.Checkpoint {
// verifyCheckpoint returns whether the passed block height and hash combination // verifyCheckpoint returns whether the passed block height and hash combination
// match the hard-coded checkpoint data. It also returns true if there is no // match the hard-coded checkpoint data. It also returns true if there is no
// checkpoint data for the passed block height. // checkpoint data for the passed block height.
func (b *BlockChain) verifyCheckpoint(height int64, hash *btcwire.ShaHash) bool { func (b *BlockChain) verifyCheckpoint(height int64, hash *wire.ShaHash) bool {
if b.noCheckpoints || len(b.netParams.Checkpoints) == 0 { if b.noCheckpoints || len(b.netParams.Checkpoints) == 0 {
return true return true
} }

View file

@ -17,9 +17,9 @@ import (
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
_ "github.com/btcsuite/btcd/database/ldb" _ "github.com/btcsuite/btcd/database/ldb"
_ "github.com/btcsuite/btcd/database/memdb" _ "github.com/btcsuite/btcd/database/memdb"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcnet" "github.com/btcsuite/btcnet"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
) )
// testDbType is the database backend type to use for the tests. // testDbType is the database backend type to use for the tests.
@ -161,14 +161,14 @@ func loadTxStore(filename string) (blockchain.TxStore, error) {
return nil, err return nil, err
} }
serializedTxLen := uintBuf serializedTxLen := uintBuf
if serializedTxLen > btcwire.MaxBlockPayload { if serializedTxLen > wire.MaxBlockPayload {
return nil, fmt.Errorf("Read serialized transaction "+ return nil, fmt.Errorf("Read serialized transaction "+
"length of %d is larger max allowed %d", "length of %d is larger max allowed %d",
serializedTxLen, btcwire.MaxBlockPayload) serializedTxLen, wire.MaxBlockPayload)
} }
// Transaction. // Transaction.
var msgTx btcwire.MsgTx var msgTx wire.MsgTx
err = msgTx.Deserialize(r) err = msgTx.Deserialize(r)
if err != nil { if err != nil {
return nil, err return nil, err

View file

@ -9,7 +9,7 @@ import (
"math/big" "math/big"
"time" "time"
"github.com/btcsuite/btcwire" "github.com/btcsuite/btcd/wire"
) )
const ( const (
@ -53,9 +53,9 @@ var (
oneLsh256 = new(big.Int).Lsh(bigOne, 256) oneLsh256 = new(big.Int).Lsh(bigOne, 256)
) )
// ShaHashToBig converts a btcwire.ShaHash into a big.Int that can be used to // ShaHashToBig converts a wire.ShaHash into a big.Int that can be used to
// perform math comparisons. // perform math comparisons.
func ShaHashToBig(hash *btcwire.ShaHash) *big.Int { func ShaHashToBig(hash *wire.ShaHash) *big.Int {
// A ShaHash is in little-endian, but the big package wants the bytes // A ShaHash is in little-endian, but the big package wants the bytes
// in big-endian. Reverse them. ShaHash.Bytes makes a copy, so it // in big-endian. Reverse them. ShaHash.Bytes makes a copy, so it
// is safe to modify the returned buffer. // is safe to modify the returned buffer.

View file

@ -7,8 +7,8 @@ package blockchain
import ( import (
"math" "math"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
) )
// nextPowerOfTwo returns the next highest power of two from a given number if // nextPowerOfTwo returns the next highest power of two from a given number if
@ -28,16 +28,16 @@ func nextPowerOfTwo(n int) int {
// HashMerkleBranches takes two hashes, treated as the left and right tree // HashMerkleBranches takes two hashes, treated as the left and right tree
// nodes, and returns the hash of their concatenation. This is a helper // nodes, and returns the hash of their concatenation. This is a helper
// function used to aid in the generation of a merkle tree. // function used to aid in the generation of a merkle tree.
func HashMerkleBranches(left *btcwire.ShaHash, right *btcwire.ShaHash) *btcwire.ShaHash { func HashMerkleBranches(left *wire.ShaHash, right *wire.ShaHash) *wire.ShaHash {
// Concatenate the left and right nodes. // Concatenate the left and right nodes.
var sha [btcwire.HashSize * 2]byte var sha [wire.HashSize * 2]byte
copy(sha[:btcwire.HashSize], left.Bytes()) copy(sha[:wire.HashSize], left.Bytes())
copy(sha[btcwire.HashSize:], right.Bytes()) copy(sha[wire.HashSize:], right.Bytes())
// Create a new sha hash from the double sha 256. Ignore the error // Create a new sha hash from the double sha 256. Ignore the error
// here since SetBytes can't fail here due to the fact DoubleSha256 // here since SetBytes can't fail here due to the fact DoubleSha256
// always returns a []byte of the right size regardless of input. // always returns a []byte of the right size regardless of input.
newSha, _ := btcwire.NewShaHash(btcwire.DoubleSha256(sha[:])) newSha, _ := wire.NewShaHash(wire.DoubleSha256(sha[:]))
return newSha return newSha
} }
@ -69,12 +69,12 @@ func HashMerkleBranches(left *btcwire.ShaHash, right *btcwire.ShaHash) *btcwire.
// are calculated by concatenating the left node with itself before hashing. // are calculated by concatenating the left node with itself before hashing.
// Since this function uses nodes that are pointers to the hashes, empty nodes // Since this function uses nodes that are pointers to the hashes, empty nodes
// will be nil. // will be nil.
func BuildMerkleTreeStore(transactions []*btcutil.Tx) []*btcwire.ShaHash { func BuildMerkleTreeStore(transactions []*btcutil.Tx) []*wire.ShaHash {
// Calculate how many entries are required to hold the binary merkle // Calculate how many entries are required to hold the binary merkle
// tree as a linear array and create an array of that size. // tree as a linear array and create an array of that size.
nextPoT := nextPowerOfTwo(len(transactions)) nextPoT := nextPowerOfTwo(len(transactions))
arraySize := nextPoT*2 - 1 arraySize := nextPoT*2 - 1
merkles := make([]*btcwire.ShaHash, arraySize) merkles := make([]*wire.ShaHash, arraySize)
// Create the base transaction shas and populate the array with them. // Create the base transaction shas and populate the array with them.
for i, tx := range transactions { for i, tx := range transactions {

View file

@ -7,8 +7,8 @@ package blockchain
import ( import (
"fmt" "fmt"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
) )
// BehaviorFlags is a bitmask defining tweaks to the normal behavior when // BehaviorFlags is a bitmask defining tweaks to the normal behavior when
@ -38,7 +38,7 @@ const (
// blockExists determines whether a block with the given hash exists either in // blockExists determines whether a block with the given hash exists either in
// the main chain or any side chains. // the main chain or any side chains.
func (b *BlockChain) blockExists(hash *btcwire.ShaHash) (bool, error) { func (b *BlockChain) blockExists(hash *wire.ShaHash) (bool, error) {
// Check memory chain first (could be main chain or side chain blocks). // Check memory chain first (could be main chain or side chain blocks).
if _, ok := b.index[*hash]; ok { if _, ok := b.index[*hash]; ok {
return true, nil return true, nil
@ -55,11 +55,11 @@ func (b *BlockChain) blockExists(hash *btcwire.ShaHash) (bool, error) {
// //
// The flags do not modify the behavior of this function directly, however they // The flags do not modify the behavior of this function directly, however they
// are needed to pass along to maybeAcceptBlock. // are needed to pass along to maybeAcceptBlock.
func (b *BlockChain) processOrphans(hash *btcwire.ShaHash, flags BehaviorFlags) error { func (b *BlockChain) processOrphans(hash *wire.ShaHash, flags BehaviorFlags) error {
// Start with processing at least the passed hash. Leave a little room // Start with processing at least the passed hash. Leave a little room
// for additional orphan blocks that need to be processed without // for additional orphan blocks that need to be processed without
// needing to grow the array in the common case. // needing to grow the array in the common case.
processHashes := make([]*btcwire.ShaHash, 0, 10) processHashes := make([]*wire.ShaHash, 0, 10)
processHashes = append(processHashes, hash) processHashes = append(processHashes, hash)
for len(processHashes) > 0 { for len(processHashes) > 0 {
// Pop the first hash to process from the slice. // Pop the first hash to process from the slice.

View file

@ -14,8 +14,8 @@ import (
"testing" "testing"
"github.com/btcsuite/btcd/blockchain" "github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
) )
// TestReorganization loads a set of test blocks which force a chain // TestReorganization loads a set of test blocks which force a chain
@ -81,7 +81,7 @@ func TestReorganization(t *testing.T) {
func loadBlocks(filename string) (blocks []*btcutil.Block, err error) { func loadBlocks(filename string) (blocks []*btcutil.Block, err error) {
filename = filepath.Join("testdata/", filename) filename = filepath.Join("testdata/", filename)
var network = btcwire.MainNet var network = wire.MainNet
var dr io.Reader var dr io.Reader
var fi io.ReadCloser var fi io.ReadCloser

View file

@ -10,14 +10,14 @@ import (
"runtime" "runtime"
"github.com/btcsuite/btcd/txscript" "github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
) )
// txValidateItem holds a transaction along with which input to validate. // txValidateItem holds a transaction along with which input to validate.
type txValidateItem struct { type txValidateItem struct {
txInIndex int txInIndex int
txIn *btcwire.TxIn txIn *wire.TxIn
tx *btcutil.Tx tx *btcutil.Tx
} }

View file

@ -8,15 +8,15 @@ import (
"fmt" "fmt"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
) )
// TxData contains contextual information about transactions such as which block // TxData contains contextual information about transactions such as which block
// they were found in and whether or not the outputs are spent. // they were found in and whether or not the outputs are spent.
type TxData struct { type TxData struct {
Tx *btcutil.Tx Tx *btcutil.Tx
Hash *btcwire.ShaHash Hash *wire.ShaHash
BlockHeight int64 BlockHeight int64
Spent []bool Spent []bool
Err error Err error
@ -26,7 +26,7 @@ type TxData struct {
// such as script validation and double spend prevention. This also allows the // such as script validation and double spend prevention. This also allows the
// transaction data to be treated as a view since it can contain the information // transaction data to be treated as a view since it can contain the information
// from the point-of-view of different points in the chain. // from the point-of-view of different points in the chain.
type TxStore map[btcwire.ShaHash]*TxData type TxStore map[wire.ShaHash]*TxData
// connectTransactions updates the passed map by applying transaction and // connectTransactions updates the passed map by applying transaction and
// spend information for all the transactions in the passed block. Only // spend information for all the transactions in the passed block. Only
@ -101,7 +101,7 @@ func disconnectTransactions(txStore TxStore, block *btcutil.Block) error {
// transactions from the point of view of the end of the main chain. It takes // transactions from the point of view of the end of the main chain. It takes
// a flag which specifies whether or not fully spent transaction should be // a flag which specifies whether or not fully spent transaction should be
// included in the results. // included in the results.
func fetchTxStoreMain(db database.Db, txSet map[btcwire.ShaHash]struct{}, includeSpent bool) TxStore { func fetchTxStoreMain(db database.Db, txSet map[wire.ShaHash]struct{}, includeSpent bool) TxStore {
// Just return an empty store now if there are no requested hashes. // Just return an empty store now if there are no requested hashes.
txStore := make(TxStore) txStore := make(TxStore)
if len(txSet) == 0 { if len(txSet) == 0 {
@ -111,7 +111,7 @@ func fetchTxStoreMain(db database.Db, txSet map[btcwire.ShaHash]struct{}, includ
// The transaction store map needs to have an entry for every requested // The transaction store map needs to have an entry for every requested
// transaction. By default, all the transactions are marked as missing. // transaction. By default, all the transactions are marked as missing.
// Each entry will be filled in with the appropriate data below. // Each entry will be filled in with the appropriate data below.
txList := make([]*btcwire.ShaHash, 0, len(txSet)) txList := make([]*wire.ShaHash, 0, len(txSet))
for hash := range txSet { for hash := range txSet {
hashCopy := hash hashCopy := hash
txStore[hash] = &TxData{Hash: &hashCopy, Err: database.ErrTxShaMissing} txStore[hash] = &TxData{Hash: &hashCopy, Err: database.ErrTxShaMissing}
@ -161,7 +161,7 @@ func fetchTxStoreMain(db database.Db, txSet map[btcwire.ShaHash]struct{}, includ
// chain). Another scenario is where a transaction exists from the point of // chain). Another scenario is where a transaction exists from the point of
// view of the main chain, but doesn't exist in a side chain that branches // view of the main chain, but doesn't exist in a side chain that branches
// before the block that contains the transaction on the main chain. // before the block that contains the transaction on the main chain.
func (b *BlockChain) fetchTxStore(node *blockNode, txSet map[btcwire.ShaHash]struct{}) (TxStore, error) { func (b *BlockChain) fetchTxStore(node *blockNode, txSet map[wire.ShaHash]struct{}) (TxStore, error) {
// Get the previous block node. This function is used over simply // Get the previous block node. This function is used over simply
// accessing node.parent directly as it will dynamically create previous // accessing node.parent directly as it will dynamically create previous
// block nodes as needed. This helps allow only the pieces of the chain // block nodes as needed. This helps allow only the pieces of the chain
@ -237,7 +237,7 @@ func (b *BlockChain) fetchInputTransactions(node *blockNode, block *btcutil.Bloc
// Build a map of in-flight transactions because some of the inputs in // Build a map of in-flight transactions because some of the inputs in
// this block could be referencing other transactions earlier in this // this block could be referencing other transactions earlier in this
// block which are not yet in the chain. // block which are not yet in the chain.
txInFlight := map[btcwire.ShaHash]int{} txInFlight := map[wire.ShaHash]int{}
transactions := block.Transactions() transactions := block.Transactions()
for i, tx := range transactions { for i, tx := range transactions {
txInFlight[*tx.Sha()] = i txInFlight[*tx.Sha()] = i
@ -246,7 +246,7 @@ func (b *BlockChain) fetchInputTransactions(node *blockNode, block *btcutil.Bloc
// Loop through all of the transaction inputs (except for the coinbase // Loop through all of the transaction inputs (except for the coinbase
// which has no inputs) collecting them into sets of what is needed and // which has no inputs) collecting them into sets of what is needed and
// what is already known (in-flight). // what is already known (in-flight).
txNeededSet := make(map[btcwire.ShaHash]struct{}) txNeededSet := make(map[wire.ShaHash]struct{})
txStore := make(TxStore) txStore := make(TxStore)
for i, tx := range transactions[1:] { for i, tx := range transactions[1:] {
for _, txIn := range tx.MsgTx().TxIn { for _, txIn := range tx.MsgTx().TxIn {
@ -303,7 +303,7 @@ func (b *BlockChain) FetchTransactionStore(tx *btcutil.Tx) (TxStore, error) {
// Create a set of needed transactions from the transactions referenced // Create a set of needed transactions from the transactions referenced
// by the inputs of the passed transaction. Also, add the passed // by the inputs of the passed transaction. Also, add the passed
// transaction itself as a way for the caller to detect duplicates. // transaction itself as a way for the caller to detect duplicates.
txNeededSet := make(map[btcwire.ShaHash]struct{}) txNeededSet := make(map[wire.ShaHash]struct{})
txNeededSet[*tx.Sha()] = struct{}{} txNeededSet[*tx.Sha()] = struct{}{}
for _, txIn := range tx.MsgTx().TxIn { for _, txIn := range tx.MsgTx().TxIn {
txNeededSet[txIn.PreviousOutPoint.Hash] = struct{}{} txNeededSet[txIn.PreviousOutPoint.Hash] = struct{}{}

View file

@ -13,15 +13,15 @@ import (
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcd/txscript" "github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcnet" "github.com/btcsuite/btcnet"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
) )
const ( const (
// MaxSigOpsPerBlock is the maximum number of signature operations // MaxSigOpsPerBlock is the maximum number of signature operations
// allowed for a block. It is a fraction of the max block payload size. // allowed for a block. It is a fraction of the max block payload size.
MaxSigOpsPerBlock = btcwire.MaxBlockPayload / 50 MaxSigOpsPerBlock = wire.MaxBlockPayload / 50
// lockTimeThreshold is the number below which a lock time is // lockTimeThreshold is the number below which a lock time is
// interpreted to be a block number. Since an average of one block // interpreted to be a block number. Since an average of one block
@ -64,10 +64,10 @@ var (
// constant is used because the tests need the ability to modify it. // constant is used because the tests need the ability to modify it.
coinbaseMaturity = int64(CoinbaseMaturity) coinbaseMaturity = int64(CoinbaseMaturity)
// zeroHash is the zero value for a btcwire.ShaHash and is defined as // zeroHash is the zero value for a wire.ShaHash and is defined as
// a package level variable to avoid the need to create a new instance // a package level variable to avoid the need to create a new instance
// every time a check is needed. // every time a check is needed.
zeroHash = &btcwire.ShaHash{} zeroHash = &wire.ShaHash{}
// block91842Hash is one of the two nodes which violate the rules // block91842Hash is one of the two nodes which violate the rules
// set forth in BIP0030. It is defined as a package level variable to // set forth in BIP0030. It is defined as a package level variable to
@ -82,7 +82,7 @@ var (
// isNullOutpoint determines whether or not a previous transaction output point // isNullOutpoint determines whether or not a previous transaction output point
// is set. // is set.
func isNullOutpoint(outpoint *btcwire.OutPoint) bool { func isNullOutpoint(outpoint *wire.OutPoint) bool {
if outpoint.Index == math.MaxUint32 && outpoint.Hash.IsEqual(zeroHash) { if outpoint.Index == math.MaxUint32 && outpoint.Hash.IsEqual(zeroHash) {
return true return true
} }
@ -198,9 +198,9 @@ func CheckTransactionSanity(tx *btcutil.Tx) error {
// A transaction must not exceed the maximum allowed block payload when // A transaction must not exceed the maximum allowed block payload when
// serialized. // serialized.
serializedTxSize := tx.MsgTx().SerializeSize() serializedTxSize := tx.MsgTx().SerializeSize()
if serializedTxSize > btcwire.MaxBlockPayload { if serializedTxSize > wire.MaxBlockPayload {
str := fmt.Sprintf("serialized transaction is too big - got "+ str := fmt.Sprintf("serialized transaction is too big - got "+
"%d, max %d", serializedTxSize, btcwire.MaxBlockPayload) "%d, max %d", serializedTxSize, wire.MaxBlockPayload)
return ruleError(ErrTxTooBig, str) return ruleError(ErrTxTooBig, str)
} }
@ -244,7 +244,7 @@ func CheckTransactionSanity(tx *btcutil.Tx) error {
} }
// Check for duplicate transaction inputs. // Check for duplicate transaction inputs.
existingTxOut := make(map[btcwire.OutPoint]struct{}) existingTxOut := make(map[wire.OutPoint]struct{})
for _, txIn := range msgTx.TxIn { for _, txIn := range msgTx.TxIn {
if _, exists := existingTxOut[txIn.PreviousOutPoint]; exists { if _, exists := existingTxOut[txIn.PreviousOutPoint]; exists {
return ruleError(ErrDuplicateTxInputs, "transaction "+ return ruleError(ErrDuplicateTxInputs, "transaction "+
@ -433,18 +433,18 @@ func checkBlockSanity(block *btcutil.Block, powLimit *big.Int, timeSource Median
} }
// A block must not have more transactions than the max block payload. // A block must not have more transactions than the max block payload.
if numTx > btcwire.MaxBlockPayload { if numTx > wire.MaxBlockPayload {
str := fmt.Sprintf("block contains too many transactions - "+ str := fmt.Sprintf("block contains too many transactions - "+
"got %d, max %d", numTx, btcwire.MaxBlockPayload) "got %d, max %d", numTx, wire.MaxBlockPayload)
return ruleError(ErrTooManyTransactions, str) return ruleError(ErrTooManyTransactions, str)
} }
// A block must not exceed the maximum allowed block payload when // A block must not exceed the maximum allowed block payload when
// serialized. // serialized.
serializedSize := msgBlock.SerializeSize() serializedSize := msgBlock.SerializeSize()
if serializedSize > btcwire.MaxBlockPayload { if serializedSize > wire.MaxBlockPayload {
str := fmt.Sprintf("serialized block is too big - got %d, "+ str := fmt.Sprintf("serialized block is too big - got %d, "+
"max %d", serializedSize, btcwire.MaxBlockPayload) "max %d", serializedSize, wire.MaxBlockPayload)
return ruleError(ErrBlockTooBig, str) return ruleError(ErrBlockTooBig, str)
} }
@ -520,7 +520,7 @@ func checkBlockSanity(block *btcutil.Block, powLimit *big.Int, timeSource Median
// Check for duplicate transactions. This check will be fairly quick // Check for duplicate transactions. This check will be fairly quick
// since the transaction hashes are already cached due to building the // since the transaction hashes are already cached due to building the
// merkle tree above. // merkle tree above.
existingTxHashes := make(map[btcwire.ShaHash]struct{}) existingTxHashes := make(map[wire.ShaHash]struct{})
for _, tx := range transactions { for _, tx := range transactions {
hash := tx.Sha() hash := tx.Sha()
if _, exists := existingTxHashes[*hash]; exists { if _, exists := existingTxHashes[*hash]; exists {
@ -613,7 +613,7 @@ func isTransactionSpent(txD *TxData) bool {
func (b *BlockChain) checkBIP0030(node *blockNode, block *btcutil.Block) error { func (b *BlockChain) checkBIP0030(node *blockNode, block *btcutil.Block) error {
// Attempt to fetch duplicate transactions for all of the transactions // Attempt to fetch duplicate transactions for all of the transactions
// in this block from the point of view of the parent node. // in this block from the point of view of the parent node.
fetchSet := make(map[btcwire.ShaHash]struct{}) fetchSet := make(map[wire.ShaHash]struct{})
for _, tx := range block.Transactions() { for _, tx := range block.Transactions() {
fetchSet[*tx.Sha()] = struct{}{} fetchSet[*tx.Sha()] = struct{}{}
} }

View file

@ -11,9 +11,9 @@ import (
"time" "time"
"github.com/btcsuite/btcd/blockchain" "github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcnet" "github.com/btcsuite/btcnet"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
) )
// TestCheckConnectBlock tests the CheckConnectBlock function to ensure it // TestCheckConnectBlock tests the CheckConnectBlock function to ensure it
@ -67,10 +67,10 @@ func TestCheckBlockSanity(t *testing.T) {
// and handled properly. // and handled properly.
func TestCheckSerializedHeight(t *testing.T) { func TestCheckSerializedHeight(t *testing.T) {
// Create an empty coinbase template to be used in the tests below. // Create an empty coinbase template to be used in the tests below.
coinbaseOutpoint := btcwire.NewOutPoint(&btcwire.ShaHash{}, math.MaxUint32) coinbaseOutpoint := wire.NewOutPoint(&wire.ShaHash{}, math.MaxUint32)
coinbaseTx := btcwire.NewMsgTx() coinbaseTx := wire.NewMsgTx()
coinbaseTx.Version = 2 coinbaseTx.Version = 2
coinbaseTx.AddTxIn(btcwire.NewTxIn(coinbaseOutpoint, nil)) coinbaseTx.AddTxIn(wire.NewTxIn(coinbaseOutpoint, nil))
// Expected rule errors. // Expected rule errors.
missingHeightError := blockchain.RuleError{ missingHeightError := blockchain.RuleError{
@ -130,16 +130,16 @@ func TestCheckSerializedHeight(t *testing.T) {
// Block100000 defines block 100,000 of the block chain. It is used to // Block100000 defines block 100,000 of the block chain. It is used to
// test Block operations. // test Block operations.
var Block100000 = btcwire.MsgBlock{ var Block100000 = wire.MsgBlock{
Header: btcwire.BlockHeader{ Header: wire.BlockHeader{
Version: 1, Version: 1,
PrevBlock: btcwire.ShaHash([32]byte{ // Make go vet happy. PrevBlock: wire.ShaHash([32]byte{ // Make go vet happy.
0x50, 0x12, 0x01, 0x19, 0x17, 0x2a, 0x61, 0x04, 0x50, 0x12, 0x01, 0x19, 0x17, 0x2a, 0x61, 0x04,
0x21, 0xa6, 0xc3, 0x01, 0x1d, 0xd3, 0x30, 0xd9, 0x21, 0xa6, 0xc3, 0x01, 0x1d, 0xd3, 0x30, 0xd9,
0xdf, 0x07, 0xb6, 0x36, 0x16, 0xc2, 0xcc, 0x1f, 0xdf, 0x07, 0xb6, 0x36, 0x16, 0xc2, 0xcc, 0x1f,
0x1c, 0xd0, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1c, 0xd0, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
}), // 000000000002d01c1fccc21636b607dfd930d31d01c3a62104612a1719011250 }), // 000000000002d01c1fccc21636b607dfd930d31d01c3a62104612a1719011250
MerkleRoot: btcwire.ShaHash([32]byte{ // Make go vet happy. MerkleRoot: wire.ShaHash([32]byte{ // Make go vet happy.
0x66, 0x57, 0xa9, 0x25, 0x2a, 0xac, 0xd5, 0xc0, 0x66, 0x57, 0xa9, 0x25, 0x2a, 0xac, 0xd5, 0xc0,
0xb2, 0x94, 0x09, 0x96, 0xec, 0xff, 0x95, 0x22, 0xb2, 0x94, 0x09, 0x96, 0xec, 0xff, 0x95, 0x22,
0x28, 0xc3, 0x06, 0x7c, 0xc3, 0x8d, 0x48, 0x85, 0x28, 0xc3, 0x06, 0x7c, 0xc3, 0x8d, 0x48, 0x85,
@ -149,13 +149,13 @@ var Block100000 = btcwire.MsgBlock{
Bits: 0x1b04864c, // 453281356 Bits: 0x1b04864c, // 453281356
Nonce: 0x10572b0f, // 274148111 Nonce: 0x10572b0f, // 274148111
}, },
Transactions: []*btcwire.MsgTx{ Transactions: []*wire.MsgTx{
{ {
Version: 1, Version: 1,
TxIn: []*btcwire.TxIn{ TxIn: []*wire.TxIn{
{ {
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash{}, Hash: wire.ShaHash{},
Index: 0xffffffff, Index: 0xffffffff,
}, },
SignatureScript: []byte{ SignatureScript: []byte{
@ -164,7 +164,7 @@ var Block100000 = btcwire.MsgBlock{
Sequence: 0xffffffff, Sequence: 0xffffffff,
}, },
}, },
TxOut: []*btcwire.TxOut{ TxOut: []*wire.TxOut{
{ {
Value: 0x12a05f200, // 5000000000 Value: 0x12a05f200, // 5000000000
PkScript: []byte{ PkScript: []byte{
@ -186,10 +186,10 @@ var Block100000 = btcwire.MsgBlock{
}, },
{ {
Version: 1, Version: 1,
TxIn: []*btcwire.TxIn{ TxIn: []*wire.TxIn{
{ {
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash([32]byte{ // Make go vet happy. Hash: wire.ShaHash([32]byte{ // Make go vet happy.
0x03, 0x2e, 0x38, 0xe9, 0xc0, 0xa8, 0x4c, 0x60, 0x03, 0x2e, 0x38, 0xe9, 0xc0, 0xa8, 0x4c, 0x60,
0x46, 0xd6, 0x87, 0xd1, 0x05, 0x56, 0xdc, 0xac, 0x46, 0xd6, 0x87, 0xd1, 0x05, 0x56, 0xdc, 0xac,
0xc4, 0x1d, 0x27, 0x5e, 0xc5, 0x5f, 0xc0, 0x07, 0xc4, 0x1d, 0x27, 0x5e, 0xc5, 0x5f, 0xc0, 0x07,
@ -223,7 +223,7 @@ var Block100000 = btcwire.MsgBlock{
Sequence: 0xffffffff, Sequence: 0xffffffff,
}, },
}, },
TxOut: []*btcwire.TxOut{ TxOut: []*wire.TxOut{
{ {
Value: 0x2123e300, // 556000000 Value: 0x2123e300, // 556000000
PkScript: []byte{ PkScript: []byte{
@ -255,10 +255,10 @@ var Block100000 = btcwire.MsgBlock{
}, },
{ {
Version: 1, Version: 1,
TxIn: []*btcwire.TxIn{ TxIn: []*wire.TxIn{
{ {
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash([32]byte{ // Make go vet happy. Hash: wire.ShaHash([32]byte{ // Make go vet happy.
0xc3, 0x3e, 0xbf, 0xf2, 0xa7, 0x09, 0xf1, 0x3d, 0xc3, 0x3e, 0xbf, 0xf2, 0xa7, 0x09, 0xf1, 0x3d,
0x9f, 0x9a, 0x75, 0x69, 0xab, 0x16, 0xa3, 0x27, 0x9f, 0x9a, 0x75, 0x69, 0xab, 0x16, 0xa3, 0x27,
0x86, 0xaf, 0x7d, 0x7e, 0x2d, 0xe0, 0x92, 0x65, 0x86, 0xaf, 0x7d, 0x7e, 0x2d, 0xe0, 0x92, 0x65,
@ -291,7 +291,7 @@ var Block100000 = btcwire.MsgBlock{
Sequence: 0xffffffff, Sequence: 0xffffffff,
}, },
}, },
TxOut: []*btcwire.TxOut{ TxOut: []*wire.TxOut{
{ {
Value: 0xf4240, // 1000000 Value: 0xf4240, // 1000000
PkScript: []byte{ PkScript: []byte{
@ -323,10 +323,10 @@ var Block100000 = btcwire.MsgBlock{
}, },
{ {
Version: 1, Version: 1,
TxIn: []*btcwire.TxIn{ TxIn: []*wire.TxIn{
{ {
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash([32]byte{ // Make go vet happy. Hash: wire.ShaHash([32]byte{ // Make go vet happy.
0x0b, 0x60, 0x72, 0xb3, 0x86, 0xd4, 0xa7, 0x73, 0x0b, 0x60, 0x72, 0xb3, 0x86, 0xd4, 0xa7, 0x73,
0x23, 0x52, 0x37, 0xf6, 0x4c, 0x11, 0x26, 0xac, 0x23, 0x52, 0x37, 0xf6, 0x4c, 0x11, 0x26, 0xac,
0x3b, 0x24, 0x0c, 0x84, 0xb9, 0x17, 0xa3, 0x90, 0x3b, 0x24, 0x0c, 0x84, 0xb9, 0x17, 0xa3, 0x90,
@ -360,7 +360,7 @@ var Block100000 = btcwire.MsgBlock{
Sequence: 0xffffffff, Sequence: 0xffffffff,
}, },
}, },
TxOut: []*btcwire.TxOut{ TxOut: []*wire.TxOut{
{ {
Value: 0xf4240, // 1000000 Value: 0xf4240, // 1000000
PkScript: []byte{ PkScript: []byte{

View file

@ -15,9 +15,9 @@ import (
"github.com/btcsuite/btcd/blockchain" "github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcnet" "github.com/btcsuite/btcnet"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
) )
const ( const (
@ -49,14 +49,14 @@ type blockMsg struct {
// invMsg packages a bitcoin inv message and the peer it came from together // invMsg packages a bitcoin inv message and the peer it came from together
// so the block handler has access to that information. // so the block handler has access to that information.
type invMsg struct { type invMsg struct {
inv *btcwire.MsgInv inv *wire.MsgInv
peer *peer peer *peer
} }
// blockMsg packages a bitcoin block message and the peer it came from together // blockMsg packages a bitcoin block message and the peer it came from together
// so the block handler has access to that information. // so the block handler has access to that information.
type headersMsg struct { type headersMsg struct {
headers *btcwire.MsgHeaders headers *wire.MsgHeaders
peer *peer peer *peer
} }
@ -129,7 +129,7 @@ type isCurrentMsg struct {
// between checkpoints. // between checkpoints.
type headerNode struct { type headerNode struct {
height int64 height int64
sha *btcwire.ShaHash sha *wire.ShaHash
} }
// chainState tracks the state of the best chain as blocks are inserted. This // chainState tracks the state of the best chain as blocks are inserted. This
@ -140,7 +140,7 @@ type headerNode struct {
// is inserted and protecting it with a mutex. // is inserted and protecting it with a mutex.
type chainState struct { type chainState struct {
sync.Mutex sync.Mutex
newestHash *btcwire.ShaHash newestHash *wire.ShaHash
newestHeight int64 newestHeight int64
pastMedianTime time.Time pastMedianTime time.Time
pastMedianTimeErr error pastMedianTimeErr error
@ -150,7 +150,7 @@ type chainState struct {
// chain. // chain.
// //
// This function is safe for concurrent access. // This function is safe for concurrent access.
func (c *chainState) Best() (*btcwire.ShaHash, int64) { func (c *chainState) Best() (*wire.ShaHash, int64) {
c.Lock() c.Lock()
defer c.Unlock() defer c.Unlock()
@ -164,8 +164,8 @@ type blockManager struct {
started int32 started int32
shutdown int32 shutdown int32
blockChain *blockchain.BlockChain blockChain *blockchain.BlockChain
requestedTxns map[btcwire.ShaHash]struct{} requestedTxns map[wire.ShaHash]struct{}
requestedBlocks map[btcwire.ShaHash]struct{} requestedBlocks map[wire.ShaHash]struct{}
receivedLogBlocks int64 receivedLogBlocks int64
receivedLogTx int64 receivedLogTx int64
lastBlockLogTime time.Time lastBlockLogTime time.Time
@ -185,7 +185,7 @@ type blockManager struct {
// resetHeaderState sets the headers-first mode state to values appropriate for // resetHeaderState sets the headers-first mode state to values appropriate for
// syncing from a new peer. // syncing from a new peer.
func (b *blockManager) resetHeaderState(newestHash *btcwire.ShaHash, newestHeight int64) { func (b *blockManager) resetHeaderState(newestHash *wire.ShaHash, newestHeight int64) {
b.headersFirstMode = false b.headersFirstMode = false
b.headerList.Init() b.headerList.Init()
b.startHeader = nil b.startHeader = nil
@ -203,7 +203,7 @@ func (b *blockManager) resetHeaderState(newestHash *btcwire.ShaHash, newestHeigh
// This allows fast access to chain information since btcchain is currently not // This allows fast access to chain information since btcchain is currently not
// safe for concurrent access and the block manager is typically quite busy // safe for concurrent access and the block manager is typically quite busy
// processing block and inventory. // processing block and inventory.
func (b *blockManager) updateChainState(newestHash *btcwire.ShaHash, newestHeight int64) { func (b *blockManager) updateChainState(newestHash *wire.ShaHash, newestHeight int64) {
b.chainState.Lock() b.chainState.Lock()
defer b.chainState.Unlock() defer b.chainState.Unlock()
@ -354,7 +354,7 @@ func (b *blockManager) isSyncCandidate(p *peer) bool {
} }
} else { } else {
// The peer is not a candidate for sync if it's not a full node. // The peer is not a candidate for sync if it's not a full node.
if p.services&btcwire.SFNodeNetwork != btcwire.SFNodeNetwork { if p.services&wire.SFNodeNetwork != wire.SFNodeNetwork {
return false return false
} }
} }
@ -510,7 +510,7 @@ func (b *blockManager) handleTxMsg(tmsg *txMsg) {
// Convert the error into an appropriate reject message and // Convert the error into an appropriate reject message and
// send it. // send it.
code, reason := errToRejectErr(err) code, reason := errToRejectErr(err)
tmsg.peer.PushRejectMsg(btcwire.CmdBlock, code, reason, txHash, tmsg.peer.PushRejectMsg(wire.CmdBlock, code, reason, txHash,
false) false)
return return
} }
@ -609,7 +609,7 @@ func (b *blockManager) handleBlockMsg(bmsg *blockMsg) {
// Convert the error into an appropriate reject message and // Convert the error into an appropriate reject message and
// send it. // send it.
code, reason := errToRejectErr(err) code, reason := errToRejectErr(err)
bmsg.peer.PushRejectMsg(btcwire.CmdBlock, code, reason, bmsg.peer.PushRejectMsg(wire.CmdBlock, code, reason,
blockSha, false) blockSha, false)
return return
} }
@ -672,7 +672,7 @@ func (b *blockManager) handleBlockMsg(bmsg *blockMsg) {
prevHash := b.nextCheckpoint.Hash prevHash := b.nextCheckpoint.Hash
b.nextCheckpoint = b.findNextHeaderCheckpoint(prevHeight) b.nextCheckpoint = b.findNextHeaderCheckpoint(prevHeight)
if b.nextCheckpoint != nil { if b.nextCheckpoint != nil {
locator := blockchain.BlockLocator([]*btcwire.ShaHash{prevHash}) locator := blockchain.BlockLocator([]*wire.ShaHash{prevHash})
err := bmsg.peer.PushGetHeadersMsg(locator, b.nextCheckpoint.Hash) err := bmsg.peer.PushGetHeadersMsg(locator, b.nextCheckpoint.Hash)
if err != nil { if err != nil {
bmgrLog.Warnf("Failed to send getheaders message to "+ bmgrLog.Warnf("Failed to send getheaders message to "+
@ -691,7 +691,7 @@ func (b *blockManager) handleBlockMsg(bmsg *blockMsg) {
b.headersFirstMode = false b.headersFirstMode = false
b.headerList.Init() b.headerList.Init()
bmgrLog.Infof("Reached the final checkpoint -- switching to normal mode") bmgrLog.Infof("Reached the final checkpoint -- switching to normal mode")
locator := blockchain.BlockLocator([]*btcwire.ShaHash{blockSha}) locator := blockchain.BlockLocator([]*wire.ShaHash{blockSha})
err = bmsg.peer.PushGetBlocksMsg(locator, &zeroHash) err = bmsg.peer.PushGetBlocksMsg(locator, &zeroHash)
if err != nil { if err != nil {
bmgrLog.Warnf("Failed to send getblocks message to peer %s: %v", bmgrLog.Warnf("Failed to send getblocks message to peer %s: %v",
@ -710,9 +710,9 @@ func (b *blockManager) fetchHeaderBlocks() {
} }
// Build up a getdata request for the list of blocks the headers // Build up a getdata request for the list of blocks the headers
// describe. The size hint will be limited to btcwire.MaxInvPerMsg by // describe. The size hint will be limited to wire.MaxInvPerMsg by
// the function, so no need to double check it here. // the function, so no need to double check it here.
gdmsg := btcwire.NewMsgGetDataSizeHint(uint(b.headerList.Len())) gdmsg := wire.NewMsgGetDataSizeHint(uint(b.headerList.Len()))
numRequested := 0 numRequested := 0
for e := b.startHeader; e != nil; e = e.Next() { for e := b.startHeader; e != nil; e = e.Next() {
node, ok := e.Value.(*headerNode) node, ok := e.Value.(*headerNode)
@ -721,7 +721,7 @@ func (b *blockManager) fetchHeaderBlocks() {
continue continue
} }
iv := btcwire.NewInvVect(btcwire.InvTypeBlock, node.sha) iv := wire.NewInvVect(wire.InvTypeBlock, node.sha)
haveInv, err := b.haveInventory(iv) haveInv, err := b.haveInventory(iv)
if err != nil { if err != nil {
bmgrLog.Warnf("Unexpected failure when checking for "+ bmgrLog.Warnf("Unexpected failure when checking for "+
@ -735,7 +735,7 @@ func (b *blockManager) fetchHeaderBlocks() {
numRequested++ numRequested++
} }
b.startHeader = e.Next() b.startHeader = e.Next()
if numRequested >= btcwire.MaxInvPerMsg { if numRequested >= wire.MaxInvPerMsg {
break break
} }
} }
@ -764,7 +764,7 @@ func (b *blockManager) handleHeadersMsg(hmsg *headersMsg) {
// Process all of the received headers ensuring each one connects to the // Process all of the received headers ensuring each one connects to the
// previous and that checkpoints match. // previous and that checkpoints match.
receivedCheckpoint := false receivedCheckpoint := false
var finalHash *btcwire.ShaHash var finalHash *wire.ShaHash
for _, blockHeader := range msg.Headers { for _, blockHeader := range msg.Headers {
blockHash, err := blockHeader.BlockSha() blockHash, err := blockHeader.BlockSha()
if err != nil { if err != nil {
@ -842,7 +842,7 @@ func (b *blockManager) handleHeadersMsg(hmsg *headersMsg) {
// This header is not a checkpoint, so request the next batch of // This header is not a checkpoint, so request the next batch of
// headers starting from the latest known header and ending with the // headers starting from the latest known header and ending with the
// next checkpoint. // next checkpoint.
locator := blockchain.BlockLocator([]*btcwire.ShaHash{finalHash}) locator := blockchain.BlockLocator([]*wire.ShaHash{finalHash})
err := hmsg.peer.PushGetHeadersMsg(locator, b.nextCheckpoint.Hash) err := hmsg.peer.PushGetHeadersMsg(locator, b.nextCheckpoint.Hash)
if err != nil { if err != nil {
bmgrLog.Warnf("Failed to send getheaders message to "+ bmgrLog.Warnf("Failed to send getheaders message to "+
@ -856,14 +856,14 @@ func (b *blockManager) handleHeadersMsg(hmsg *headersMsg) {
// inventory can be when it is in different states such as blocks that are part // inventory can be when it is in different states such as blocks that are part
// of the main chain, on a side chain, in the orphan pool, and transactions that // of the main chain, on a side chain, in the orphan pool, and transactions that
// are in the memory pool (either the main pool or orphan pool). // are in the memory pool (either the main pool or orphan pool).
func (b *blockManager) haveInventory(invVect *btcwire.InvVect) (bool, error) { func (b *blockManager) haveInventory(invVect *wire.InvVect) (bool, error) {
switch invVect.Type { switch invVect.Type {
case btcwire.InvTypeBlock: case wire.InvTypeBlock:
// Ask chain if the block is known to it in any form (main // Ask chain if the block is known to it in any form (main
// chain, side chain, or orphan). // chain, side chain, or orphan).
return b.blockChain.HaveBlock(&invVect.Hash) return b.blockChain.HaveBlock(&invVect.Hash)
case btcwire.InvTypeTx: case wire.InvTypeTx:
// Ask the transaction memory pool if the transaction is known // Ask the transaction memory pool if the transaction is known
// to it in any form (main pool or orphan). // to it in any form (main pool or orphan).
if b.server.txMemPool.HaveTransaction(&invVect.Hash) { if b.server.txMemPool.HaveTransaction(&invVect.Hash) {
@ -894,7 +894,7 @@ func (b *blockManager) handleInvMsg(imsg *invMsg) {
lastBlock := -1 lastBlock := -1
invVects := imsg.inv.InvList invVects := imsg.inv.InvList
for i := len(invVects) - 1; i >= 0; i-- { for i := len(invVects) - 1; i >= 0; i-- {
if invVects[i].Type == btcwire.InvTypeBlock { if invVects[i].Type == wire.InvTypeBlock {
lastBlock = i lastBlock = i
break break
} }
@ -907,7 +907,7 @@ func (b *blockManager) handleInvMsg(imsg *invMsg) {
chain := b.blockChain chain := b.blockChain
for i, iv := range invVects { for i, iv := range invVects {
// Ignore unsupported inventory types. // Ignore unsupported inventory types.
if iv.Type != btcwire.InvTypeBlock && iv.Type != btcwire.InvTypeTx { if iv.Type != wire.InvTypeBlock && iv.Type != wire.InvTypeTx {
continue continue
} }
@ -934,7 +934,7 @@ func (b *blockManager) handleInvMsg(imsg *invMsg) {
continue continue
} }
if iv.Type == btcwire.InvTypeBlock { if iv.Type == wire.InvTypeBlock {
// The block is an orphan block that we already have. // The block is an orphan block that we already have.
// When the existing orphan was processed, it requested // When the existing orphan was processed, it requested
// the missing parent blocks. When this scenario // the missing parent blocks. When this scenario
@ -978,7 +978,7 @@ func (b *blockManager) handleInvMsg(imsg *invMsg) {
// Request as much as possible at once. Anything that won't fit into // Request as much as possible at once. Anything that won't fit into
// the request will be requested on the next inv message. // the request will be requested on the next inv message.
numRequested := 0 numRequested := 0
gdmsg := btcwire.NewMsgGetData() gdmsg := wire.NewMsgGetData()
requestQueue := imsg.peer.requestQueue requestQueue := imsg.peer.requestQueue
for len(requestQueue) != 0 { for len(requestQueue) != 0 {
iv := requestQueue[0] iv := requestQueue[0]
@ -986,7 +986,7 @@ func (b *blockManager) handleInvMsg(imsg *invMsg) {
requestQueue = requestQueue[1:] requestQueue = requestQueue[1:]
switch iv.Type { switch iv.Type {
case btcwire.InvTypeBlock: case wire.InvTypeBlock:
// Request the block if there is not already a pending // Request the block if there is not already a pending
// request. // request.
if _, exists := b.requestedBlocks[iv.Hash]; !exists { if _, exists := b.requestedBlocks[iv.Hash]; !exists {
@ -996,7 +996,7 @@ func (b *blockManager) handleInvMsg(imsg *invMsg) {
numRequested++ numRequested++
} }
case btcwire.InvTypeTx: case wire.InvTypeTx:
// Request the transaction if there is not already a // Request the transaction if there is not already a
// pending request. // pending request.
if _, exists := b.requestedTxns[iv.Hash]; !exists { if _, exists := b.requestedTxns[iv.Hash]; !exists {
@ -1007,7 +1007,7 @@ func (b *blockManager) handleInvMsg(imsg *invMsg) {
} }
} }
if numRequested >= btcwire.MaxInvPerMsg { if numRequested >= wire.MaxInvPerMsg {
break break
} }
} }
@ -1130,7 +1130,7 @@ func (b *blockManager) handleNotifyMsg(notification *blockchain.Notification) {
hash, _ := block.Sha() hash, _ := block.Sha()
// Generate the inventory vector and relay it. // Generate the inventory vector and relay it.
iv := btcwire.NewInvVect(btcwire.InvTypeBlock, hash) iv := wire.NewInvVect(wire.InvTypeBlock, hash)
b.server.RelayInventory(iv, nil) b.server.RelayInventory(iv, nil)
// A block has been connected to the main block chain. // A block has been connected to the main block chain.
@ -1159,7 +1159,7 @@ func (b *blockManager) handleNotifyMsg(notification *blockchain.Notification) {
// all the transactions (except the coinbase) as no // all the transactions (except the coinbase) as no
// longer needing rebroadcasting. // longer needing rebroadcasting.
for _, tx := range block.Transactions()[1:] { for _, tx := range block.Transactions()[1:] {
iv := btcwire.NewInvVect(btcwire.InvTypeTx, tx.Sha()) iv := wire.NewInvVect(wire.InvTypeTx, tx.Sha())
b.server.RemoveRebroadcastInventory(iv) b.server.RemoveRebroadcastInventory(iv)
} }
@ -1229,7 +1229,7 @@ func (b *blockManager) QueueBlock(block *btcutil.Block, p *peer) {
} }
// QueueInv adds the passed inv message and peer to the block handling queue. // QueueInv adds the passed inv message and peer to the block handling queue.
func (b *blockManager) QueueInv(inv *btcwire.MsgInv, p *peer) { func (b *blockManager) QueueInv(inv *wire.MsgInv, p *peer) {
// No channel handling here because peers do not need to block on inv // No channel handling here because peers do not need to block on inv
// messages. // messages.
if atomic.LoadInt32(&b.shutdown) != 0 { if atomic.LoadInt32(&b.shutdown) != 0 {
@ -1241,7 +1241,7 @@ func (b *blockManager) QueueInv(inv *btcwire.MsgInv, p *peer) {
// QueueHeaders adds the passed headers message and peer to the block handling // QueueHeaders adds the passed headers message and peer to the block handling
// queue. // queue.
func (b *blockManager) QueueHeaders(headers *btcwire.MsgHeaders, p *peer) { func (b *blockManager) QueueHeaders(headers *wire.MsgHeaders, p *peer) {
// No channel handling here because peers do not need to block on // No channel handling here because peers do not need to block on
// headers messages. // headers messages.
if atomic.LoadInt32(&b.shutdown) != 0 { if atomic.LoadInt32(&b.shutdown) != 0 {
@ -1345,8 +1345,8 @@ func newBlockManager(s *server) (*blockManager, error) {
bm := blockManager{ bm := blockManager{
server: s, server: s,
requestedTxns: make(map[btcwire.ShaHash]struct{}), requestedTxns: make(map[wire.ShaHash]struct{}),
requestedBlocks: make(map[btcwire.ShaHash]struct{}), requestedBlocks: make(map[wire.ShaHash]struct{}),
lastBlockLogTime: time.Now(), lastBlockLogTime: time.Now(),
msgChan: make(chan interface{}, cfg.MaxPeers*3), msgChan: make(chan interface{}, cfg.MaxPeers*3),
headerList: list.New(), headerList: list.New(),

View file

@ -11,9 +11,9 @@ import (
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
_ "github.com/btcsuite/btcd/database/ldb" _ "github.com/btcsuite/btcd/database/ldb"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcnet" "github.com/btcsuite/btcnet"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
flags "github.com/btcsuite/go-flags" flags "github.com/btcsuite/go-flags"
) )
@ -68,14 +68,14 @@ func validDbType(dbType string) bool {
// time of writing, btcd currently places blocks for testnet version 3 in the // time of writing, btcd currently places blocks for testnet version 3 in the
// data and log directory "testnet", which does not match the Name field of the // data and log directory "testnet", which does not match the Name field of the
// btcnet parameters. This function can be used to override this directory name // btcnet parameters. This function can be used to override this directory name
// as "testnet" when the passed active network matches btcwire.TestNet3. // as "testnet" when the passed active network matches wire.TestNet3.
// //
// A proper upgrade to move the data and log directories for this network to // A proper upgrade to move the data and log directories for this network to
// "testnet3" is planned for the future, at which point this function can be // "testnet3" is planned for the future, at which point this function can be
// removed and the network parameter's name used instead. // removed and the network parameter's name used instead.
func netName(netParams *btcnet.Params) string { func netName(netParams *btcnet.Params) string {
switch netParams.Net { switch netParams.Net {
case btcwire.TestNet3: case wire.TestNet3:
return "testnet" return "testnet"
default: default:
return netParams.Name return netParams.Name

View file

@ -14,11 +14,11 @@ import (
"github.com/btcsuite/btcd/blockchain" "github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
_ "github.com/btcsuite/btcd/database/ldb" _ "github.com/btcsuite/btcd/database/ldb"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
) )
var zeroHash = btcwire.ShaHash{} var zeroHash = wire.ShaHash{}
// importResults houses the stats and result as an import operation. // importResults houses the stats and result as an import operation.
type importResults struct { type importResults struct {
@ -72,10 +72,10 @@ func (bi *blockImporter) readBlock() ([]byte, error) {
if err := binary.Read(bi.r, binary.LittleEndian, &blockLen); err != nil { if err := binary.Read(bi.r, binary.LittleEndian, &blockLen); err != nil {
return nil, err return nil, err
} }
if blockLen > btcwire.MaxBlockPayload { if blockLen > wire.MaxBlockPayload {
return nil, fmt.Errorf("block payload of %d bytes is larger "+ return nil, fmt.Errorf("block payload of %d bytes is larger "+
"than the max allowed %d bytes", blockLen, "than the max allowed %d bytes", blockLen,
btcwire.MaxBlockPayload) wire.MaxBlockPayload)
} }
serializedBlock := make([]byte, blockLen) serializedBlock := make([]byte, blockLen)

View file

@ -13,10 +13,10 @@ import (
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
_ "github.com/btcsuite/btcd/database/ldb" _ "github.com/btcsuite/btcd/database/ldb"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btclog" "github.com/btcsuite/btclog"
"github.com/btcsuite/btcnet" "github.com/btcsuite/btcnet"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
flags "github.com/btcsuite/go-flags" flags "github.com/btcsuite/go-flags"
) )
@ -45,14 +45,14 @@ const (
// time of writing, btcd currently places blocks for testnet version 3 in the // time of writing, btcd currently places blocks for testnet version 3 in the
// data and log directory "testnet", which does not match the Name field of the // data and log directory "testnet", which does not match the Name field of the
// btcnet parameters. This function can be used to override this directory name // btcnet parameters. This function can be used to override this directory name
// as "testnet" when the passed active network matches btcwire.TestNet3. // as "testnet" when the passed active network matches wire.TestNet3.
// //
// A proper upgrade to move the data and log directories for this network to // A proper upgrade to move the data and log directories for this network to
// "testnet3" is planned for the future, at which point this function can be // "testnet3" is planned for the future, at which point this function can be
// removed and the network parameter's name used instead. // removed and the network parameter's name used instead.
func netName(netParams *btcnet.Params) string { func netName(netParams *btcnet.Params) string {
switch netParams.Net { switch netParams.Net {
case btcwire.TestNet3: case wire.TestNet3:
return "testnet" return "testnet"
default: default:
return netParams.Name return netParams.Name
@ -137,11 +137,11 @@ func main() {
} }
func getSha(db database.Db, str string) (btcwire.ShaHash, error) { func getSha(db database.Db, str string) (wire.ShaHash, error) {
argtype, idx, sha, err := parsesha(str) argtype, idx, sha, err := parsesha(str)
if err != nil { if err != nil {
log.Warnf("unable to decode [%v] %v", str, err) log.Warnf("unable to decode [%v] %v", str, err)
return btcwire.ShaHash{}, err return wire.ShaHash{}, err
} }
switch argtype { switch argtype {
@ -150,7 +150,7 @@ func getSha(db database.Db, str string) (btcwire.ShaHash, error) {
case argHeight: case argHeight:
sha, err = db.FetchBlockShaByHeight(idx) sha, err = db.FetchBlockShaByHeight(idx)
if err != nil { if err != nil {
return btcwire.ShaHash{}, err return wire.ShaHash{}, err
} }
} }
if sha == nil { if sha == nil {
@ -167,8 +167,8 @@ var errBadShaPrefix = errors.New("invalid prefix")
var errBadShaLen = errors.New("invalid len") var errBadShaLen = errors.New("invalid len")
var errBadShaChar = errors.New("invalid character") var errBadShaChar = errors.New("invalid character")
func parsesha(argstr string) (argtype int, height int64, psha *btcwire.ShaHash, err error) { func parsesha(argstr string) (argtype int, height int64, psha *wire.ShaHash, err error) {
var sha btcwire.ShaHash var sha wire.ShaHash
var hashbuf string var hashbuf string

View file

@ -11,9 +11,9 @@ import (
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
_ "github.com/btcsuite/btcd/database/ldb" _ "github.com/btcsuite/btcd/database/ldb"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcnet" "github.com/btcsuite/btcnet"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
flags "github.com/btcsuite/go-flags" flags "github.com/btcsuite/go-flags"
) )
@ -59,14 +59,14 @@ func validDbType(dbType string) bool {
// time of writing, btcd currently places blocks for testnet version 3 in the // time of writing, btcd currently places blocks for testnet version 3 in the
// data and log directory "testnet", which does not match the Name field of the // data and log directory "testnet", which does not match the Name field of the
// btcnet parameters. This function can be used to override this directory name // btcnet parameters. This function can be used to override this directory name
// as "testnet" when the passed active network matches btcwire.TestNet3. // as "testnet" when the passed active network matches wire.TestNet3.
// //
// A proper upgrade to move the data and log directories for this network to // A proper upgrade to move the data and log directories for this network to
// "testnet3" is planned for the future, at which point this function can be // "testnet3" is planned for the future, at which point this function can be
// removed and the network parameter's name used instead. // removed and the network parameter's name used instead.
func netName(netParams *btcnet.Params) string { func netName(netParams *btcnet.Params) string {
switch netParams.Net { switch netParams.Net {
case btcwire.TestNet3: case wire.TestNet3:
return "testnet" return "testnet"
default: default:
return netParams.Name return netParams.Name

View file

@ -12,8 +12,8 @@ import (
"github.com/btcsuite/btcd/blockchain" "github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
_ "github.com/btcsuite/btcd/database/ldb" _ "github.com/btcsuite/btcd/database/ldb"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcnet" "github.com/btcsuite/btcnet"
"github.com/btcsuite/btcwire"
) )
const blockDbNamePrefix = "blocks" const blockDbNamePrefix = "blocks"
@ -44,7 +44,7 @@ func loadBlockDB() (database.Db, error) {
// candidates at the last checkpoint that is already hard coded into btcchain // candidates at the last checkpoint that is already hard coded into btcchain
// since there is no point in finding candidates before already existing // since there is no point in finding candidates before already existing
// checkpoints. // checkpoints.
func findCandidates(db database.Db, latestHash *btcwire.ShaHash) ([]*btcnet.Checkpoint, error) { func findCandidates(db database.Db, latestHash *wire.ShaHash) ([]*btcnet.Checkpoint, error) {
// Start with the latest block of the main chain. // Start with the latest block of the main chain.
block, err := db.FetchBlockBySha(latestHash) block, err := db.FetchBlockBySha(latestHash)
if err != nil { if err != nil {

View file

@ -19,8 +19,8 @@ import (
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
_ "github.com/btcsuite/btcd/database/ldb" _ "github.com/btcsuite/btcd/database/ldb"
_ "github.com/btcsuite/btcd/database/memdb" _ "github.com/btcsuite/btcd/database/memdb"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
flags "github.com/btcsuite/go-flags" flags "github.com/btcsuite/go-flags"
"github.com/btcsuite/go-socks/socks" "github.com/btcsuite/go-socks/socks"
) )
@ -41,7 +41,7 @@ const (
defaultBlockMinSize = 0 defaultBlockMinSize = 0
defaultBlockMaxSize = 750000 defaultBlockMaxSize = 750000
blockMaxSizeMin = 1000 blockMaxSizeMin = 1000
blockMaxSizeMax = btcwire.MaxBlockPayload - 1000 blockMaxSizeMax = wire.MaxBlockPayload - 1000
defaultBlockPrioritySize = 50000 defaultBlockPrioritySize = 50000
defaultGenerate = false defaultGenerate = false
) )

View file

@ -12,8 +12,8 @@ import (
"time" "time"
"github.com/btcsuite/btcd/blockchain" "github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
) )
const ( const (
@ -164,12 +164,12 @@ func (m *CPUMiner) submitBlock(block *btcutil.Block) bool {
// This function will return early with false when conditions that trigger a // This function will return early with false when conditions that trigger a
// stale block such as a new block showing up or periodically when there are // stale block such as a new block showing up or periodically when there are
// new transactions and enough time has elapsed without finding a solution. // new transactions and enough time has elapsed without finding a solution.
func (m *CPUMiner) solveBlock(msgBlock *btcwire.MsgBlock, blockHeight int64, func (m *CPUMiner) solveBlock(msgBlock *wire.MsgBlock, blockHeight int64,
ticker *time.Ticker, quit chan struct{}) bool { ticker *time.Ticker, quit chan struct{}) bool {
// Choose a random extra nonce offset for this block template and // Choose a random extra nonce offset for this block template and
// worker. // worker.
enOffset, err := btcwire.RandomUint64() enOffset, err := wire.RandomUint64()
if err != nil { if err != nil {
minrLog.Errorf("Unexpected error while generating random "+ minrLog.Errorf("Unexpected error while generating random "+
"extra nonce offset: %v", err) "extra nonce offset: %v", err)

View file

@ -17,14 +17,14 @@ import (
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
_ "github.com/btcsuite/btcd/database/ldb" _ "github.com/btcsuite/btcd/database/ldb"
_ "github.com/btcsuite/btcd/database/memdb" _ "github.com/btcsuite/btcd/database/memdb"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcnet" "github.com/btcsuite/btcnet"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
) )
var ( var (
// network is the expected bitcoin network in the test block data. // network is the expected bitcoin network in the test block data.
network = btcwire.MainNet network = wire.MainNet
// savedBlocks is used to store blocks loaded from the blockDataFile // savedBlocks is used to store blocks loaded from the blockDataFile
// so multiple invocations to loadBlocks from the various test functions // so multiple invocations to loadBlocks from the various test functions
@ -36,7 +36,7 @@ var (
blockDataFile = filepath.Join("testdata", "blocks1-256.bz2") blockDataFile = filepath.Join("testdata", "blocks1-256.bz2")
) )
var zeroHash = btcwire.ShaHash{} var zeroHash = wire.ShaHash{}
// testDbRoot is the root directory used to create all test databases. // testDbRoot is the root directory used to create all test databases.
const testDbRoot = "testdbs" const testDbRoot = "testdbs"

View file

@ -7,8 +7,8 @@ package database
import ( import (
"errors" "errors"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
"golang.org/x/crypto/ripemd160" "golang.org/x/crypto/ripemd160"
) )
@ -42,40 +42,40 @@ type Db interface {
// the given block. It terminates any existing transaction and performs // the given block. It terminates any existing transaction and performs
// its operations in an atomic transaction which is commited before // its operations in an atomic transaction which is commited before
// the function returns. // the function returns.
DropAfterBlockBySha(*btcwire.ShaHash) (err error) DropAfterBlockBySha(*wire.ShaHash) (err error)
// ExistsSha returns whether or not the given block hash is present in // ExistsSha returns whether or not the given block hash is present in
// the database. // the database.
ExistsSha(sha *btcwire.ShaHash) (exists bool, err error) ExistsSha(sha *wire.ShaHash) (exists bool, err error)
// FetchBlockBySha returns a btcutil Block. The implementation may // FetchBlockBySha returns a btcutil Block. The implementation may
// cache the underlying data if desired. // cache the underlying data if desired.
FetchBlockBySha(sha *btcwire.ShaHash) (blk *btcutil.Block, err error) FetchBlockBySha(sha *wire.ShaHash) (blk *btcutil.Block, err error)
// FetchBlockHeightBySha returns the block height for the given hash. // FetchBlockHeightBySha returns the block height for the given hash.
FetchBlockHeightBySha(sha *btcwire.ShaHash) (height int64, err error) FetchBlockHeightBySha(sha *wire.ShaHash) (height int64, err error)
// FetchBlockHeaderBySha returns a btcwire.BlockHeader for the given // FetchBlockHeaderBySha returns a wire.BlockHeader for the given
// sha. The implementation may cache the underlying data if desired. // sha. The implementation may cache the underlying data if desired.
FetchBlockHeaderBySha(sha *btcwire.ShaHash) (bh *btcwire.BlockHeader, err error) FetchBlockHeaderBySha(sha *wire.ShaHash) (bh *wire.BlockHeader, err error)
// FetchBlockShaByHeight returns a block hash based on its height in the // FetchBlockShaByHeight returns a block hash based on its height in the
// block chain. // block chain.
FetchBlockShaByHeight(height int64) (sha *btcwire.ShaHash, err error) FetchBlockShaByHeight(height int64) (sha *wire.ShaHash, err error)
// FetchHeightRange looks up a range of blocks by the start and ending // FetchHeightRange looks up a range of blocks by the start and ending
// heights. Fetch is inclusive of the start height and exclusive of the // heights. Fetch is inclusive of the start height and exclusive of the
// ending height. To fetch all hashes from the start height until no // ending height. To fetch all hashes from the start height until no
// more are present, use the special id `AllShas'. // more are present, use the special id `AllShas'.
FetchHeightRange(startHeight, endHeight int64) (rshalist []btcwire.ShaHash, err error) FetchHeightRange(startHeight, endHeight int64) (rshalist []wire.ShaHash, err error)
// ExistsTxSha returns whether or not the given tx hash is present in // ExistsTxSha returns whether or not the given tx hash is present in
// the database // the database
ExistsTxSha(sha *btcwire.ShaHash) (exists bool, err error) ExistsTxSha(sha *wire.ShaHash) (exists bool, err error)
// FetchTxBySha returns some data for the given transaction hash. The // FetchTxBySha returns some data for the given transaction hash. The
// implementation may cache the underlying data if desired. // implementation may cache the underlying data if desired.
FetchTxBySha(txsha *btcwire.ShaHash) ([]*TxListReply, error) FetchTxBySha(txsha *wire.ShaHash) ([]*TxListReply, error)
// FetchTxByShaList returns a TxListReply given an array of transaction // FetchTxByShaList returns a TxListReply given an array of transaction
// hashes. The implementation may cache the underlying data if desired. // hashes. The implementation may cache the underlying data if desired.
@ -86,7 +86,7 @@ type Db interface {
// return at least one TxListReply instance for each requested // return at least one TxListReply instance for each requested
// transaction. Each TxListReply instance then contains an Err field // transaction. Each TxListReply instance then contains an Err field
// which can be used to detect errors. // which can be used to detect errors.
FetchTxByShaList(txShaList []*btcwire.ShaHash) []*TxListReply FetchTxByShaList(txShaList []*wire.ShaHash) []*TxListReply
// FetchUnSpentTxByShaList returns a TxListReply given an array of // FetchUnSpentTxByShaList returns a TxListReply given an array of
// transaction hashes. The implementation may cache the underlying // transaction hashes. The implementation may cache the underlying
@ -97,7 +97,7 @@ type Db interface {
// return at least one TxListReply instance for each requested // return at least one TxListReply instance for each requested
// transaction. Each TxListReply instance then contains an Err field // transaction. Each TxListReply instance then contains an Err field
// which can be used to detect errors. // which can be used to detect errors.
FetchUnSpentTxByShaList(txShaList []*btcwire.ShaHash) []*TxListReply FetchUnSpentTxByShaList(txShaList []*wire.ShaHash) []*TxListReply
// InsertBlock inserts raw block and transaction data from a block // InsertBlock inserts raw block and transaction data from a block
// into the database. The first block inserted into the database // into the database. The first block inserted into the database
@ -109,13 +109,13 @@ type Db interface {
// block of the block chain. It will return the zero hash, -1 for // block of the block chain. It will return the zero hash, -1 for
// the block height, and no error (nil) if there are not any blocks in // the block height, and no error (nil) if there are not any blocks in
// the database yet. // the database yet.
NewestSha() (sha *btcwire.ShaHash, height int64, err error) NewestSha() (sha *wire.ShaHash, height int64, err error)
// FetchAddrIndexTip returns the hash and block height of the most recent // FetchAddrIndexTip returns the hash and block height of the most recent
// block which has had its address index populated. It will return // block which has had its address index populated. It will return
// ErrAddrIndexDoesNotExist along with a zero hash, and -1 if the // ErrAddrIndexDoesNotExist along with a zero hash, and -1 if the
// addrindex hasn't yet been built up. // addrindex hasn't yet been built up.
FetchAddrIndexTip() (sha *btcwire.ShaHash, height int64, err error) FetchAddrIndexTip() (sha *wire.ShaHash, height int64, err error)
// UpdateAddrIndexForBlock updates the stored addrindex with passed // UpdateAddrIndexForBlock updates the stored addrindex with passed
// index information for a particular block height. Additionally, it // index information for a particular block height. Additionally, it
@ -124,7 +124,7 @@ type Db interface {
// transaction which is commited before the function returns. // transaction which is commited before the function returns.
// Addresses are indexed by the raw bytes of their base58 decoded // Addresses are indexed by the raw bytes of their base58 decoded
// hash160. // hash160.
UpdateAddrIndexForBlock(blkSha *btcwire.ShaHash, height int64, UpdateAddrIndexForBlock(blkSha *wire.ShaHash, height int64,
addrIndex BlockAddrIndex) error addrIndex BlockAddrIndex) error
// FetchTxsForAddr looks up and returns all transactions which either // FetchTxsForAddr looks up and returns all transactions which either
@ -159,9 +159,9 @@ type DriverDB struct {
// TxListReply is used to return individual transaction information when // TxListReply is used to return individual transaction information when
// data about multiple transactions is requested in a single call. // data about multiple transactions is requested in a single call.
type TxListReply struct { type TxListReply struct {
Sha *btcwire.ShaHash Sha *wire.ShaHash
Tx *btcwire.MsgTx Tx *wire.MsgTx
BlkSha *btcwire.ShaHash BlkSha *wire.ShaHash
Height int64 Height int64
TxSpent []bool TxSpent []bool
Err error Err error
@ -173,7 +173,7 @@ const AddrIndexKeySize = ripemd160.Size
// BlockAddrIndex represents the indexing structure for addresses. // BlockAddrIndex represents the indexing structure for addresses.
// It maps a hash160 to a list of transaction locations within a block that // It maps a hash160 to a list of transaction locations within a block that
// either pays to or spends from the passed UTXO for the hash160. // either pays to or spends from the passed UTXO for the hash160.
type BlockAddrIndex map[[AddrIndexKeySize]byte][]*btcwire.TxLoc type BlockAddrIndex map[[AddrIndexKeySize]byte][]*wire.TxLoc
// driverList holds all of the registered database backends. // driverList holds all of the registered database backends.
var driverList []DriverDB var driverList []DriverDB

View file

@ -9,8 +9,8 @@ import (
"testing" "testing"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
) )
@ -27,7 +27,7 @@ type testContext struct {
dbType string dbType string
db database.Db db database.Db
blockHeight int64 blockHeight int64
blockHash *btcwire.ShaHash blockHash *wire.ShaHash
block *btcutil.Block block *btcutil.Block
useSpends bool useSpends bool
} }
@ -356,7 +356,7 @@ func testFetchTxByShaListCommon(tc *testContext, includeSpent bool) bool {
} }
transactions := tc.block.Transactions() transactions := tc.block.Transactions()
txHashes := make([]*btcwire.ShaHash, len(transactions)) txHashes := make([]*wire.ShaHash, len(transactions))
for i, tx := range transactions { for i, tx := range transactions {
txHashes[i] = tx.Sha() txHashes[i] = tx.Sha()
} }
@ -620,17 +620,17 @@ func testInterface(t *testing.T, dbType string) {
// TODO(davec): Add tests for the following functions: // TODO(davec): Add tests for the following functions:
/* /*
- Close() - Close()
- DropAfterBlockBySha(*btcwire.ShaHash) (err error) - DropAfterBlockBySha(*wire.ShaHash) (err error)
x ExistsSha(sha *btcwire.ShaHash) (exists bool) x ExistsSha(sha *wire.ShaHash) (exists bool)
x FetchBlockBySha(sha *btcwire.ShaHash) (blk *btcutil.Block, err error) x FetchBlockBySha(sha *wire.ShaHash) (blk *btcutil.Block, err error)
x FetchBlockShaByHeight(height int64) (sha *btcwire.ShaHash, err error) x FetchBlockShaByHeight(height int64) (sha *wire.ShaHash, err error)
- FetchHeightRange(startHeight, endHeight int64) (rshalist []btcwire.ShaHash, err error) - FetchHeightRange(startHeight, endHeight int64) (rshalist []wire.ShaHash, err error)
x ExistsTxSha(sha *btcwire.ShaHash) (exists bool) x ExistsTxSha(sha *wire.ShaHash) (exists bool)
x FetchTxBySha(txsha *btcwire.ShaHash) ([]*TxListReply, error) x FetchTxBySha(txsha *wire.ShaHash) ([]*TxListReply, error)
x FetchTxByShaList(txShaList []*btcwire.ShaHash) []*TxListReply x FetchTxByShaList(txShaList []*wire.ShaHash) []*TxListReply
x FetchUnSpentTxByShaList(txShaList []*btcwire.ShaHash) []*TxListReply x FetchUnSpentTxByShaList(txShaList []*wire.ShaHash) []*TxListReply
x InsertBlock(block *btcutil.Block) (height int64, err error) x InsertBlock(block *btcutil.Block) (height int64, err error)
x NewestSha() (sha *btcwire.ShaHash, height int64, err error) x NewestSha() (sha *wire.ShaHash, height int64, err error)
- RollbackClose() - RollbackClose()
- Sync() - Sync()
*/ */

View file

@ -9,13 +9,13 @@ import (
"encoding/binary" "encoding/binary"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
"github.com/btcsuite/goleveldb/leveldb" "github.com/btcsuite/goleveldb/leveldb"
) )
// FetchBlockBySha - return a btcutil Block // FetchBlockBySha - return a btcutil Block
func (db *LevelDb) FetchBlockBySha(sha *btcwire.ShaHash) (blk *btcutil.Block, err error) { func (db *LevelDb) FetchBlockBySha(sha *wire.ShaHash) (blk *btcutil.Block, err error) {
db.dbLock.Lock() db.dbLock.Lock()
defer db.dbLock.Unlock() defer db.dbLock.Unlock()
return db.fetchBlockBySha(sha) return db.fetchBlockBySha(sha)
@ -23,7 +23,7 @@ func (db *LevelDb) FetchBlockBySha(sha *btcwire.ShaHash) (blk *btcutil.Block, er
// fetchBlockBySha - return a btcutil Block // fetchBlockBySha - return a btcutil Block
// Must be called with db lock held. // Must be called with db lock held.
func (db *LevelDb) fetchBlockBySha(sha *btcwire.ShaHash) (blk *btcutil.Block, err error) { func (db *LevelDb) fetchBlockBySha(sha *wire.ShaHash) (blk *btcutil.Block, err error) {
buf, height, err := db.fetchSha(sha) buf, height, err := db.fetchSha(sha)
if err != nil { if err != nil {
@ -41,7 +41,7 @@ func (db *LevelDb) fetchBlockBySha(sha *btcwire.ShaHash) (blk *btcutil.Block, er
// FetchBlockHeightBySha returns the block height for the given hash. This is // FetchBlockHeightBySha returns the block height for the given hash. This is
// part of the database.Db interface implementation. // part of the database.Db interface implementation.
func (db *LevelDb) FetchBlockHeightBySha(sha *btcwire.ShaHash) (int64, error) { func (db *LevelDb) FetchBlockHeightBySha(sha *wire.ShaHash) (int64, error) {
db.dbLock.Lock() db.dbLock.Lock()
defer db.dbLock.Unlock() defer db.dbLock.Unlock()
@ -49,7 +49,7 @@ func (db *LevelDb) FetchBlockHeightBySha(sha *btcwire.ShaHash) (int64, error) {
} }
// FetchBlockHeaderBySha - return a btcwire ShaHash // FetchBlockHeaderBySha - return a btcwire ShaHash
func (db *LevelDb) FetchBlockHeaderBySha(sha *btcwire.ShaHash) (bh *btcwire.BlockHeader, err error) { func (db *LevelDb) FetchBlockHeaderBySha(sha *wire.ShaHash) (bh *wire.BlockHeader, err error) {
db.dbLock.Lock() db.dbLock.Lock()
defer db.dbLock.Unlock() defer db.dbLock.Unlock()
@ -61,7 +61,7 @@ func (db *LevelDb) FetchBlockHeaderBySha(sha *btcwire.ShaHash) (bh *btcwire.Bloc
// Only deserialize the header portion and ensure the transaction count // Only deserialize the header portion and ensure the transaction count
// is zero since this is a standalone header. // is zero since this is a standalone header.
var blockHeader btcwire.BlockHeader var blockHeader wire.BlockHeader
err = blockHeader.Deserialize(bytes.NewReader(buf)) err = blockHeader.Deserialize(bytes.NewReader(buf))
if err != nil { if err != nil {
return nil, err return nil, err
@ -71,7 +71,7 @@ func (db *LevelDb) FetchBlockHeaderBySha(sha *btcwire.ShaHash) (bh *btcwire.Bloc
return bh, err return bh, err
} }
func (db *LevelDb) getBlkLoc(sha *btcwire.ShaHash) (int64, error) { func (db *LevelDb) getBlkLoc(sha *wire.ShaHash) (int64, error) {
key := shaBlkToKey(sha) key := shaBlkToKey(sha)
data, err := db.lDb.Get(key, db.ro) data, err := db.lDb.Get(key, db.ro)
@ -88,7 +88,7 @@ func (db *LevelDb) getBlkLoc(sha *btcwire.ShaHash) (int64, error) {
return int64(blkHeight), nil return int64(blkHeight), nil
} }
func (db *LevelDb) getBlkByHeight(blkHeight int64) (rsha *btcwire.ShaHash, rbuf []byte, err error) { func (db *LevelDb) getBlkByHeight(blkHeight int64) (rsha *wire.ShaHash, rbuf []byte, err error) {
var blkVal []byte var blkVal []byte
key := int64ToKey(blkHeight) key := int64ToKey(blkHeight)
@ -99,7 +99,7 @@ func (db *LevelDb) getBlkByHeight(blkHeight int64) (rsha *btcwire.ShaHash, rbuf
return // exists ??? return // exists ???
} }
var sha btcwire.ShaHash var sha wire.ShaHash
sha.SetBytes(blkVal[0:32]) sha.SetBytes(blkVal[0:32])
@ -109,7 +109,7 @@ func (db *LevelDb) getBlkByHeight(blkHeight int64) (rsha *btcwire.ShaHash, rbuf
return &sha, blockdata, nil return &sha, blockdata, nil
} }
func (db *LevelDb) getBlk(sha *btcwire.ShaHash) (rblkHeight int64, rbuf []byte, err error) { func (db *LevelDb) getBlk(sha *wire.ShaHash) (rblkHeight int64, rbuf []byte, err error) {
var blkHeight int64 var blkHeight int64
blkHeight, err = db.getBlkLoc(sha) blkHeight, err = db.getBlkLoc(sha)
@ -126,7 +126,7 @@ func (db *LevelDb) getBlk(sha *btcwire.ShaHash) (rblkHeight int64, rbuf []byte,
return blkHeight, buf, nil return blkHeight, buf, nil
} }
func (db *LevelDb) setBlk(sha *btcwire.ShaHash, blkHeight int64, buf []byte) { func (db *LevelDb) setBlk(sha *wire.ShaHash, blkHeight int64, buf []byte) {
// serialize // serialize
var lw [8]byte var lw [8]byte
binary.LittleEndian.PutUint64(lw[0:8], uint64(blkHeight)) binary.LittleEndian.PutUint64(lw[0:8], uint64(blkHeight))
@ -146,7 +146,7 @@ func (db *LevelDb) setBlk(sha *btcwire.ShaHash, blkHeight int64, buf []byte) {
// insertSha stores a block hash and its associated data block with a // insertSha stores a block hash and its associated data block with a
// previous sha of `prevSha'. // previous sha of `prevSha'.
// insertSha shall be called with db lock held // insertSha shall be called with db lock held
func (db *LevelDb) insertBlockData(sha *btcwire.ShaHash, prevSha *btcwire.ShaHash, buf []byte) (int64, error) { func (db *LevelDb) insertBlockData(sha *wire.ShaHash, prevSha *wire.ShaHash, buf []byte) (int64, error) {
oBlkHeight, err := db.getBlkLoc(prevSha) oBlkHeight, err := db.getBlkLoc(prevSha)
if err != nil { if err != nil {
// check current block count // check current block count
@ -175,7 +175,7 @@ func (db *LevelDb) insertBlockData(sha *btcwire.ShaHash, prevSha *btcwire.ShaHas
} }
// fetchSha returns the datablock for the given ShaHash. // fetchSha returns the datablock for the given ShaHash.
func (db *LevelDb) fetchSha(sha *btcwire.ShaHash) (rbuf []byte, func (db *LevelDb) fetchSha(sha *wire.ShaHash) (rbuf []byte,
rblkHeight int64, err error) { rblkHeight int64, err error) {
var blkHeight int64 var blkHeight int64
var buf []byte var buf []byte
@ -190,7 +190,7 @@ func (db *LevelDb) fetchSha(sha *btcwire.ShaHash) (rbuf []byte,
// ExistsSha looks up the given block hash // ExistsSha looks up the given block hash
// returns true if it is present in the database. // returns true if it is present in the database.
func (db *LevelDb) ExistsSha(sha *btcwire.ShaHash) (bool, error) { func (db *LevelDb) ExistsSha(sha *wire.ShaHash) (bool, error) {
db.dbLock.Lock() db.dbLock.Lock()
defer db.dbLock.Unlock() defer db.dbLock.Unlock()
@ -201,7 +201,7 @@ func (db *LevelDb) ExistsSha(sha *btcwire.ShaHash) (bool, error) {
// blkExistsSha looks up the given block hash // blkExistsSha looks up the given block hash
// returns true if it is present in the database. // returns true if it is present in the database.
// CALLED WITH LOCK HELD // CALLED WITH LOCK HELD
func (db *LevelDb) blkExistsSha(sha *btcwire.ShaHash) (bool, error) { func (db *LevelDb) blkExistsSha(sha *wire.ShaHash) (bool, error) {
key := shaBlkToKey(sha) key := shaBlkToKey(sha)
return db.lDb.Has(key, db.ro) return db.lDb.Has(key, db.ro)
@ -209,7 +209,7 @@ func (db *LevelDb) blkExistsSha(sha *btcwire.ShaHash) (bool, error) {
// FetchBlockShaByHeight returns a block hash based on its height in the // FetchBlockShaByHeight returns a block hash based on its height in the
// block chain. // block chain.
func (db *LevelDb) FetchBlockShaByHeight(height int64) (sha *btcwire.ShaHash, err error) { func (db *LevelDb) FetchBlockShaByHeight(height int64) (sha *wire.ShaHash, err error) {
db.dbLock.Lock() db.dbLock.Lock()
defer db.dbLock.Unlock() defer db.dbLock.Unlock()
@ -218,7 +218,7 @@ func (db *LevelDb) FetchBlockShaByHeight(height int64) (sha *btcwire.ShaHash, er
// fetchBlockShaByHeight returns a block hash based on its height in the // fetchBlockShaByHeight returns a block hash based on its height in the
// block chain. // block chain.
func (db *LevelDb) fetchBlockShaByHeight(height int64) (rsha *btcwire.ShaHash, err error) { func (db *LevelDb) fetchBlockShaByHeight(height int64) (rsha *wire.ShaHash, err error) {
key := int64ToKey(height) key := int64ToKey(height)
blkVal, err := db.lDb.Get(key, db.ro) blkVal, err := db.lDb.Get(key, db.ro)
@ -227,7 +227,7 @@ func (db *LevelDb) fetchBlockShaByHeight(height int64) (rsha *btcwire.ShaHash, e
return // exists ??? return // exists ???
} }
var sha btcwire.ShaHash var sha wire.ShaHash
sha.SetBytes(blkVal[0:32]) sha.SetBytes(blkVal[0:32])
return &sha, nil return &sha, nil
@ -237,7 +237,7 @@ func (db *LevelDb) fetchBlockShaByHeight(height int64) (rsha *btcwire.ShaHash, e
// heights. Fetch is inclusive of the start height and exclusive of the // heights. Fetch is inclusive of the start height and exclusive of the
// ending height. To fetch all hashes from the start height until no // ending height. To fetch all hashes from the start height until no
// more are present, use the special id `AllShas'. // more are present, use the special id `AllShas'.
func (db *LevelDb) FetchHeightRange(startHeight, endHeight int64) (rshalist []btcwire.ShaHash, err error) { func (db *LevelDb) FetchHeightRange(startHeight, endHeight int64) (rshalist []wire.ShaHash, err error) {
db.dbLock.Lock() db.dbLock.Lock()
defer db.dbLock.Unlock() defer db.dbLock.Unlock()
@ -248,7 +248,7 @@ func (db *LevelDb) FetchHeightRange(startHeight, endHeight int64) (rshalist []bt
endidx = endHeight endidx = endHeight
} }
shalist := make([]btcwire.ShaHash, 0, endidx-startHeight) shalist := make([]wire.ShaHash, 0, endidx-startHeight)
for height := startHeight; height < endidx; height++ { for height := startHeight; height < endidx; height++ {
// TODO(drahn) fix blkFile from height // TODO(drahn) fix blkFile from height
@ -258,7 +258,7 @@ func (db *LevelDb) FetchHeightRange(startHeight, endHeight int64) (rshalist []bt
break break
} }
var sha btcwire.ShaHash var sha wire.ShaHash
sha.SetBytes(blkVal[0:32]) sha.SetBytes(blkVal[0:32])
shalist = append(shalist, sha) shalist = append(shalist, sha)
} }
@ -274,12 +274,12 @@ func (db *LevelDb) FetchHeightRange(startHeight, endHeight int64) (rshalist []bt
// NewestSha returns the hash and block height of the most recent (end) block of // NewestSha returns the hash and block height of the most recent (end) block of
// the block chain. It will return the zero hash, -1 for the block height, and // the block chain. It will return the zero hash, -1 for the block height, and
// no error (nil) if there are not any blocks in the database yet. // no error (nil) if there are not any blocks in the database yet.
func (db *LevelDb) NewestSha() (rsha *btcwire.ShaHash, rblkid int64, err error) { func (db *LevelDb) NewestSha() (rsha *wire.ShaHash, rblkid int64, err error) {
db.dbLock.Lock() db.dbLock.Lock()
defer db.dbLock.Unlock() defer db.dbLock.Unlock()
if db.lastBlkIdx == -1 { if db.lastBlkIdx == -1 {
return &btcwire.ShaHash{}, -1, nil return &wire.ShaHash{}, -1, nil
} }
sha := db.lastBlkSha sha := db.lastBlkSha
@ -291,16 +291,16 @@ func (db *LevelDb) NewestSha() (rsha *btcwire.ShaHash, rblkid int64, err error)
// updated accordingly by functions that modify the state. This function is // updated accordingly by functions that modify the state. This function is
// used on start up to load the info into memory. Callers will use the public // used on start up to load the info into memory. Callers will use the public
// version of this function below, which returns our cached copy. // version of this function below, which returns our cached copy.
func (db *LevelDb) fetchAddrIndexTip() (*btcwire.ShaHash, int64, error) { func (db *LevelDb) fetchAddrIndexTip() (*wire.ShaHash, int64, error) {
db.dbLock.Lock() db.dbLock.Lock()
defer db.dbLock.Unlock() defer db.dbLock.Unlock()
data, err := db.lDb.Get(addrIndexMetaDataKey, db.ro) data, err := db.lDb.Get(addrIndexMetaDataKey, db.ro)
if err != nil { if err != nil {
return &btcwire.ShaHash{}, -1, database.ErrAddrIndexDoesNotExist return &wire.ShaHash{}, -1, database.ErrAddrIndexDoesNotExist
} }
var blkSha btcwire.ShaHash var blkSha wire.ShaHash
blkSha.SetBytes(data[0:32]) blkSha.SetBytes(data[0:32])
blkHeight := binary.LittleEndian.Uint64(data[32:]) blkHeight := binary.LittleEndian.Uint64(data[32:])
@ -312,12 +312,12 @@ func (db *LevelDb) fetchAddrIndexTip() (*btcwire.ShaHash, int64, error) {
// block whose transactions have been indexed by address. It will return // block whose transactions have been indexed by address. It will return
// ErrAddrIndexDoesNotExist along with a zero hash, and -1 if the // ErrAddrIndexDoesNotExist along with a zero hash, and -1 if the
// addrindex hasn't yet been built up. // addrindex hasn't yet been built up.
func (db *LevelDb) FetchAddrIndexTip() (*btcwire.ShaHash, int64, error) { func (db *LevelDb) FetchAddrIndexTip() (*wire.ShaHash, int64, error) {
db.dbLock.Lock() db.dbLock.Lock()
defer db.dbLock.Unlock() defer db.dbLock.Unlock()
if db.lastAddrIndexBlkIdx == -1 { if db.lastAddrIndexBlkIdx == -1 {
return &btcwire.ShaHash{}, -1, database.ErrAddrIndexDoesNotExist return &wire.ShaHash{}, -1, database.ErrAddrIndexDoesNotExist
} }
sha := db.lastAddrIndexBlkSha sha := db.lastAddrIndexBlkSha

View file

@ -9,7 +9,7 @@ import (
"testing" "testing"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcwire" "github.com/btcsuite/btcd/wire"
) )
// we need to test for an empty database and make certain it returns the proper // we need to test for an empty database and make certain it returns the proper
@ -30,7 +30,7 @@ func TestEmptyDB(t *testing.T) {
defer os.RemoveAll(dbnamever) defer os.RemoveAll(dbnamever)
sha, height, err := db.NewestSha() sha, height, err := db.NewestSha()
if !sha.IsEqual(&btcwire.ShaHash{}) { if !sha.IsEqual(&wire.ShaHash{}) {
t.Errorf("sha not zero hash") t.Errorf("sha not zero hash")
} }
if height != -1 { if height != -1 {
@ -54,7 +54,7 @@ func TestEmptyDB(t *testing.T) {
}() }()
sha, height, err = db.NewestSha() sha, height, err = db.NewestSha()
if !sha.IsEqual(&btcwire.ShaHash{}) { if !sha.IsEqual(&wire.ShaHash{}) {
t.Errorf("sha not zero hash") t.Errorf("sha not zero hash")
} }
if height != -1 { if height != -1 {

View file

@ -11,8 +11,8 @@ import (
"testing" "testing"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
) )
func Test_dupTx(t *testing.T) { func Test_dupTx(t *testing.T) {
@ -43,7 +43,7 @@ func Test_dupTx(t *testing.T) {
return return
} }
var lastSha *btcwire.ShaHash var lastSha *wire.ShaHash
// Populate with the fisrt 256 blocks, so we have blocks to 'mess with' // Populate with the fisrt 256 blocks, so we have blocks to 'mess with'
err = nil err = nil
@ -53,7 +53,7 @@ out:
// except for NoVerify which does not allow lookups check inputs // except for NoVerify which does not allow lookups check inputs
mblock := block.MsgBlock() mblock := block.MsgBlock()
var txneededList []*btcwire.ShaHash var txneededList []*wire.ShaHash
for _, tx := range mblock.Transactions { for _, tx := range mblock.Transactions {
for _, txin := range tx.TxIn { for _, txin := range tx.TxIn {
if txin.PreviousOutPoint.Index == uint32(4294967295) { if txin.PreviousOutPoint.Index == uint32(4294967295) {
@ -114,21 +114,21 @@ out:
// these block are not verified, so there are a bunch of garbage fields // these block are not verified, so there are a bunch of garbage fields
// in the 'generated' block. // in the 'generated' block.
var bh btcwire.BlockHeader var bh wire.BlockHeader
bh.Version = 2 bh.Version = 2
bh.PrevBlock = *lastSha bh.PrevBlock = *lastSha
// Bits, Nonce are not filled in // Bits, Nonce are not filled in
mblk := btcwire.NewMsgBlock(&bh) mblk := wire.NewMsgBlock(&bh)
hash, _ := btcwire.NewShaHashFromStr("df2b060fa2e5e9c8ed5eaf6a45c13753ec8c63282b2688322eba40cd98ea067a") hash, _ := wire.NewShaHashFromStr("df2b060fa2e5e9c8ed5eaf6a45c13753ec8c63282b2688322eba40cd98ea067a")
po := btcwire.NewOutPoint(hash, 0) po := wire.NewOutPoint(hash, 0)
txI := btcwire.NewTxIn(po, []byte("garbage")) txI := wire.NewTxIn(po, []byte("garbage"))
txO := btcwire.NewTxOut(50000000, []byte("garbageout")) txO := wire.NewTxOut(50000000, []byte("garbageout"))
var tx btcwire.MsgTx var tx wire.MsgTx
tx.AddTxIn(txI) tx.AddTxIn(txI)
tx.AddTxOut(txO) tx.AddTxOut(txO)
@ -136,7 +136,7 @@ out:
blk := btcutil.NewBlock(mblk) blk := btcutil.NewBlock(mblk)
fetchList := []*btcwire.ShaHash{hash} fetchList := []*wire.ShaHash{hash}
listReply := db.FetchUnSpentTxByShaList(fetchList) listReply := db.FetchUnSpentTxByShaList(fetchList)
for _, lr := range listReply { for _, lr := range listReply {
if lr.Err != nil { if lr.Err != nil {

View file

@ -12,8 +12,8 @@ import (
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
_ "github.com/btcsuite/btcd/database/ldb" _ "github.com/btcsuite/btcd/database/ldb"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
) )
var tstBlocks []*btcutil.Block var tstBlocks []*btcutil.Block
@ -68,10 +68,10 @@ endtest:
block := blocks[height] block := blocks[height]
// look up inputs to this tx // look up inputs to this tx
mblock := block.MsgBlock() mblock := block.MsgBlock()
var txneededList []*btcwire.ShaHash var txneededList []*wire.ShaHash
var txlookupList []*btcwire.ShaHash var txlookupList []*wire.ShaHash
var txOutList []*btcwire.ShaHash var txOutList []*wire.ShaHash
var txInList []*btcwire.OutPoint var txInList []*wire.OutPoint
for _, tx := range mblock.Transactions { for _, tx := range mblock.Transactions {
for _, txin := range tx.TxIn { for _, txin := range tx.TxIn {
if txin.PreviousOutPoint.Index == uint32(4294967295) { if txin.PreviousOutPoint.Index == uint32(4294967295) {
@ -96,7 +96,7 @@ endtest:
txOutList = append(txOutList, &txshaname) txOutList = append(txOutList, &txshaname)
} }
txneededmap := map[btcwire.ShaHash]*database.TxListReply{} txneededmap := map[wire.ShaHash]*database.TxListReply{}
txlist := db.FetchUnSpentTxByShaList(txneededList) txlist := db.FetchUnSpentTxByShaList(txneededList)
for _, txe := range txlist { for _, txe := range txlist {
if txe.Err != nil { if txe.Err != nil {
@ -122,7 +122,7 @@ endtest:
break endtest break endtest
} }
txlookupmap := map[btcwire.ShaHash]*database.TxListReply{} txlookupmap := map[wire.ShaHash]*database.TxListReply{}
txlist = db.FetchTxByShaList(txlookupList) txlist = db.FetchTxByShaList(txlookupList)
for _, txe := range txlist { for _, txe := range txlist {
if txe.Err != nil { if txe.Err != nil {
@ -158,7 +158,7 @@ endtest:
break endtest break endtest
} }
txlookupmap = map[btcwire.ShaHash]*database.TxListReply{} txlookupmap = map[wire.ShaHash]*database.TxListReply{}
txlist = db.FetchUnSpentTxByShaList(txlookupList) txlist = db.FetchUnSpentTxByShaList(txlookupList)
for _, txe := range txlist { for _, txe := range txlist {
if txe.Err != nil { if txe.Err != nil {
@ -180,7 +180,7 @@ endtest:
t.Errorf("failed to insert block %v err %v", height, err) t.Errorf("failed to insert block %v err %v", height, err)
break endtest break endtest
} }
txlookupmap = map[btcwire.ShaHash]*database.TxListReply{} txlookupmap = map[wire.ShaHash]*database.TxListReply{}
txlist = db.FetchTxByShaList(txlookupList) txlist = db.FetchTxByShaList(txlookupList)
for _, txe := range txlist { for _, txe := range txlist {
if txe.Err != nil { if txe.Err != nil {

View file

@ -12,9 +12,9 @@ import (
"sync" "sync"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btclog" "github.com/btcsuite/btclog"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
"github.com/btcsuite/goleveldb/leveldb" "github.com/btcsuite/goleveldb/leveldb"
"github.com/btcsuite/goleveldb/leveldb/opt" "github.com/btcsuite/goleveldb/leveldb/opt"
) )
@ -28,7 +28,7 @@ const (
var log = btclog.Disabled var log = btclog.Disabled
type tTxInsertData struct { type tTxInsertData struct {
txsha *btcwire.ShaHash txsha *wire.ShaHash
blockid int64 blockid int64
txoff int txoff int
txlen int txlen int
@ -50,14 +50,14 @@ type LevelDb struct {
nextBlock int64 nextBlock int64
lastBlkShaCached bool lastBlkShaCached bool
lastBlkSha btcwire.ShaHash lastBlkSha wire.ShaHash
lastBlkIdx int64 lastBlkIdx int64
lastAddrIndexBlkSha btcwire.ShaHash lastAddrIndexBlkSha wire.ShaHash
lastAddrIndexBlkIdx int64 lastAddrIndexBlkIdx int64
txUpdateMap map[btcwire.ShaHash]*txUpdateObj txUpdateMap map[wire.ShaHash]*txUpdateObj
txSpentUpdateMap map[btcwire.ShaHash]*spentTxUpdate txSpentUpdateMap map[wire.ShaHash]*spentTxUpdate
} }
var self = database.DriverDB{DbType: "leveldb", CreateDB: CreateDB, OpenDB: OpenDB} var self = database.DriverDB{DbType: "leveldb", CreateDB: CreateDB, OpenDB: OpenDB}
@ -100,7 +100,7 @@ func OpenDB(args ...interface{}) (database.Db, error) {
increment := int64(100000) increment := int64(100000)
ldb := db.(*LevelDb) ldb := db.(*LevelDb)
var lastSha *btcwire.ShaHash var lastSha *wire.ShaHash
// forward scan // forward scan
blockforward: blockforward:
for { for {
@ -116,7 +116,7 @@ blockforward:
//no blocks in db, odd but ok. //no blocks in db, odd but ok.
lastknownblock = -1 lastknownblock = -1
nextunknownblock = 0 nextunknownblock = 0
var emptysha btcwire.ShaHash var emptysha wire.ShaHash
lastSha = &emptysha lastSha = &emptysha
} else { } else {
nextunknownblock = testblock nextunknownblock = testblock
@ -168,8 +168,8 @@ func openDB(dbpath string, create bool) (pbdb database.Db, err error) {
if err == nil { if err == nil {
db.lDb = tlDb db.lDb = tlDb
db.txUpdateMap = map[btcwire.ShaHash]*txUpdateObj{} db.txUpdateMap = map[wire.ShaHash]*txUpdateObj{}
db.txSpentUpdateMap = make(map[btcwire.ShaHash]*spentTxUpdate) db.txSpentUpdateMap = make(map[wire.ShaHash]*spentTxUpdate)
pbdb = &db pbdb = &db
} }
@ -291,7 +291,7 @@ func (db *LevelDb) Close() error {
// DropAfterBlockBySha will remove any blocks from the database after // DropAfterBlockBySha will remove any blocks from the database after
// the given block. // the given block.
func (db *LevelDb) DropAfterBlockBySha(sha *btcwire.ShaHash) (rerr error) { func (db *LevelDb) DropAfterBlockBySha(sha *wire.ShaHash) (rerr error) {
db.dbLock.Lock() db.dbLock.Lock()
defer db.dbLock.Unlock() defer db.dbLock.Unlock()
defer func() { defer func() {
@ -413,16 +413,16 @@ func (db *LevelDb) InsertBlock(block *btcutil.Block) (height int64, rerr error)
// http://blockexplorer.com/b/91812 dup in 91842 // http://blockexplorer.com/b/91812 dup in 91842
// http://blockexplorer.com/b/91722 dup in 91880 // http://blockexplorer.com/b/91722 dup in 91880
if newheight == 91812 { if newheight == 91812 {
dupsha, err := btcwire.NewShaHashFromStr("d5d27987d2a3dfc724e359870c6644b40e497bdc0589a033220fe15429d88599") dupsha, err := wire.NewShaHashFromStr("d5d27987d2a3dfc724e359870c6644b40e497bdc0589a033220fe15429d88599")
if err != nil { if err != nil {
panic("invalid sha string in source") panic("invalid sha string in source")
} }
if txsha.IsEqual(dupsha) { if txsha.IsEqual(dupsha) {
// marking TxOut[0] as spent // marking TxOut[0] as spent
po := btcwire.NewOutPoint(dupsha, 0) po := wire.NewOutPoint(dupsha, 0)
txI := btcwire.NewTxIn(po, []byte("garbage")) txI := wire.NewTxIn(po, []byte("garbage"))
var spendtx btcwire.MsgTx var spendtx wire.MsgTx
spendtx.AddTxIn(txI) spendtx.AddTxIn(txI)
err = db.doSpend(&spendtx) err = db.doSpend(&spendtx)
if err != nil { if err != nil {
@ -431,16 +431,16 @@ func (db *LevelDb) InsertBlock(block *btcutil.Block) (height int64, rerr error)
} }
} }
if newheight == 91722 { if newheight == 91722 {
dupsha, err := btcwire.NewShaHashFromStr("e3bf3d07d4b0375638d5f1db5255fe07ba2c4cb067cd81b84ee974b6585fb468") dupsha, err := wire.NewShaHashFromStr("e3bf3d07d4b0375638d5f1db5255fe07ba2c4cb067cd81b84ee974b6585fb468")
if err != nil { if err != nil {
panic("invalid sha string in source") panic("invalid sha string in source")
} }
if txsha.IsEqual(dupsha) { if txsha.IsEqual(dupsha) {
// marking TxOut[0] as spent // marking TxOut[0] as spent
po := btcwire.NewOutPoint(dupsha, 0) po := wire.NewOutPoint(dupsha, 0)
txI := btcwire.NewTxIn(po, []byte("garbage")) txI := wire.NewTxIn(po, []byte("garbage"))
var spendtx btcwire.MsgTx var spendtx wire.MsgTx
spendtx.AddTxIn(txI) spendtx.AddTxIn(txI)
err = db.doSpend(&spendtx) err = db.doSpend(&spendtx)
if err != nil { if err != nil {
@ -460,7 +460,7 @@ func (db *LevelDb) InsertBlock(block *btcutil.Block) (height int64, rerr error)
// doSpend iterates all TxIn in a bitcoin transaction marking each associated // doSpend iterates all TxIn in a bitcoin transaction marking each associated
// TxOut as spent. // TxOut as spent.
func (db *LevelDb) doSpend(tx *btcwire.MsgTx) error { func (db *LevelDb) doSpend(tx *wire.MsgTx) error {
for txinidx := range tx.TxIn { for txinidx := range tx.TxIn {
txin := tx.TxIn[txinidx] txin := tx.TxIn[txinidx]
@ -483,7 +483,7 @@ func (db *LevelDb) doSpend(tx *btcwire.MsgTx) error {
// unSpend iterates all TxIn in a bitcoin transaction marking each associated // unSpend iterates all TxIn in a bitcoin transaction marking each associated
// TxOut as unspent. // TxOut as unspent.
func (db *LevelDb) unSpend(tx *btcwire.MsgTx) error { func (db *LevelDb) unSpend(tx *wire.MsgTx) error {
for txinidx := range tx.TxIn { for txinidx := range tx.TxIn {
txin := tx.TxIn[txinidx] txin := tx.TxIn[txinidx]
@ -502,15 +502,15 @@ func (db *LevelDb) unSpend(tx *btcwire.MsgTx) error {
return nil return nil
} }
func (db *LevelDb) setSpentData(sha *btcwire.ShaHash, idx uint32) error { func (db *LevelDb) setSpentData(sha *wire.ShaHash, idx uint32) error {
return db.setclearSpentData(sha, idx, true) return db.setclearSpentData(sha, idx, true)
} }
func (db *LevelDb) clearSpentData(sha *btcwire.ShaHash, idx uint32) error { func (db *LevelDb) clearSpentData(sha *wire.ShaHash, idx uint32) error {
return db.setclearSpentData(sha, idx, false) return db.setclearSpentData(sha, idx, false)
} }
func (db *LevelDb) setclearSpentData(txsha *btcwire.ShaHash, idx uint32, set bool) error { func (db *LevelDb) setclearSpentData(txsha *wire.ShaHash, idx uint32, set bool) error {
var txUo *txUpdateObj var txUo *txUpdateObj
var ok bool var ok bool
@ -625,18 +625,18 @@ func int64ToKey(keyint int64) []byte {
return []byte(key) return []byte(key)
} }
func shaBlkToKey(sha *btcwire.ShaHash) []byte { func shaBlkToKey(sha *wire.ShaHash) []byte {
shaB := sha.Bytes() shaB := sha.Bytes()
return shaB return shaB
} }
func shaTxToKey(sha *btcwire.ShaHash) []byte { func shaTxToKey(sha *wire.ShaHash) []byte {
shaB := sha.Bytes() shaB := sha.Bytes()
shaB = append(shaB, "tx"...) shaB = append(shaB, "tx"...)
return shaB return shaB
} }
func shaSpentTxToKey(sha *btcwire.ShaHash) []byte { func shaSpentTxToKey(sha *wire.ShaHash) []byte {
shaB := sha.Bytes() shaB := sha.Bytes()
shaB = append(shaB, "sx"...) shaB = append(shaB, "sx"...)
return shaB return shaB
@ -687,8 +687,8 @@ func (db *LevelDb) processBatches() error {
log.Tracef("batch failed %v\n", err) log.Tracef("batch failed %v\n", err)
return err return err
} }
db.txUpdateMap = map[btcwire.ShaHash]*txUpdateObj{} db.txUpdateMap = map[wire.ShaHash]*txUpdateObj{}
db.txSpentUpdateMap = make(map[btcwire.ShaHash]*spentTxUpdate) db.txSpentUpdateMap = make(map[wire.ShaHash]*spentTxUpdate)
} }
return nil return nil

View file

@ -16,13 +16,13 @@ import (
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcd/txscript" "github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcnet" "github.com/btcsuite/btcnet"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
"golang.org/x/crypto/ripemd160" "golang.org/x/crypto/ripemd160"
) )
var network = btcwire.MainNet var network = wire.MainNet
// testDb is used to store db related context for a running test. // testDb is used to store db related context for a running test.
// the `cleanUpFunc` *must* be called after each test to maintain db // the `cleanUpFunc` *must* be called after each test to maintain db
@ -72,14 +72,14 @@ func TestOperational(t *testing.T) {
// testAddrIndexOperations ensures that all normal operations concerning // testAddrIndexOperations ensures that all normal operations concerning
// the optional address index function correctly. // the optional address index function correctly.
func testAddrIndexOperations(t *testing.T, db database.Db, newestBlock *btcutil.Block, newestSha *btcwire.ShaHash, newestBlockIdx int64) { func testAddrIndexOperations(t *testing.T, db database.Db, newestBlock *btcutil.Block, newestSha *wire.ShaHash, newestBlockIdx int64) {
// Metadata about the current addr index state should be unset. // Metadata about the current addr index state should be unset.
sha, height, err := db.FetchAddrIndexTip() sha, height, err := db.FetchAddrIndexTip()
if err != database.ErrAddrIndexDoesNotExist { if err != database.ErrAddrIndexDoesNotExist {
t.Fatalf("Address index metadata shouldn't be in db, hasn't been built up yet.") t.Fatalf("Address index metadata shouldn't be in db, hasn't been built up yet.")
} }
var zeroHash btcwire.ShaHash var zeroHash wire.ShaHash
if !sha.IsEqual(&zeroHash) { if !sha.IsEqual(&zeroHash) {
t.Fatalf("AddrIndexTip wrong hash got: %s, want %s", sha, &zeroHash) t.Fatalf("AddrIndexTip wrong hash got: %s, want %s", sha, &zeroHash)
@ -122,7 +122,7 @@ func testAddrIndexOperations(t *testing.T, db database.Db, newestBlock *btcutil.
// Create a fake index. // Create a fake index.
blktxLoc, _ := newestBlock.TxLoc() blktxLoc, _ := newestBlock.TxLoc()
testIndex[hash160Bytes] = []*btcwire.TxLoc{&blktxLoc[0]} testIndex[hash160Bytes] = []*wire.TxLoc{&blktxLoc[0]}
// Insert our test addr index into the DB. // Insert our test addr index into the DB.
err = db.UpdateAddrIndexForBlock(newestSha, newestBlockIdx, testIndex) err = db.UpdateAddrIndexForBlock(newestSha, newestBlockIdx, testIndex)
@ -188,7 +188,7 @@ func testAddrIndexOperations(t *testing.T, db database.Db, newestBlock *btcutil.
} }
func assertAddrIndexTipIsUpdated(db database.Db, t *testing.T, newestSha *btcwire.ShaHash, newestBlockIdx int64) { func assertAddrIndexTipIsUpdated(db database.Db, t *testing.T, newestSha *wire.ShaHash, newestBlockIdx int64) {
// Safe to ignore error, since height will be < 0 in "error" case. // Safe to ignore error, since height will be < 0 in "error" case.
sha, height, _ := db.FetchAddrIndexTip() sha, height, _ := db.FetchAddrIndexTip()
if newestBlockIdx != height { if newestBlockIdx != height {
@ -218,7 +218,7 @@ out:
for height := int64(0); height < int64(len(testDb.blocks)); height++ { for height := int64(0); height < int64(len(testDb.blocks)); height++ {
block := testDb.blocks[height] block := testDb.blocks[height]
mblock := block.MsgBlock() mblock := block.MsgBlock()
var txneededList []*btcwire.ShaHash var txneededList []*wire.ShaHash
for _, tx := range mblock.Transactions { for _, tx := range mblock.Transactions {
for _, txin := range tx.TxIn { for _, txin := range tx.TxIn {
if txin.PreviousOutPoint.Index == uint32(4294967295) { if txin.PreviousOutPoint.Index == uint32(4294967295) {
@ -467,7 +467,7 @@ func testFetchHeightRange(t *testing.T, db database.Db, blocks []*btcutil.Block)
var testincrement int64 = 50 var testincrement int64 = 50
var testcnt int64 = 100 var testcnt int64 = 100
shanames := make([]*btcwire.ShaHash, len(blocks)) shanames := make([]*wire.ShaHash, len(blocks))
nBlocks := int64(len(blocks)) nBlocks := int64(len(blocks))
@ -531,12 +531,12 @@ func TestLimitAndSkipFetchTxsForAddr(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("Unable make test pkScript %v", err) t.Fatalf("Unable make test pkScript %v", err)
} }
fakeTxOut := btcwire.NewTxOut(10, outputScript) fakeTxOut := wire.NewTxOut(10, outputScript)
var emptyHash btcwire.ShaHash var emptyHash wire.ShaHash
fakeHeader := btcwire.NewBlockHeader(&emptyHash, &emptyHash, 1, 1) fakeHeader := wire.NewBlockHeader(&emptyHash, &emptyHash, 1, 1)
msgBlock := btcwire.NewMsgBlock(fakeHeader) msgBlock := wire.NewMsgBlock(fakeHeader)
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
mtx := btcwire.NewMsgTx() mtx := wire.NewMsgTx()
mtx.AddTxOut(fakeTxOut) mtx.AddTxOut(fakeTxOut)
msgBlock.AddTransaction(mtx) msgBlock.AddTransaction(mtx)
} }

View file

@ -10,8 +10,8 @@ import (
"errors" "errors"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
"github.com/btcsuite/goleveldb/leveldb" "github.com/btcsuite/goleveldb/leveldb"
"github.com/btcsuite/goleveldb/leveldb/util" "github.com/btcsuite/goleveldb/leveldb/util"
@ -37,7 +37,7 @@ var addrIndexMetaDataKey = []byte("addrindex")
var addrIndexKeyPrefix = []byte("a-") var addrIndexKeyPrefix = []byte("a-")
type txUpdateObj struct { type txUpdateObj struct {
txSha *btcwire.ShaHash txSha *wire.ShaHash
blkHeight int64 blkHeight int64
txoff int txoff int
txlen int txlen int
@ -66,7 +66,7 @@ type txAddrIndex struct {
} }
// InsertTx inserts a tx hash and its associated data into the database. // InsertTx inserts a tx hash and its associated data into the database.
func (db *LevelDb) InsertTx(txsha *btcwire.ShaHash, height int64, txoff int, txlen int, spentbuf []byte) (err error) { func (db *LevelDb) InsertTx(txsha *wire.ShaHash, height int64, txoff int, txlen int, spentbuf []byte) (err error) {
db.dbLock.Lock() db.dbLock.Lock()
defer db.dbLock.Unlock() defer db.dbLock.Unlock()
@ -75,7 +75,7 @@ func (db *LevelDb) InsertTx(txsha *btcwire.ShaHash, height int64, txoff int, txl
// insertTx inserts a tx hash and its associated data into the database. // insertTx inserts a tx hash and its associated data into the database.
// Must be called with db lock held. // Must be called with db lock held.
func (db *LevelDb) insertTx(txSha *btcwire.ShaHash, height int64, txoff int, txlen int, spentbuf []byte) (err error) { func (db *LevelDb) insertTx(txSha *wire.ShaHash, height int64, txoff int, txlen int, spentbuf []byte) (err error) {
var txU txUpdateObj var txU txUpdateObj
txU.txSha = txSha txU.txSha = txSha
@ -105,7 +105,7 @@ func (db *LevelDb) formatTx(txu *txUpdateObj) []byte {
return txW[:] return txW[:]
} }
func (db *LevelDb) getTxData(txsha *btcwire.ShaHash) (int64, int, int, []byte, error) { func (db *LevelDb) getTxData(txsha *wire.ShaHash) (int64, int, int, []byte, error) {
key := shaTxToKey(txsha) key := shaTxToKey(txsha)
buf, err := db.lDb.Get(key, db.ro) buf, err := db.lDb.Get(key, db.ro)
if err != nil { if err != nil {
@ -122,7 +122,7 @@ func (db *LevelDb) getTxData(txsha *btcwire.ShaHash) (int64, int, int, []byte, e
return int64(blkHeight), int(txOff), int(txLen), spentBuf, nil return int64(blkHeight), int(txOff), int(txLen), spentBuf, nil
} }
func (db *LevelDb) getTxFullySpent(txsha *btcwire.ShaHash) ([]*spentTx, error) { func (db *LevelDb) getTxFullySpent(txsha *wire.ShaHash) ([]*spentTx, error) {
var badTxList, spentTxList []*spentTx var badTxList, spentTxList []*spentTx
@ -177,7 +177,7 @@ func (db *LevelDb) formatTxFullySpent(sTxList []*spentTx) []byte {
} }
// ExistsTxSha returns if the given tx sha exists in the database // ExistsTxSha returns if the given tx sha exists in the database
func (db *LevelDb) ExistsTxSha(txsha *btcwire.ShaHash) (bool, error) { func (db *LevelDb) ExistsTxSha(txsha *wire.ShaHash) (bool, error) {
db.dbLock.Lock() db.dbLock.Lock()
defer db.dbLock.Unlock() defer db.dbLock.Unlock()
@ -186,14 +186,14 @@ func (db *LevelDb) ExistsTxSha(txsha *btcwire.ShaHash) (bool, error) {
// existsTxSha returns if the given tx sha exists in the database.o // existsTxSha returns if the given tx sha exists in the database.o
// Must be called with the db lock held. // Must be called with the db lock held.
func (db *LevelDb) existsTxSha(txSha *btcwire.ShaHash) (bool, error) { func (db *LevelDb) existsTxSha(txSha *wire.ShaHash) (bool, error) {
key := shaTxToKey(txSha) key := shaTxToKey(txSha)
return db.lDb.Has(key, db.ro) return db.lDb.Has(key, db.ro)
} }
// FetchTxByShaList returns the most recent tx of the name fully spent or not // FetchTxByShaList returns the most recent tx of the name fully spent or not
func (db *LevelDb) FetchTxByShaList(txShaList []*btcwire.ShaHash) []*database.TxListReply { func (db *LevelDb) FetchTxByShaList(txShaList []*wire.ShaHash) []*database.TxListReply {
db.dbLock.Lock() db.dbLock.Lock()
defer db.dbLock.Unlock() defer db.dbLock.Unlock()
@ -238,7 +238,7 @@ func (db *LevelDb) FetchTxByShaList(txShaList []*btcwire.ShaHash) []*database.Tx
// FetchUnSpentTxByShaList given a array of ShaHash, look up the transactions // FetchUnSpentTxByShaList given a array of ShaHash, look up the transactions
// and return them in a TxListReply array. // and return them in a TxListReply array.
func (db *LevelDb) FetchUnSpentTxByShaList(txShaList []*btcwire.ShaHash) []*database.TxListReply { func (db *LevelDb) FetchUnSpentTxByShaList(txShaList []*wire.ShaHash) []*database.TxListReply {
db.dbLock.Lock() db.dbLock.Lock()
defer db.dbLock.Unlock() defer db.dbLock.Unlock()
@ -261,7 +261,7 @@ func (db *LevelDb) FetchUnSpentTxByShaList(txShaList []*btcwire.ShaHash) []*data
} }
// fetchTxDataBySha returns several pieces of data regarding the given sha. // fetchTxDataBySha returns several pieces of data regarding the given sha.
func (db *LevelDb) fetchTxDataBySha(txsha *btcwire.ShaHash) (rtx *btcwire.MsgTx, rblksha *btcwire.ShaHash, rheight int64, rtxspent []byte, err error) { func (db *LevelDb) fetchTxDataBySha(txsha *wire.ShaHash) (rtx *wire.MsgTx, rblksha *wire.ShaHash, rheight int64, rtxspent []byte, err error) {
var blkHeight int64 var blkHeight int64
var txspent []byte var txspent []byte
var txOff, txLen int var txOff, txLen int
@ -278,8 +278,8 @@ func (db *LevelDb) fetchTxDataBySha(txsha *btcwire.ShaHash) (rtx *btcwire.MsgTx,
// fetchTxDataByLoc returns several pieces of data regarding the given tx // fetchTxDataByLoc returns several pieces of data regarding the given tx
// located by the block/offset/size location // located by the block/offset/size location
func (db *LevelDb) fetchTxDataByLoc(blkHeight int64, txOff int, txLen int, txspent []byte) (rtx *btcwire.MsgTx, rblksha *btcwire.ShaHash, rheight int64, rtxspent []byte, err error) { func (db *LevelDb) fetchTxDataByLoc(blkHeight int64, txOff int, txLen int, txspent []byte) (rtx *wire.MsgTx, rblksha *wire.ShaHash, rheight int64, rtxspent []byte, err error) {
var blksha *btcwire.ShaHash var blksha *wire.ShaHash
var blkbuf []byte var blkbuf []byte
blksha, blkbuf, err = db.getBlkByHeight(blkHeight) blksha, blkbuf, err = db.getBlkByHeight(blkHeight)
@ -299,7 +299,7 @@ func (db *LevelDb) fetchTxDataByLoc(blkHeight int64, txOff int, txLen int, txspe
} }
rbuf := bytes.NewReader(blkbuf[txOff : txOff+txLen]) rbuf := bytes.NewReader(blkbuf[txOff : txOff+txLen])
var tx btcwire.MsgTx var tx wire.MsgTx
err = tx.Deserialize(rbuf) err = tx.Deserialize(rbuf)
if err != nil { if err != nil {
log.Warnf("unable to decode tx block %v %v txoff %v txlen %v", log.Warnf("unable to decode tx block %v %v txoff %v txlen %v",
@ -311,7 +311,7 @@ func (db *LevelDb) fetchTxDataByLoc(blkHeight int64, txOff int, txLen int, txspe
} }
// FetchTxBySha returns some data for the given Tx Sha. // FetchTxBySha returns some data for the given Tx Sha.
func (db *LevelDb) FetchTxBySha(txsha *btcwire.ShaHash) ([]*database.TxListReply, error) { func (db *LevelDb) FetchTxBySha(txsha *wire.ShaHash) ([]*database.TxListReply, error) {
db.dbLock.Lock() db.dbLock.Lock()
defer db.dbLock.Unlock() defer db.dbLock.Unlock()
@ -497,7 +497,7 @@ func (db *LevelDb) FetchTxsForAddr(addr btcutil.Address, skip int,
// append-only list for the stored value. However, this add unnecessary // append-only list for the stored value. However, this add unnecessary
// overhead when storing and retrieving since the entire list must // overhead when storing and retrieving since the entire list must
// be fetched each time. // be fetched each time.
func (db *LevelDb) UpdateAddrIndexForBlock(blkSha *btcwire.ShaHash, blkHeight int64, addrIndex database.BlockAddrIndex) error { func (db *LevelDb) UpdateAddrIndexForBlock(blkSha *wire.ShaHash, blkHeight int64, addrIndex database.BlockAddrIndex) error {
db.dbLock.Lock() db.dbLock.Lock()
defer db.dbLock.Unlock() defer db.dbLock.Unlock()
@ -572,7 +572,7 @@ func (db *LevelDb) DeleteAddrIndex() error {
} }
db.lastAddrIndexBlkIdx = -1 db.lastAddrIndexBlkIdx = -1
db.lastAddrIndexBlkSha = btcwire.ShaHash{} db.lastAddrIndexBlkSha = wire.ShaHash{}
return nil return nil
} }

View file

@ -11,8 +11,8 @@ import (
"sync" "sync"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
) )
// Errors that the various database functions may return. // Errors that the various database functions may return.
@ -21,7 +21,7 @@ var (
) )
var ( var (
zeroHash = btcwire.ShaHash{} zeroHash = wire.ShaHash{}
// The following two hashes are ones that must be specially handled. // The following two hashes are ones that must be specially handled.
// See the comments where they're used for more details. // See the comments where they're used for more details.
@ -38,11 +38,11 @@ type tTxInsertData struct {
} }
// newShaHashFromStr converts the passed big-endian hex string into a // newShaHashFromStr converts the passed big-endian hex string into a
// btcwire.ShaHash. It only differs from the one available in btcwire in that // wire.ShaHash. It only differs from the one available in btcwire in that
// it ignores the error since it will only (and must only) be called with // it ignores the error since it will only (and must only) be called with
// hard-coded, and therefore known good, hashes. // hard-coded, and therefore known good, hashes.
func newShaHashFromStr(hexStr string) *btcwire.ShaHash { func newShaHashFromStr(hexStr string) *wire.ShaHash {
sha, _ := btcwire.NewShaHashFromStr(hexStr) sha, _ := wire.NewShaHashFromStr(hexStr)
return sha return sha
} }
@ -51,7 +51,7 @@ func newShaHashFromStr(hexStr string) *btcwire.ShaHash {
// has no inputs. This is represented in the block chain by a transaction with // has no inputs. This is represented in the block chain by a transaction with
// a single input that has a previous output transaction index set to the // a single input that has a previous output transaction index set to the
// maximum value along with a zero hash. // maximum value along with a zero hash.
func isCoinbaseInput(txIn *btcwire.TxIn) bool { func isCoinbaseInput(txIn *wire.TxIn) bool {
prevOut := &txIn.PreviousOutPoint prevOut := &txIn.PreviousOutPoint
if prevOut.Index == math.MaxUint32 && prevOut.Hash.IsEqual(&zeroHash) { if prevOut.Index == math.MaxUint32 && prevOut.Hash.IsEqual(&zeroHash) {
return true return true
@ -82,15 +82,15 @@ type MemDb struct {
// blocks holds all of the bitcoin blocks that will be in the memory // blocks holds all of the bitcoin blocks that will be in the memory
// database. // database.
blocks []*btcwire.MsgBlock blocks []*wire.MsgBlock
// blocksBySha keeps track of block heights by hash. The height can // blocksBySha keeps track of block heights by hash. The height can
// be used as an index into the blocks slice. // be used as an index into the blocks slice.
blocksBySha map[btcwire.ShaHash]int64 blocksBySha map[wire.ShaHash]int64
// txns holds information about transactions such as which their // txns holds information about transactions such as which their
// block height and spent status of all their outputs. // block height and spent status of all their outputs.
txns map[btcwire.ShaHash][]*tTxInsertData txns map[wire.ShaHash][]*tTxInsertData
// closed indicates whether or not the database has been closed and is // closed indicates whether or not the database has been closed and is
// therefore invalidated. // therefore invalidated.
@ -98,7 +98,7 @@ type MemDb struct {
} }
// removeTx removes the passed transaction including unspending it. // removeTx removes the passed transaction including unspending it.
func (db *MemDb) removeTx(msgTx *btcwire.MsgTx, txHash *btcwire.ShaHash) { func (db *MemDb) removeTx(msgTx *wire.MsgTx, txHash *wire.ShaHash) {
// Undo all of the spends for the transaction. // Undo all of the spends for the transaction.
for _, txIn := range msgTx.TxIn { for _, txIn := range msgTx.TxIn {
if isCoinbaseInput(txIn) { if isCoinbaseInput(txIn) {
@ -157,7 +157,7 @@ func (db *MemDb) Close() error {
// block. This is different than a simple truncate since the spend information // block. This is different than a simple truncate since the spend information
// for each block must also be unwound. This is part of the database.Db interface // for each block must also be unwound. This is part of the database.Db interface
// implementation. // implementation.
func (db *MemDb) DropAfterBlockBySha(sha *btcwire.ShaHash) error { func (db *MemDb) DropAfterBlockBySha(sha *wire.ShaHash) error {
db.Lock() db.Lock()
defer db.Unlock() defer db.Unlock()
@ -197,7 +197,7 @@ func (db *MemDb) DropAfterBlockBySha(sha *btcwire.ShaHash) error {
// ExistsSha returns whether or not the given block hash is present in the // ExistsSha returns whether or not the given block hash is present in the
// database. This is part of the database.Db interface implementation. // database. This is part of the database.Db interface implementation.
func (db *MemDb) ExistsSha(sha *btcwire.ShaHash) (bool, error) { func (db *MemDb) ExistsSha(sha *wire.ShaHash) (bool, error) {
db.Lock() db.Lock()
defer db.Unlock() defer db.Unlock()
@ -218,7 +218,7 @@ func (db *MemDb) ExistsSha(sha *btcwire.ShaHash) (bool, error) {
// //
// This implementation does not use any additional cache since the entire // This implementation does not use any additional cache since the entire
// database is already in memory. // database is already in memory.
func (db *MemDb) FetchBlockBySha(sha *btcwire.ShaHash) (*btcutil.Block, error) { func (db *MemDb) FetchBlockBySha(sha *wire.ShaHash) (*btcutil.Block, error) {
db.Lock() db.Lock()
defer db.Unlock() defer db.Unlock()
@ -237,7 +237,7 @@ func (db *MemDb) FetchBlockBySha(sha *btcwire.ShaHash) (*btcutil.Block, error) {
// FetchBlockHeightBySha returns the block height for the given hash. This is // FetchBlockHeightBySha returns the block height for the given hash. This is
// part of the database.Db interface implementation. // part of the database.Db interface implementation.
func (db *MemDb) FetchBlockHeightBySha(sha *btcwire.ShaHash) (int64, error) { func (db *MemDb) FetchBlockHeightBySha(sha *wire.ShaHash) (int64, error) {
db.Lock() db.Lock()
defer db.Unlock() defer db.Unlock()
@ -252,13 +252,13 @@ func (db *MemDb) FetchBlockHeightBySha(sha *btcwire.ShaHash) (int64, error) {
return 0, fmt.Errorf("block %v is not in database", sha) return 0, fmt.Errorf("block %v is not in database", sha)
} }
// FetchBlockHeaderBySha returns a btcwire.BlockHeader for the given sha. The // FetchBlockHeaderBySha returns a wire.BlockHeader for the given sha. The
// implementation may cache the underlying data if desired. This is part of the // implementation may cache the underlying data if desired. This is part of the
// database.Db interface implementation. // database.Db interface implementation.
// //
// This implementation does not use any additional cache since the entire // This implementation does not use any additional cache since the entire
// database is already in memory. // database is already in memory.
func (db *MemDb) FetchBlockHeaderBySha(sha *btcwire.ShaHash) (*btcwire.BlockHeader, error) { func (db *MemDb) FetchBlockHeaderBySha(sha *wire.ShaHash) (*wire.BlockHeader, error) {
db.Lock() db.Lock()
defer db.Unlock() defer db.Unlock()
@ -275,7 +275,7 @@ func (db *MemDb) FetchBlockHeaderBySha(sha *btcwire.ShaHash) (*btcwire.BlockHead
// FetchBlockShaByHeight returns a block hash based on its height in the block // FetchBlockShaByHeight returns a block hash based on its height in the block
// chain. This is part of the database.Db interface implementation. // chain. This is part of the database.Db interface implementation.
func (db *MemDb) FetchBlockShaByHeight(height int64) (*btcwire.ShaHash, error) { func (db *MemDb) FetchBlockShaByHeight(height int64) (*wire.ShaHash, error) {
db.Lock() db.Lock()
defer db.Unlock() defer db.Unlock()
@ -303,7 +303,7 @@ func (db *MemDb) FetchBlockShaByHeight(height int64) (*btcwire.ShaHash, error) {
// Fetch is inclusive of the start height and exclusive of the ending height. // Fetch is inclusive of the start height and exclusive of the ending height.
// To fetch all hashes from the start height until no more are present, use the // To fetch all hashes from the start height until no more are present, use the
// special id `AllShas'. This is part of the database.Db interface implementation. // special id `AllShas'. This is part of the database.Db interface implementation.
func (db *MemDb) FetchHeightRange(startHeight, endHeight int64) ([]btcwire.ShaHash, error) { func (db *MemDb) FetchHeightRange(startHeight, endHeight int64) ([]wire.ShaHash, error) {
db.Lock() db.Lock()
defer db.Unlock() defer db.Unlock()
@ -330,7 +330,7 @@ func (db *MemDb) FetchHeightRange(startHeight, endHeight int64) ([]btcwire.ShaHa
// Fetch as many as are availalbe within the specified range. // Fetch as many as are availalbe within the specified range.
lastBlockIndex := int64(len(db.blocks) - 1) lastBlockIndex := int64(len(db.blocks) - 1)
hashList := make([]btcwire.ShaHash, 0, endHeight-startHeight) hashList := make([]wire.ShaHash, 0, endHeight-startHeight)
for i := startHeight; i < endHeight; i++ { for i := startHeight; i < endHeight; i++ {
if i > lastBlockIndex { if i > lastBlockIndex {
break break
@ -350,7 +350,7 @@ func (db *MemDb) FetchHeightRange(startHeight, endHeight int64) ([]btcwire.ShaHa
// ExistsTxSha returns whether or not the given transaction hash is present in // ExistsTxSha returns whether or not the given transaction hash is present in
// the database and is not fully spent. This is part of the database.Db interface // the database and is not fully spent. This is part of the database.Db interface
// implementation. // implementation.
func (db *MemDb) ExistsTxSha(sha *btcwire.ShaHash) (bool, error) { func (db *MemDb) ExistsTxSha(sha *wire.ShaHash) (bool, error) {
db.Lock() db.Lock()
defer db.Unlock() defer db.Unlock()
@ -371,7 +371,7 @@ func (db *MemDb) ExistsTxSha(sha *btcwire.ShaHash) (bool, error) {
// //
// This implementation does not use any additional cache since the entire // This implementation does not use any additional cache since the entire
// database is already in memory. // database is already in memory.
func (db *MemDb) FetchTxBySha(txHash *btcwire.ShaHash) ([]*database.TxListReply, error) { func (db *MemDb) FetchTxBySha(txHash *wire.ShaHash) ([]*database.TxListReply, error) {
db.Lock() db.Lock()
defer db.Unlock() defer db.Unlock()
@ -422,7 +422,7 @@ func (db *MemDb) FetchTxBySha(txHash *btcwire.ShaHash) ([]*database.TxListReply,
// will indicate the transaction does not exist. // will indicate the transaction does not exist.
// //
// This function must be called with the db lock held. // This function must be called with the db lock held.
func (db *MemDb) fetchTxByShaList(txShaList []*btcwire.ShaHash, includeSpent bool) []*database.TxListReply { func (db *MemDb) fetchTxByShaList(txShaList []*wire.ShaHash, includeSpent bool) []*database.TxListReply {
replyList := make([]*database.TxListReply, 0, len(txShaList)) replyList := make([]*database.TxListReply, 0, len(txShaList))
for i, hash := range txShaList { for i, hash := range txShaList {
// Every requested entry needs a response, so start with nothing // Every requested entry needs a response, so start with nothing
@ -498,7 +498,7 @@ func (db *MemDb) fetchTxByShaList(txShaList []*btcwire.ShaHash, includeSpent boo
// //
// This implementation does not use any additional cache since the entire // This implementation does not use any additional cache since the entire
// database is already in memory. // database is already in memory.
func (db *MemDb) FetchTxByShaList(txShaList []*btcwire.ShaHash) []*database.TxListReply { func (db *MemDb) FetchTxByShaList(txShaList []*wire.ShaHash) []*database.TxListReply {
db.Lock() db.Lock()
defer db.Unlock() defer db.Unlock()
@ -517,7 +517,7 @@ func (db *MemDb) FetchTxByShaList(txShaList []*btcwire.ShaHash) []*database.TxLi
// //
// This implementation does not use any additional cache since the entire // This implementation does not use any additional cache since the entire
// database is already in memory. // database is already in memory.
func (db *MemDb) FetchUnSpentTxByShaList(txShaList []*btcwire.ShaHash) []*database.TxListReply { func (db *MemDb) FetchUnSpentTxByShaList(txShaList []*wire.ShaHash) []*database.TxListReply {
db.Lock() db.Lock()
defer db.Unlock() defer db.Unlock()
@ -555,7 +555,7 @@ func (db *MemDb) InsertBlock(block *btcutil.Block) (int64, error) {
// Build a map of in-flight transactions because some of the inputs in // Build a map of in-flight transactions because some of the inputs in
// this block could be referencing other transactions earlier in this // this block could be referencing other transactions earlier in this
// block which are not yet in the chain. // block which are not yet in the chain.
txInFlight := map[btcwire.ShaHash]int{} txInFlight := map[wire.ShaHash]int{}
transactions := block.Transactions() transactions := block.Transactions()
for i, tx := range transactions { for i, tx := range transactions {
txInFlight[*tx.Sha()] = i txInFlight[*tx.Sha()] = i
@ -675,7 +675,7 @@ func (db *MemDb) InsertBlock(block *btcutil.Block) (int64, error) {
// the block chain. It will return the zero hash, -1 for the block height, and // the block chain. It will return the zero hash, -1 for the block height, and
// no error (nil) if there are not any blocks in the database yet. This is part // no error (nil) if there are not any blocks in the database yet. This is part
// of the database.Db interface implementation. // of the database.Db interface implementation.
func (db *MemDb) NewestSha() (*btcwire.ShaHash, int64, error) { func (db *MemDb) NewestSha() (*wire.ShaHash, int64, error) {
db.Lock() db.Lock()
defer db.Unlock() defer db.Unlock()
@ -700,13 +700,13 @@ func (db *MemDb) NewestSha() (*btcwire.ShaHash, int64, error) {
// FetchAddrIndexTip isn't currently implemented. This is a part of the // FetchAddrIndexTip isn't currently implemented. This is a part of the
// database.Db interface implementation. // database.Db interface implementation.
func (db *MemDb) FetchAddrIndexTip() (*btcwire.ShaHash, int64, error) { func (db *MemDb) FetchAddrIndexTip() (*wire.ShaHash, int64, error) {
return nil, 0, database.ErrNotImplemented return nil, 0, database.ErrNotImplemented
} }
// UpdateAddrIndexForBlock isn't currently implemented. This is a part of the // UpdateAddrIndexForBlock isn't currently implemented. This is a part of the
// database.Db interface implementation. // database.Db interface implementation.
func (db *MemDb) UpdateAddrIndexForBlock(*btcwire.ShaHash, int64, func (db *MemDb) UpdateAddrIndexForBlock(*wire.ShaHash, int64,
database.BlockAddrIndex) error { database.BlockAddrIndex) error {
return database.ErrNotImplemented return database.ErrNotImplemented
} }
@ -759,9 +759,9 @@ func (db *MemDb) Sync() error {
// newMemDb returns a new memory-only database ready for block inserts. // newMemDb returns a new memory-only database ready for block inserts.
func newMemDb() *MemDb { func newMemDb() *MemDb {
db := MemDb{ db := MemDb{
blocks: make([]*btcwire.MsgBlock, 0, 200000), blocks: make([]*wire.MsgBlock, 0, 200000),
blocksBySha: make(map[btcwire.ShaHash]int64), blocksBySha: make(map[wire.ShaHash]int64),
txns: make(map[btcwire.ShaHash][]*tTxInsertData), txns: make(map[wire.ShaHash][]*tTxInsertData),
} }
return &db return &db
} }

View file

@ -10,9 +10,9 @@ import (
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcd/database/memdb" "github.com/btcsuite/btcd/database/memdb"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcnet" "github.com/btcsuite/btcnet"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
) )
// TestClosed ensure calling the interface functions on a closed database // TestClosed ensure calling the interface functions on a closed database
@ -67,7 +67,7 @@ func TestClosed(t *testing.T) {
t.Errorf("FetchTxBySha: unexpected error %v", err) t.Errorf("FetchTxBySha: unexpected error %v", err)
} }
requestHashes := []*btcwire.ShaHash{genesisHash} requestHashes := []*wire.ShaHash{genesisHash}
reply := db.FetchTxByShaList(requestHashes) reply := db.FetchTxByShaList(requestHashes)
if len(reply) != len(requestHashes) { if len(reply) != len(requestHashes) {
t.Errorf("FetchUnSpentTxByShaList unexpected number of replies "+ t.Errorf("FetchUnSpentTxByShaList unexpected number of replies "+

View file

@ -907,7 +907,7 @@ package main
import ( import (
"github.com/btcsuite/btcrpcclient" "github.com/btcsuite/btcrpcclient"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire" "github.com/btcsuite/btcd/wire"
"io/ioutil" "io/ioutil"
"log" "log"
"path/filepath" "path/filepath"
@ -944,7 +944,7 @@ func main() {
// command with the verbose flag set to true and the verboseTx flag // command with the verbose flag set to true and the verboseTx flag
// set to false. // set to false.
genesisHashStr := "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f" genesisHashStr := "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"
blockHash, err := btcwire.NewShaHashFromStr(genesisHashStr) blockHash, err := wire.NewShaHashFromStr(genesisHashStr)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
@ -997,7 +997,7 @@ package main
import ( import (
"github.com/btcsuite/btcrpcclient" "github.com/btcsuite/btcrpcclient"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire" "github.com/btcsuite/btcd/wire"
"io/ioutil" "io/ioutil"
"log" "log"
"path/filepath" "path/filepath"
@ -1008,10 +1008,10 @@ func main() {
// Setup handlers for blockconnected and blockdisconnected // Setup handlers for blockconnected and blockdisconnected
// notifications. // notifications.
ntfnHandlers := btcrpcclient.NotificationHandlers{ ntfnHandlers := btcrpcclient.NotificationHandlers{
OnBlockConnected: func(hash *btcwire.ShaHash, height int32) { OnBlockConnected: func(hash *wire.ShaHash, height int32) {
log.Printf("Block connected: %v (%d)", hash, height) log.Printf("Block connected: %v (%d)", hash, height)
}, },
OnBlockDisconnected: func(hash *btcwire.ShaHash, height int32) { OnBlockDisconnected: func(hash *wire.ShaHash, height int32) {
log.Printf("Block disconnected: %v", hash, height) log.Printf("Block disconnected: %v", hash, height)
}, },
} }

52
log.go
View file

@ -15,8 +15,8 @@ import (
"github.com/btcsuite/btcd/blockchain" "github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcd/txscript" "github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btclog" "github.com/btcsuite/btclog"
"github.com/btcsuite/btcwire"
"github.com/btcsuite/seelog" "github.com/btcsuite/seelog"
) )
@ -219,7 +219,7 @@ func formatLockTime(lockTime uint32) string {
} }
// invSummary returns an inventory message as a human-readable string. // invSummary returns an inventory message as a human-readable string.
func invSummary(invList []*btcwire.InvVect) string { func invSummary(invList []*wire.InvVect) string {
// No inventory. // No inventory.
invLen := len(invList) invLen := len(invList)
if invLen == 0 { if invLen == 0 {
@ -230,11 +230,11 @@ func invSummary(invList []*btcwire.InvVect) string {
if invLen == 1 { if invLen == 1 {
iv := invList[0] iv := invList[0]
switch iv.Type { switch iv.Type {
case btcwire.InvTypeError: case wire.InvTypeError:
return fmt.Sprintf("error %s", iv.Hash) return fmt.Sprintf("error %s", iv.Hash)
case btcwire.InvTypeBlock: case wire.InvTypeBlock:
return fmt.Sprintf("block %s", iv.Hash) return fmt.Sprintf("block %s", iv.Hash)
case btcwire.InvTypeTx: case wire.InvTypeTx:
return fmt.Sprintf("tx %s", iv.Hash) return fmt.Sprintf("tx %s", iv.Hash)
} }
@ -246,7 +246,7 @@ func invSummary(invList []*btcwire.InvVect) string {
} }
// locatorSummary returns a block locator as a human-readable string. // locatorSummary returns a block locator as a human-readable string.
func locatorSummary(locator []*btcwire.ShaHash, stopHash *btcwire.ShaHash) string { func locatorSummary(locator []*wire.ShaHash, stopHash *wire.ShaHash) string {
if len(locator) > 0 { if len(locator) > 0 {
return fmt.Sprintf("locator %s, stop %s", locator[0], stopHash) return fmt.Sprintf("locator %s, stop %s", locator[0], stopHash)
} }
@ -281,73 +281,73 @@ func sanitizeString(str string, maxLength uint) string {
// messageSummary returns a human-readable string which summarizes a message. // messageSummary returns a human-readable string which summarizes a message.
// Not all messages have or need a summary. This is used for debug logging. // Not all messages have or need a summary. This is used for debug logging.
func messageSummary(msg btcwire.Message) string { func messageSummary(msg wire.Message) string {
switch msg := msg.(type) { switch msg := msg.(type) {
case *btcwire.MsgVersion: case *wire.MsgVersion:
return fmt.Sprintf("agent %s, pver %d, block %d", return fmt.Sprintf("agent %s, pver %d, block %d",
msg.UserAgent, msg.ProtocolVersion, msg.LastBlock) msg.UserAgent, msg.ProtocolVersion, msg.LastBlock)
case *btcwire.MsgVerAck: case *wire.MsgVerAck:
// No summary. // No summary.
case *btcwire.MsgGetAddr: case *wire.MsgGetAddr:
// No summary. // No summary.
case *btcwire.MsgAddr: case *wire.MsgAddr:
return fmt.Sprintf("%d addr", len(msg.AddrList)) return fmt.Sprintf("%d addr", len(msg.AddrList))
case *btcwire.MsgPing: case *wire.MsgPing:
// No summary - perhaps add nonce. // No summary - perhaps add nonce.
case *btcwire.MsgPong: case *wire.MsgPong:
// No summary - perhaps add nonce. // No summary - perhaps add nonce.
case *btcwire.MsgAlert: case *wire.MsgAlert:
// No summary. // No summary.
case *btcwire.MsgMemPool: case *wire.MsgMemPool:
// No summary. // No summary.
case *btcwire.MsgTx: case *wire.MsgTx:
hash, _ := msg.TxSha() hash, _ := msg.TxSha()
return fmt.Sprintf("hash %s, %d inputs, %d outputs, lock %s", return fmt.Sprintf("hash %s, %d inputs, %d outputs, lock %s",
hash, len(msg.TxIn), len(msg.TxOut), hash, len(msg.TxIn), len(msg.TxOut),
formatLockTime(msg.LockTime)) formatLockTime(msg.LockTime))
case *btcwire.MsgBlock: case *wire.MsgBlock:
header := &msg.Header header := &msg.Header
hash, _ := msg.BlockSha() hash, _ := msg.BlockSha()
return fmt.Sprintf("hash %s, ver %d, %d tx, %s", hash, return fmt.Sprintf("hash %s, ver %d, %d tx, %s", hash,
header.Version, len(msg.Transactions), header.Timestamp) header.Version, len(msg.Transactions), header.Timestamp)
case *btcwire.MsgInv: case *wire.MsgInv:
return invSummary(msg.InvList) return invSummary(msg.InvList)
case *btcwire.MsgNotFound: case *wire.MsgNotFound:
return invSummary(msg.InvList) return invSummary(msg.InvList)
case *btcwire.MsgGetData: case *wire.MsgGetData:
return invSummary(msg.InvList) return invSummary(msg.InvList)
case *btcwire.MsgGetBlocks: case *wire.MsgGetBlocks:
return locatorSummary(msg.BlockLocatorHashes, &msg.HashStop) return locatorSummary(msg.BlockLocatorHashes, &msg.HashStop)
case *btcwire.MsgGetHeaders: case *wire.MsgGetHeaders:
return locatorSummary(msg.BlockLocatorHashes, &msg.HashStop) return locatorSummary(msg.BlockLocatorHashes, &msg.HashStop)
case *btcwire.MsgHeaders: case *wire.MsgHeaders:
return fmt.Sprintf("num %d", len(msg.Headers)) return fmt.Sprintf("num %d", len(msg.Headers))
case *btcwire.MsgReject: case *wire.MsgReject:
// Ensure the variable length strings don't contain any // Ensure the variable length strings don't contain any
// characters which are even remotely dangerous such as HTML // characters which are even remotely dangerous such as HTML
// control characters, etc. Also limit them to sane length for // control characters, etc. Also limit them to sane length for
// logging. // logging.
rejCommand := sanitizeString(msg.Cmd, btcwire.CommandSize) rejCommand := sanitizeString(msg.Cmd, wire.CommandSize)
rejReason := sanitizeString(msg.Reason, maxRejectReasonLen) rejReason := sanitizeString(msg.Reason, maxRejectReasonLen)
summary := fmt.Sprintf("cmd %v, code %v, reason %v", rejCommand, summary := fmt.Sprintf("cmd %v, code %v, reason %v", rejCommand,
msg.Code, rejReason) msg.Code, rejReason)
if rejCommand == btcwire.CmdBlock || rejCommand == btcwire.CmdTx { if rejCommand == wire.CmdBlock || rejCommand == wire.CmdTx {
summary += fmt.Sprintf(", hash %v", msg.Hash) summary += fmt.Sprintf(", hash %v", msg.Hash)
} }
return summary return summary

View file

@ -16,8 +16,8 @@ import (
"github.com/btcsuite/btcd/blockchain" "github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcd/txscript" "github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
) )
const ( const (
@ -29,7 +29,7 @@ const (
// that can be queued. At the time this comment was written, this // that can be queued. At the time this comment was written, this
// equates to 10,000 transactions, but will increase if the max allowed // equates to 10,000 transactions, but will increase if the max allowed
// block payload increases. // block payload increases.
maxOrphanTransactions = btcwire.MaxBlockPayload / 100 maxOrphanTransactions = wire.MaxBlockPayload / 100
// maxOrphanTxSize is the maximum size allowed for orphan transactions. // maxOrphanTxSize is the maximum size allowed for orphan transactions.
// This helps prevent memory exhaustion attacks from sending a lot of // This helps prevent memory exhaustion attacks from sending a lot of
@ -94,10 +94,10 @@ type TxDesc struct {
type txMemPool struct { type txMemPool struct {
sync.RWMutex sync.RWMutex
server *server server *server
pool map[btcwire.ShaHash]*TxDesc pool map[wire.ShaHash]*TxDesc
orphans map[btcwire.ShaHash]*btcutil.Tx orphans map[wire.ShaHash]*btcutil.Tx
orphansByPrev map[btcwire.ShaHash]*list.List orphansByPrev map[wire.ShaHash]*list.List
outpoints map[btcwire.OutPoint]*btcutil.Tx outpoints map[wire.OutPoint]*btcutil.Tx
lastUpdated time.Time // last time pool was updated lastUpdated time.Time // last time pool was updated
pennyTotal float64 // exponentially decaying total for penny spends. pennyTotal float64 // exponentially decaying total for penny spends.
lastPennyUnix int64 // unix time of last ``penny spend'' lastPennyUnix int64 // unix time of last ``penny spend''
@ -107,7 +107,7 @@ type txMemPool struct {
// considered dust or not. Dust is defined in terms of the minimum transaction // considered dust or not. Dust is defined in terms of the minimum transaction
// relay fee. In particular, if the cost to the network to spend coins is more // relay fee. In particular, if the cost to the network to spend coins is more
// than 1/3 of the minimum transaction relay fee, it is considered dust. // than 1/3 of the minimum transaction relay fee, it is considered dust.
func isDust(txOut *btcwire.TxOut) bool { func isDust(txOut *wire.TxOut) bool {
// The total serialized size consists of the output and the associated // The total serialized size consists of the output and the associated
// input script to redeem it. Since there is no input script // input script to redeem it. Since there is no input script
// to redeem it yet, use the minimum size of a typical input script. // to redeem it yet, use the minimum size of a typical input script.
@ -179,38 +179,38 @@ func checkPkScriptStandard(pkScript []byte, scriptClass txscript.ScriptClass) er
if err != nil { if err != nil {
str := fmt.Sprintf("multi-signature script parse "+ str := fmt.Sprintf("multi-signature script parse "+
"failure: %v", err) "failure: %v", err)
return txRuleError(btcwire.RejectNonstandard, str) return txRuleError(wire.RejectNonstandard, str)
} }
// A standard multi-signature public key script must contain // A standard multi-signature public key script must contain
// from 1 to maxStandardMultiSigKeys public keys. // from 1 to maxStandardMultiSigKeys public keys.
if numPubKeys < 1 { if numPubKeys < 1 {
str := "multi-signature script with no pubkeys" str := "multi-signature script with no pubkeys"
return txRuleError(btcwire.RejectNonstandard, str) return txRuleError(wire.RejectNonstandard, str)
} }
if numPubKeys > maxStandardMultiSigKeys { if numPubKeys > maxStandardMultiSigKeys {
str := fmt.Sprintf("multi-signature script with %d "+ str := fmt.Sprintf("multi-signature script with %d "+
"public keys which is more than the allowed "+ "public keys which is more than the allowed "+
"max of %d", numPubKeys, maxStandardMultiSigKeys) "max of %d", numPubKeys, maxStandardMultiSigKeys)
return txRuleError(btcwire.RejectNonstandard, str) return txRuleError(wire.RejectNonstandard, str)
} }
// A standard multi-signature public key script must have at // A standard multi-signature public key script must have at
// least 1 signature and no more signatures than available // least 1 signature and no more signatures than available
// public keys. // public keys.
if numSigs < 1 { if numSigs < 1 {
return txRuleError(btcwire.RejectNonstandard, return txRuleError(wire.RejectNonstandard,
"multi-signature script with no signatures") "multi-signature script with no signatures")
} }
if numSigs > numPubKeys { if numSigs > numPubKeys {
str := fmt.Sprintf("multi-signature script with %d "+ str := fmt.Sprintf("multi-signature script with %d "+
"signatures which is more than the available "+ "signatures which is more than the available "+
"%d public keys", numSigs, numPubKeys) "%d public keys", numSigs, numPubKeys)
return txRuleError(btcwire.RejectNonstandard, str) return txRuleError(wire.RejectNonstandard, str)
} }
case txscript.NonStandardTy: case txscript.NonStandardTy:
return txRuleError(btcwire.RejectNonstandard, return txRuleError(wire.RejectNonstandard,
"non-standard script form") "non-standard script form")
} }
@ -228,17 +228,17 @@ func checkTransactionStandard(tx *btcutil.Tx, height int64) error {
msgTx := tx.MsgTx() msgTx := tx.MsgTx()
// The transaction must be a currently supported version. // The transaction must be a currently supported version.
if msgTx.Version > btcwire.TxVersion || msgTx.Version < 1 { if msgTx.Version > wire.TxVersion || msgTx.Version < 1 {
str := fmt.Sprintf("transaction version %d is not in the "+ str := fmt.Sprintf("transaction version %d is not in the "+
"valid range of %d-%d", msgTx.Version, 1, "valid range of %d-%d", msgTx.Version, 1,
btcwire.TxVersion) wire.TxVersion)
return txRuleError(btcwire.RejectNonstandard, str) return txRuleError(wire.RejectNonstandard, str)
} }
// The transaction must be finalized to be standard and therefore // The transaction must be finalized to be standard and therefore
// considered for inclusion in a block. // considered for inclusion in a block.
if !blockchain.IsFinalizedTransaction(tx, height, time.Now()) { if !blockchain.IsFinalizedTransaction(tx, height, time.Now()) {
return txRuleError(btcwire.RejectNonstandard, return txRuleError(wire.RejectNonstandard,
"transaction is not finalized") "transaction is not finalized")
} }
@ -250,7 +250,7 @@ func checkTransactionStandard(tx *btcutil.Tx, height int64) error {
if serializedLen > maxStandardTxSize { if serializedLen > maxStandardTxSize {
str := fmt.Sprintf("transaction size of %v is larger than max "+ str := fmt.Sprintf("transaction size of %v is larger than max "+
"allowed size of %v", serializedLen, maxStandardTxSize) "allowed size of %v", serializedLen, maxStandardTxSize)
return txRuleError(btcwire.RejectNonstandard, str) return txRuleError(wire.RejectNonstandard, str)
} }
for i, txIn := range msgTx.TxIn { for i, txIn := range msgTx.TxIn {
@ -263,7 +263,7 @@ func checkTransactionStandard(tx *btcutil.Tx, height int64) error {
"script size of %d bytes is large than max "+ "script size of %d bytes is large than max "+
"allowed size of %d bytes", i, sigScriptLen, "allowed size of %d bytes", i, sigScriptLen,
maxStandardSigScriptSize) maxStandardSigScriptSize)
return txRuleError(btcwire.RejectNonstandard, str) return txRuleError(wire.RejectNonstandard, str)
} }
// Each transaction input signature script must only contain // Each transaction input signature script must only contain
@ -271,7 +271,7 @@ func checkTransactionStandard(tx *btcutil.Tx, height int64) error {
if !txscript.IsPushOnlyScript(txIn.SignatureScript) { if !txscript.IsPushOnlyScript(txIn.SignatureScript) {
str := fmt.Sprintf("transaction input %d: signature "+ str := fmt.Sprintf("transaction input %d: signature "+
"script is not push only", i) "script is not push only", i)
return txRuleError(btcwire.RejectNonstandard, str) return txRuleError(wire.RejectNonstandard, str)
} }
// Each transaction input signature script must only contain // Each transaction input signature script must only contain
@ -281,7 +281,7 @@ func checkTransactionStandard(tx *btcutil.Tx, height int64) error {
if !txscript.HasCanonicalPushes(txIn.SignatureScript) { if !txscript.HasCanonicalPushes(txIn.SignatureScript) {
str := fmt.Sprintf("transaction input %d: signature "+ str := fmt.Sprintf("transaction input %d: signature "+
"script has a non-canonical data push", i) "script has a non-canonical data push", i)
return txRuleError(btcwire.RejectNonstandard, str) return txRuleError(wire.RejectNonstandard, str)
} }
} }
@ -297,7 +297,7 @@ func checkTransactionStandard(tx *btcutil.Tx, height int64) error {
// a non standard error. // a non standard error.
rejectCode, found := extractRejectCode(err) rejectCode, found := extractRejectCode(err)
if !found { if !found {
rejectCode = btcwire.RejectNonstandard rejectCode = wire.RejectNonstandard
} }
str := fmt.Sprintf("transaction output %d: %v", i, err) str := fmt.Sprintf("transaction output %d: %v", i, err)
return txRuleError(rejectCode, str) return txRuleError(rejectCode, str)
@ -311,7 +311,7 @@ func checkTransactionStandard(tx *btcutil.Tx, height int64) error {
} else if isDust(txOut) { } else if isDust(txOut) {
str := fmt.Sprintf("transaction output %d: payment "+ str := fmt.Sprintf("transaction output %d: payment "+
"of %d is dust", i, txOut.Value) "of %d is dust", i, txOut.Value)
return txRuleError(btcwire.RejectDust, str) return txRuleError(wire.RejectDust, str)
} }
} }
@ -319,7 +319,7 @@ func checkTransactionStandard(tx *btcutil.Tx, height int64) error {
// only carries data. // only carries data.
if numNullDataOutputs > 1 { if numNullDataOutputs > 1 {
str := "more than one transaction output in a nulldata script" str := "more than one transaction output in a nulldata script"
return txRuleError(btcwire.RejectNonstandard, str) return txRuleError(wire.RejectNonstandard, str)
} }
return nil return nil
@ -351,7 +351,7 @@ func checkInputsStandard(tx *btcutil.Tx, txStore blockchain.TxStore) error {
if err != nil { if err != nil {
str := fmt.Sprintf("transaction input #%d script parse "+ str := fmt.Sprintf("transaction input #%d script parse "+
"failure: %v", i, err) "failure: %v", i, err)
return txRuleError(btcwire.RejectNonstandard, str) return txRuleError(wire.RejectNonstandard, str)
} }
// A negative value for expected inputs indicates the script is // A negative value for expected inputs indicates the script is
@ -359,7 +359,7 @@ func checkInputsStandard(tx *btcutil.Tx, txStore blockchain.TxStore) error {
if scriptInfo.ExpectedInputs < 0 { if scriptInfo.ExpectedInputs < 0 {
str := fmt.Sprintf("transaction input #%d expects %d "+ str := fmt.Sprintf("transaction input #%d expects %d "+
"inputs", i, scriptInfo.ExpectedInputs) "inputs", i, scriptInfo.ExpectedInputs)
return txRuleError(btcwire.RejectNonstandard, str) return txRuleError(wire.RejectNonstandard, str)
} }
// The script pair is non-standard if the number of available // The script pair is non-standard if the number of available
@ -369,7 +369,7 @@ func checkInputsStandard(tx *btcutil.Tx, txStore blockchain.TxStore) error {
"inputs, but referenced output script provides "+ "inputs, but referenced output script provides "+
"%d", i, scriptInfo.ExpectedInputs, "%d", i, scriptInfo.ExpectedInputs,
scriptInfo.NumInputs) scriptInfo.NumInputs)
return txRuleError(btcwire.RejectNonstandard, str) return txRuleError(wire.RejectNonstandard, str)
} }
} }
@ -400,7 +400,7 @@ func calcMinRequiredTxRelayFee(serializedSize int64) int64 {
// removeOrphan is the internal function which implements the public // removeOrphan is the internal function which implements the public
// RemoveOrphan. See the comment for RemoveOrphan for more details. // RemoveOrphan. See the comment for RemoveOrphan for more details.
// This function MUST be called with the mempool lock held (for writes). // This function MUST be called with the mempool lock held (for writes).
func (mp *txMemPool) removeOrphan(txHash *btcwire.ShaHash) { func (mp *txMemPool) removeOrphan(txHash *wire.ShaHash) {
// Nothing to do if passed tx is not an orphan. // Nothing to do if passed tx is not an orphan.
tx, exists := mp.orphans[*txHash] tx, exists := mp.orphans[*txHash]
if !exists { if !exists {
@ -433,7 +433,7 @@ func (mp *txMemPool) removeOrphan(txHash *btcwire.ShaHash) {
// RemoveOrphan removes the passed orphan transaction from the orphan pool and // RemoveOrphan removes the passed orphan transaction from the orphan pool and
// previous orphan index. // previous orphan index.
// This function is safe for concurrent access. // This function is safe for concurrent access.
func (mp *txMemPool) RemoveOrphan(txHash *btcwire.ShaHash) { func (mp *txMemPool) RemoveOrphan(txHash *wire.ShaHash) {
mp.Lock() mp.Lock()
mp.removeOrphan(txHash) mp.removeOrphan(txHash)
mp.Unlock() mp.Unlock()
@ -446,7 +446,7 @@ func (mp *txMemPool) RemoveOrphan(txHash *btcwire.ShaHash) {
func (mp *txMemPool) limitNumOrphans() error { func (mp *txMemPool) limitNumOrphans() error {
if len(mp.orphans)+1 > maxOrphanTransactions { if len(mp.orphans)+1 > maxOrphanTransactions {
// Generate a cryptographically random hash. // Generate a cryptographically random hash.
randHashBytes := make([]byte, btcwire.HashSize) randHashBytes := make([]byte, wire.HashSize)
_, err := rand.Read(randHashBytes) _, err := rand.Read(randHashBytes)
if err != nil { if err != nil {
return err return err
@ -458,7 +458,7 @@ func (mp *txMemPool) limitNumOrphans() error {
// to Go's range statement over maps) as a fallback if none of // to Go's range statement over maps) as a fallback if none of
// the hashes in the orphan pool are larger than the random // the hashes in the orphan pool are larger than the random
// hash. // hash.
var foundHash *btcwire.ShaHash var foundHash *wire.ShaHash
for txHash := range mp.orphans { for txHash := range mp.orphans {
if foundHash == nil { if foundHash == nil {
foundHash = &txHash foundHash = &txHash
@ -516,7 +516,7 @@ func (mp *txMemPool) maybeAddOrphan(tx *btcutil.Tx) error {
str := fmt.Sprintf("orphan transaction size of %d bytes is "+ str := fmt.Sprintf("orphan transaction size of %d bytes is "+
"larger than max allowed size of %d bytes", "larger than max allowed size of %d bytes",
serializedLen, maxOrphanTxSize) serializedLen, maxOrphanTxSize)
return txRuleError(btcwire.RejectNonstandard, str) return txRuleError(wire.RejectNonstandard, str)
} }
// Add the orphan if the none of the above disqualified it. // Add the orphan if the none of the above disqualified it.
@ -529,7 +529,7 @@ func (mp *txMemPool) maybeAddOrphan(tx *btcutil.Tx) error {
// exists in the main pool. // exists in the main pool.
// //
// This function MUST be called with the mempool lock held (for reads). // This function MUST be called with the mempool lock held (for reads).
func (mp *txMemPool) isTransactionInPool(hash *btcwire.ShaHash) bool { func (mp *txMemPool) isTransactionInPool(hash *wire.ShaHash) bool {
if _, exists := mp.pool[*hash]; exists { if _, exists := mp.pool[*hash]; exists {
return true return true
} }
@ -541,7 +541,7 @@ func (mp *txMemPool) isTransactionInPool(hash *btcwire.ShaHash) bool {
// exists in the main pool. // exists in the main pool.
// //
// This function is safe for concurrent access. // This function is safe for concurrent access.
func (mp *txMemPool) IsTransactionInPool(hash *btcwire.ShaHash) bool { func (mp *txMemPool) IsTransactionInPool(hash *wire.ShaHash) bool {
// Protect concurrent access. // Protect concurrent access.
mp.RLock() mp.RLock()
defer mp.RUnlock() defer mp.RUnlock()
@ -553,7 +553,7 @@ func (mp *txMemPool) IsTransactionInPool(hash *btcwire.ShaHash) bool {
// in the orphan pool. // in the orphan pool.
// //
// This function MUST be called with the mempool lock held (for reads). // This function MUST be called with the mempool lock held (for reads).
func (mp *txMemPool) isOrphanInPool(hash *btcwire.ShaHash) bool { func (mp *txMemPool) isOrphanInPool(hash *wire.ShaHash) bool {
if _, exists := mp.orphans[*hash]; exists { if _, exists := mp.orphans[*hash]; exists {
return true return true
} }
@ -565,7 +565,7 @@ func (mp *txMemPool) isOrphanInPool(hash *btcwire.ShaHash) bool {
// in the orphan pool. // in the orphan pool.
// //
// This function is safe for concurrent access. // This function is safe for concurrent access.
func (mp *txMemPool) IsOrphanInPool(hash *btcwire.ShaHash) bool { func (mp *txMemPool) IsOrphanInPool(hash *wire.ShaHash) bool {
// Protect concurrent access. // Protect concurrent access.
mp.RLock() mp.RLock()
defer mp.RUnlock() defer mp.RUnlock()
@ -577,7 +577,7 @@ func (mp *txMemPool) IsOrphanInPool(hash *btcwire.ShaHash) bool {
// in the main pool or in the orphan pool. // in the main pool or in the orphan pool.
// //
// This function MUST be called with the mempool lock held (for reads). // This function MUST be called with the mempool lock held (for reads).
func (mp *txMemPool) haveTransaction(hash *btcwire.ShaHash) bool { func (mp *txMemPool) haveTransaction(hash *wire.ShaHash) bool {
return mp.isTransactionInPool(hash) || mp.isOrphanInPool(hash) return mp.isTransactionInPool(hash) || mp.isOrphanInPool(hash)
} }
@ -585,7 +585,7 @@ func (mp *txMemPool) haveTransaction(hash *btcwire.ShaHash) bool {
// in the main pool or in the orphan pool. // in the main pool or in the orphan pool.
// //
// This function is safe for concurrent access. // This function is safe for concurrent access.
func (mp *txMemPool) HaveTransaction(hash *btcwire.ShaHash) bool { func (mp *txMemPool) HaveTransaction(hash *wire.ShaHash) bool {
// Protect concurrent access. // Protect concurrent access.
mp.RLock() mp.RLock()
defer mp.RUnlock() defer mp.RUnlock()
@ -601,7 +601,7 @@ func (mp *txMemPool) removeTransaction(tx *btcutil.Tx) {
// Remove any transactions which rely on this one. // Remove any transactions which rely on this one.
txHash := tx.Sha() txHash := tx.Sha()
for i := uint32(0); i < uint32(len(tx.MsgTx().TxOut)); i++ { for i := uint32(0); i < uint32(len(tx.MsgTx().TxOut)); i++ {
outpoint := btcwire.NewOutPoint(txHash, i) outpoint := wire.NewOutPoint(txHash, i)
if txRedeemer, exists := mp.outpoints[*outpoint]; exists { if txRedeemer, exists := mp.outpoints[*outpoint]; exists {
mp.removeTransaction(txRedeemer) mp.removeTransaction(txRedeemer)
} }
@ -744,7 +744,7 @@ func (mp *txMemPool) checkPoolDoubleSpend(tx *btcutil.Tx) error {
str := fmt.Sprintf("output %v already spent by "+ str := fmt.Sprintf("output %v already spent by "+
"transaction %v in the memory pool", "transaction %v in the memory pool",
txIn.PreviousOutPoint, txR.Sha()) txIn.PreviousOutPoint, txR.Sha())
return txRuleError(btcwire.RejectDuplicate, str) return txRuleError(wire.RejectDuplicate, str)
} }
} }
@ -783,7 +783,7 @@ func (mp *txMemPool) fetchInputTransactions(tx *btcutil.Tx) (blockchain.TxStore,
// orphans. // orphans.
// //
// This function is safe for concurrent access. // This function is safe for concurrent access.
func (mp *txMemPool) FetchTransaction(txHash *btcwire.ShaHash) (*btcutil.Tx, error) { func (mp *txMemPool) FetchTransaction(txHash *wire.ShaHash) (*btcutil.Tx, error) {
// Protect concurrent access. // Protect concurrent access.
mp.RLock() mp.RLock()
defer mp.RUnlock() defer mp.RUnlock()
@ -800,7 +800,7 @@ func (mp *txMemPool) FetchTransaction(txHash *btcwire.ShaHash) (*btcutil.Tx, err
// more details. // more details.
// //
// This function MUST be called with the mempool lock held (for writes). // This function MUST be called with the mempool lock held (for writes).
func (mp *txMemPool) maybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit bool) ([]*btcwire.ShaHash, error) { func (mp *txMemPool) maybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit bool) ([]*wire.ShaHash, error) {
txHash := tx.Sha() txHash := tx.Sha()
// Don't accept the transaction if it already exists in the pool. This // Don't accept the transaction if it already exists in the pool. This
@ -808,7 +808,7 @@ func (mp *txMemPool) maybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit boo
// be a quick check to weed out duplicates. // be a quick check to weed out duplicates.
if mp.haveTransaction(txHash) { if mp.haveTransaction(txHash) {
str := fmt.Sprintf("already have transaction %v", txHash) str := fmt.Sprintf("already have transaction %v", txHash)
return nil, txRuleError(btcwire.RejectDuplicate, str) return nil, txRuleError(wire.RejectDuplicate, str)
} }
// Perform preliminary sanity checks on the transaction. This makes // Perform preliminary sanity checks on the transaction. This makes
@ -826,7 +826,7 @@ func (mp *txMemPool) maybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit boo
if blockchain.IsCoinBase(tx) { if blockchain.IsCoinBase(tx) {
str := fmt.Sprintf("transaction %v is an individual coinbase", str := fmt.Sprintf("transaction %v is an individual coinbase",
txHash) txHash)
return nil, txRuleError(btcwire.RejectInvalid, str) return nil, txRuleError(wire.RejectInvalid, str)
} }
// Don't accept transactions with a lock time after the maximum int32 // Don't accept transactions with a lock time after the maximum int32
@ -836,7 +836,7 @@ func (mp *txMemPool) maybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit boo
if tx.MsgTx().LockTime > math.MaxInt32 { if tx.MsgTx().LockTime > math.MaxInt32 {
str := fmt.Sprintf("transaction %v has a lock time after "+ str := fmt.Sprintf("transaction %v has a lock time after "+
"2038 which is not accepted yet", txHash) "2038 which is not accepted yet", txHash)
return nil, txRuleError(btcwire.RejectNonstandard, str) return nil, txRuleError(wire.RejectNonstandard, str)
} }
// Get the current height of the main chain. A standalone transaction // Get the current height of the main chain. A standalone transaction
@ -860,7 +860,7 @@ func (mp *txMemPool) maybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit boo
// a non standard error. // a non standard error.
rejectCode, found := extractRejectCode(err) rejectCode, found := extractRejectCode(err)
if !found { if !found {
rejectCode = btcwire.RejectNonstandard rejectCode = wire.RejectNonstandard
} }
str := fmt.Sprintf("transaction %v is not standard: %v", str := fmt.Sprintf("transaction %v is not standard: %v",
txHash, err) txHash, err)
@ -898,7 +898,7 @@ func (mp *txMemPool) maybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit boo
if txD, exists := txStore[*txHash]; exists && txD.Err == nil { if txD, exists := txStore[*txHash]; exists && txD.Err == nil {
for _, isOutputSpent := range txD.Spent { for _, isOutputSpent := range txD.Spent {
if !isOutputSpent { if !isOutputSpent {
return nil, txRuleError(btcwire.RejectDuplicate, return nil, txRuleError(wire.RejectDuplicate,
"transaction already exists") "transaction already exists")
} }
} }
@ -909,7 +909,7 @@ func (mp *txMemPool) maybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit boo
// don't exist. Adding orphans to the orphan pool is not handled by // don't exist. Adding orphans to the orphan pool is not handled by
// this function, and the caller should use maybeAddOrphan if this // this function, and the caller should use maybeAddOrphan if this
// behavior is desired. // behavior is desired.
var missingParents []*btcwire.ShaHash var missingParents []*wire.ShaHash
for _, txD := range txStore { for _, txD := range txStore {
if txD.Err == database.ErrTxShaMissing { if txD.Err == database.ErrTxShaMissing {
missingParents = append(missingParents, txD.Hash) missingParents = append(missingParents, txD.Hash)
@ -941,7 +941,7 @@ func (mp *txMemPool) maybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit boo
// a non standard error. // a non standard error.
rejectCode, found := extractRejectCode(err) rejectCode, found := extractRejectCode(err)
if !found { if !found {
rejectCode = btcwire.RejectNonstandard rejectCode = wire.RejectNonstandard
} }
str := fmt.Sprintf("transaction %v has a non-standard "+ str := fmt.Sprintf("transaction %v has a non-standard "+
"input: %v", txHash, err) "input: %v", txHash, err)
@ -969,7 +969,7 @@ func (mp *txMemPool) maybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit boo
if numSigOps > maxSigOpsPerTx { if numSigOps > maxSigOpsPerTx {
str := fmt.Sprintf("transaction %v has too many sigops: %d > %d", str := fmt.Sprintf("transaction %v has too many sigops: %d > %d",
txHash, numSigOps, maxSigOpsPerTx) txHash, numSigOps, maxSigOpsPerTx)
return nil, txRuleError(btcwire.RejectNonstandard, str) return nil, txRuleError(wire.RejectNonstandard, str)
} }
// Don't allow transactions with fees too low to get into a mined block. // Don't allow transactions with fees too low to get into a mined block.
@ -989,7 +989,7 @@ func (mp *txMemPool) maybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit boo
str := fmt.Sprintf("transaction %v has %d fees which is under "+ str := fmt.Sprintf("transaction %v has %d fees which is under "+
"the required amount of %d", txHash, txFee, "the required amount of %d", txHash, txFee,
minFee) minFee)
return nil, txRuleError(btcwire.RejectInsufficientFee, str) return nil, txRuleError(wire.RejectInsufficientFee, str)
} }
// Free-to-relay transactions are rate limited here to prevent // Free-to-relay transactions are rate limited here to prevent
@ -1006,7 +1006,7 @@ func (mp *txMemPool) maybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit boo
if mp.pennyTotal >= cfg.FreeTxRelayLimit*10*1000 { if mp.pennyTotal >= cfg.FreeTxRelayLimit*10*1000 {
str := fmt.Sprintf("transaction %v has been rejected "+ str := fmt.Sprintf("transaction %v has been rejected "+
"by the rate limiter due to low fees", txHash) "by the rate limiter due to low fees", txHash)
return nil, txRuleError(btcwire.RejectInsufficientFee, str) return nil, txRuleError(wire.RejectInsufficientFee, str)
} }
oldTotal := mp.pennyTotal oldTotal := mp.pennyTotal
@ -1056,7 +1056,7 @@ func (mp *txMemPool) maybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit boo
// be added to the orphan pool. // be added to the orphan pool.
// //
// This function is safe for concurrent access. // This function is safe for concurrent access.
func (mp *txMemPool) MaybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit bool) ([]*btcwire.ShaHash, error) { func (mp *txMemPool) MaybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit bool) ([]*wire.ShaHash, error) {
// Protect concurrent access. // Protect concurrent access.
mp.Lock() mp.Lock()
defer mp.Unlock() defer mp.Unlock()
@ -1071,14 +1071,14 @@ func (mp *txMemPool) MaybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit boo
// orphans) until there are no more. // orphans) until there are no more.
// //
// This function MUST be called with the mempool lock held (for writes). // This function MUST be called with the mempool lock held (for writes).
func (mp *txMemPool) processOrphans(hash *btcwire.ShaHash) error { func (mp *txMemPool) processOrphans(hash *wire.ShaHash) error {
// Start with processing at least the passed hash. // Start with processing at least the passed hash.
processHashes := list.New() processHashes := list.New()
processHashes.PushBack(hash) processHashes.PushBack(hash)
for processHashes.Len() > 0 { for processHashes.Len() > 0 {
// Pop the first hash to process. // Pop the first hash to process.
firstElement := processHashes.Remove(processHashes.Front()) firstElement := processHashes.Remove(processHashes.Front())
processHash := firstElement.(*btcwire.ShaHash) processHash := firstElement.(*wire.ShaHash)
// Look up all orphans that are referenced by the transaction we // Look up all orphans that are referenced by the transaction we
// just accepted. This will typically only be one, but it could // just accepted. This will typically only be one, but it could
@ -1122,7 +1122,7 @@ func (mp *txMemPool) processOrphans(hash *btcwire.ShaHash) error {
if len(missingParents) == 0 { if len(missingParents) == 0 {
// Generate and relay the inventory vector for the // Generate and relay the inventory vector for the
// newly accepted transaction. // newly accepted transaction.
iv := btcwire.NewInvVect(btcwire.InvTypeTx, tx.Sha()) iv := wire.NewInvVect(wire.InvTypeTx, tx.Sha())
mp.server.RelayInventory(iv, tx) mp.server.RelayInventory(iv, tx)
} else { } else {
// Transaction is still an orphan. // Transaction is still an orphan.
@ -1174,7 +1174,7 @@ func (mp *txMemPool) ProcessTransaction(tx *btcutil.Tx, allowOrphan, rateLimit b
if len(missingParents) == 0 { if len(missingParents) == 0 {
// Generate the inventory vector and relay it. // Generate the inventory vector and relay it.
iv := btcwire.NewInvVect(btcwire.InvTypeTx, tx.Sha()) iv := wire.NewInvVect(wire.InvTypeTx, tx.Sha())
mp.server.RelayInventory(iv, tx) mp.server.RelayInventory(iv, tx)
// Accept any orphan transactions that depend on this // Accept any orphan transactions that depend on this
@ -1201,7 +1201,7 @@ func (mp *txMemPool) ProcessTransaction(tx *btcutil.Tx, allowOrphan, rateLimit b
str := fmt.Sprintf("orphan transaction %v references "+ str := fmt.Sprintf("orphan transaction %v references "+
"outputs of unknown or fully-spent "+ "outputs of unknown or fully-spent "+
"transaction %v", tx.Sha(), missingParents[0]) "transaction %v", tx.Sha(), missingParents[0])
return txRuleError(btcwire.RejectDuplicate, str) return txRuleError(wire.RejectDuplicate, str)
} }
// Potentially add the orphan transaction to the orphan pool. // Potentially add the orphan transaction to the orphan pool.
@ -1229,11 +1229,11 @@ func (mp *txMemPool) Count() int {
// pool. // pool.
// //
// This function is safe for concurrent access. // This function is safe for concurrent access.
func (mp *txMemPool) TxShas() []*btcwire.ShaHash { func (mp *txMemPool) TxShas() []*wire.ShaHash {
mp.RLock() mp.RLock()
defer mp.RUnlock() defer mp.RUnlock()
hashes := make([]*btcwire.ShaHash, len(mp.pool)) hashes := make([]*wire.ShaHash, len(mp.pool))
i := 0 i := 0
for hash := range mp.pool { for hash := range mp.pool {
hashCopy := hash hashCopy := hash
@ -1278,9 +1278,9 @@ func (mp *txMemPool) LastUpdated() time.Time {
func newTxMemPool(server *server) *txMemPool { func newTxMemPool(server *server) *txMemPool {
return &txMemPool{ return &txMemPool{
server: server, server: server,
pool: make(map[btcwire.ShaHash]*TxDesc), pool: make(map[wire.ShaHash]*TxDesc),
orphans: make(map[btcwire.ShaHash]*btcutil.Tx), orphans: make(map[wire.ShaHash]*btcutil.Tx),
orphansByPrev: make(map[btcwire.ShaHash]*list.List), orphansByPrev: make(map[wire.ShaHash]*list.List),
outpoints: make(map[btcwire.OutPoint]*btcutil.Tx), outpoints: make(map[wire.OutPoint]*btcutil.Tx),
} }
} }

View file

@ -6,7 +6,7 @@ package main
import ( import (
"github.com/btcsuite/btcd/blockchain" "github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcwire" "github.com/btcsuite/btcd/wire"
) )
// RuleError identifies a rule violation. It is used to indicate that // RuleError identifies a rule violation. It is used to indicate that
@ -33,8 +33,8 @@ func (e RuleError) Error() string {
// specifically due to a rule violation and access the ErrorCode field to // specifically due to a rule violation and access the ErrorCode field to
// ascertain the specific reason for the rule violation. // ascertain the specific reason for the rule violation.
type TxRuleError struct { type TxRuleError struct {
RejectCode btcwire.RejectCode // The code to send with reject messages RejectCode wire.RejectCode // The code to send with reject messages
Description string // Human readable description of the issue Description string // Human readable description of the issue
} }
// Error satisfies the error interface and prints human-readable errors. // Error satisfies the error interface and prints human-readable errors.
@ -44,7 +44,7 @@ func (e TxRuleError) Error() string {
// txRuleError creates an underlying TxRuleError with the given a set of // txRuleError creates an underlying TxRuleError with the given a set of
// arguments and returns a RuleError that encapsulates it. // arguments and returns a RuleError that encapsulates it.
func txRuleError(c btcwire.RejectCode, desc string) RuleError { func txRuleError(c wire.RejectCode, desc string) RuleError {
return RuleError{ return RuleError{
Err: TxRuleError{RejectCode: c, Description: desc}, Err: TxRuleError{RejectCode: c, Description: desc},
} }
@ -61,7 +61,7 @@ func chainRuleError(chainErr blockchain.RuleError) RuleError {
// extractRejectCode attempts to return a relevant reject code for a given error // extractRejectCode attempts to return a relevant reject code for a given error
// by examining the error for known types. It will return true if a code // by examining the error for known types. It will return true if a code
// was successfully extracted. // was successfully extracted.
func extractRejectCode(err error) (btcwire.RejectCode, bool) { func extractRejectCode(err error) (wire.RejectCode, bool) {
// Pull the underlying error out of a RuleError. // Pull the underlying error out of a RuleError.
if rerr, ok := err.(RuleError); ok { if rerr, ok := err.(RuleError); ok {
err = rerr.Err err = rerr.Err
@ -70,17 +70,17 @@ func extractRejectCode(err error) (btcwire.RejectCode, bool) {
switch err := err.(type) { switch err := err.(type) {
case blockchain.RuleError: case blockchain.RuleError:
// Convert the chain error to a reject code. // Convert the chain error to a reject code.
var code btcwire.RejectCode var code wire.RejectCode
switch err.ErrorCode { switch err.ErrorCode {
// Rejected due to duplicate. // Rejected due to duplicate.
case blockchain.ErrDuplicateBlock: case blockchain.ErrDuplicateBlock:
fallthrough fallthrough
case blockchain.ErrDoubleSpend: case blockchain.ErrDoubleSpend:
code = btcwire.RejectDuplicate code = wire.RejectDuplicate
// Rejected due to obsolete version. // Rejected due to obsolete version.
case blockchain.ErrBlockVersionTooOld: case blockchain.ErrBlockVersionTooOld:
code = btcwire.RejectObsolete code = wire.RejectObsolete
// Rejected due to checkpoint. // Rejected due to checkpoint.
case blockchain.ErrCheckpointTimeTooOld: case blockchain.ErrCheckpointTimeTooOld:
@ -90,11 +90,11 @@ func extractRejectCode(err error) (btcwire.RejectCode, bool) {
case blockchain.ErrBadCheckpoint: case blockchain.ErrBadCheckpoint:
fallthrough fallthrough
case blockchain.ErrForkTooOld: case blockchain.ErrForkTooOld:
code = btcwire.RejectCheckpoint code = wire.RejectCheckpoint
// Everything else is due to the block or transaction being invalid. // Everything else is due to the block or transaction being invalid.
default: default:
code = btcwire.RejectInvalid code = wire.RejectInvalid
} }
return code, true return code, true
@ -103,15 +103,15 @@ func extractRejectCode(err error) (btcwire.RejectCode, bool) {
return err.RejectCode, true return err.RejectCode, true
case nil: case nil:
return btcwire.RejectInvalid, false return wire.RejectInvalid, false
} }
return btcwire.RejectInvalid, false return wire.RejectInvalid, false
} }
// errToRejectErr examines the underlying type of the error and returns a reject // errToRejectErr examines the underlying type of the error and returns a reject
// code and string appropriate to be sent in a btcwire.MsgReject message. // code and string appropriate to be sent in a wire.MsgReject message.
func errToRejectErr(err error) (btcwire.RejectCode, string) { func errToRejectErr(err error) (wire.RejectCode, string) {
// Return the reject code along with the error text if it can be // Return the reject code along with the error text if it can be
// extracted from the error. // extracted from the error.
rejectCode, found := extractRejectCode(err) rejectCode, found := extractRejectCode(err)
@ -125,11 +125,11 @@ func errToRejectErr(err error) (btcwire.RejectCode, string) {
// string rather than allowing the following code that derferences the // string rather than allowing the following code that derferences the
// err to panic. // err to panic.
if err == nil { if err == nil {
return btcwire.RejectInvalid, "rejected" return wire.RejectInvalid, "rejected"
} }
// When the underlying error is not one of the above cases, just return // When the underlying error is not one of the above cases, just return
// btcwire.RejectInvalid with a generic rejected string plus the error // wire.RejectInvalid with a generic rejected string plus the error
// text. // text.
return btcwire.RejectInvalid, "rejected: " + err.Error() return wire.RejectInvalid, "rejected: " + err.Error()
} }

View file

@ -13,14 +13,14 @@ import (
"github.com/btcsuite/btcd/blockchain" "github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcd/txscript" "github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
) )
const ( const (
// generatedBlockVersion is the version of the block being generated. // generatedBlockVersion is the version of the block being generated.
// It is defined as a constant here rather than using the // It is defined as a constant here rather than using the
// btcwire.BlockVersion constant since a change in the block version // wire.BlockVersion constant since a change in the block version
// will require changes to the generated block. Using the btcwire // will require changes to the generated block. Using the btcwire
// constant for generated block version could allow creation of invalid // constant for generated block version could allow creation of invalid
// blocks for the updated version. // blocks for the updated version.
@ -32,7 +32,7 @@ const (
// blockHeaderOverhead is the max number of bytes it takes to serialize // blockHeaderOverhead is the max number of bytes it takes to serialize
// a block header and max possible transaction count. // a block header and max possible transaction count.
blockHeaderOverhead = btcwire.MaxBlockHeaderPayload + btcwire.MaxVarIntPayload blockHeaderOverhead = wire.MaxBlockHeaderPayload + wire.MaxVarIntPayload
// coinbaseFlags is added to the coinbase script of a generated block // coinbaseFlags is added to the coinbase script of a generated block
// and is used to monitor BIP16 support as well as blocks that are // and is used to monitor BIP16 support as well as blocks that are
@ -65,7 +65,7 @@ type txPrioItem struct {
// on. It will only be set when the transaction references other // on. It will only be set when the transaction references other
// transactions in the memory pool and hence must come after them in // transactions in the memory pool and hence must come after them in
// a block. // a block.
dependsOn map[btcwire.ShaHash]struct{} dependsOn map[wire.ShaHash]struct{}
} }
// txPriorityQueueLessFunc describes a function that can be used as a compare // txPriorityQueueLessFunc describes a function that can be used as a compare
@ -167,7 +167,7 @@ func newTxPriorityQueue(reserve int, sortByFee bool) *txPriorityQueue {
// details about the fees and the number of signature operations for each // details about the fees and the number of signature operations for each
// transaction in the block. // transaction in the block.
type BlockTemplate struct { type BlockTemplate struct {
block *btcwire.MsgBlock block *wire.MsgBlock
fees []int64 fees []int64
sigOpCounts []int64 sigOpCounts []int64
height int64 height int64
@ -232,16 +232,16 @@ func createCoinbaseTx(coinbaseScript []byte, nextBlockHeight int64, addr btcutil
} }
} }
tx := btcwire.NewMsgTx() tx := wire.NewMsgTx()
tx.AddTxIn(&btcwire.TxIn{ tx.AddTxIn(&wire.TxIn{
// Coinbase transactions have no inputs, so previous outpoint is // Coinbase transactions have no inputs, so previous outpoint is
// zero hash and max index. // zero hash and max index.
PreviousOutPoint: *btcwire.NewOutPoint(&btcwire.ShaHash{}, PreviousOutPoint: *wire.NewOutPoint(&wire.ShaHash{},
btcwire.MaxPrevOutIndex), wire.MaxPrevOutIndex),
SignatureScript: coinbaseScript, SignatureScript: coinbaseScript,
Sequence: btcwire.MaxTxInSequenceNum, Sequence: wire.MaxTxInSequenceNum,
}) })
tx.AddTxOut(&btcwire.TxOut{ tx.AddTxOut(&wire.TxOut{
Value: blockchain.CalcBlockSubsidy(nextBlockHeight, Value: blockchain.CalcBlockSubsidy(nextBlockHeight,
activeNetParams.Params), activeNetParams.Params),
PkScript: pkScript, PkScript: pkScript,
@ -479,7 +479,7 @@ func NewBlockTemplate(mempool *txMemPool, payToAddress btcutil.Address) (*BlockT
// dependsOn map kept with each dependent transaction helps quickly // dependsOn map kept with each dependent transaction helps quickly
// determine which dependent transactions are now eligible for inclusion // determine which dependent transactions are now eligible for inclusion
// in the block once each transaction has been included. // in the block once each transaction has been included.
dependers := make(map[btcwire.ShaHash]*list.List) dependers := make(map[wire.ShaHash]*list.List)
// Create slices to hold the fees and number of signature operations // Create slices to hold the fees and number of signature operations
// for each of the selected transactions and add an entry for the // for each of the selected transactions and add an entry for the
@ -549,7 +549,7 @@ mempoolLoop:
depList.PushBack(prioItem) depList.PushBack(prioItem)
if prioItem.dependsOn == nil { if prioItem.dependsOn == nil {
prioItem.dependsOn = make( prioItem.dependsOn = make(
map[btcwire.ShaHash]struct{}) map[wire.ShaHash]struct{})
} }
prioItem.dependsOn[*originHash] = struct{}{} prioItem.dependsOn[*originHash] = struct{}{}
@ -759,8 +759,8 @@ mempoolLoop:
// Now that the actual transactions have been selected, update the // Now that the actual transactions have been selected, update the
// block size for the real transaction count and coinbase value with // block size for the real transaction count and coinbase value with
// the total fees accordingly. // the total fees accordingly.
blockSize -= btcwire.MaxVarIntPayload - blockSize -= wire.MaxVarIntPayload -
uint32(btcwire.VarIntSerializeSize(uint64(len(blockTxns)))) uint32(wire.VarIntSerializeSize(uint64(len(blockTxns))))
coinbaseTx.MsgTx().TxOut[0].Value += totalFees coinbaseTx.MsgTx().TxOut[0].Value += totalFees
txFees[0] = -totalFees txFees[0] = -totalFees
@ -778,8 +778,8 @@ mempoolLoop:
// Create a new block ready to be solved. // Create a new block ready to be solved.
merkles := blockchain.BuildMerkleTreeStore(blockTxns) merkles := blockchain.BuildMerkleTreeStore(blockTxns)
var msgBlock btcwire.MsgBlock var msgBlock wire.MsgBlock
msgBlock.Header = btcwire.BlockHeader{ msgBlock.Header = wire.BlockHeader{
Version: generatedBlockVersion, Version: generatedBlockVersion,
PrevBlock: *prevHash, PrevBlock: *prevHash,
MerkleRoot: *merkles[len(merkles)-1], MerkleRoot: *merkles[len(merkles)-1],
@ -821,7 +821,7 @@ mempoolLoop:
// consensus rules. Finally, it will update the target difficulty if needed // consensus rules. Finally, it will update the target difficulty if needed
// based on the new time for the test networks since their target difficulty can // based on the new time for the test networks since their target difficulty can
// change based upon time. // change based upon time.
func UpdateBlockTime(msgBlock *btcwire.MsgBlock, bManager *blockManager) error { func UpdateBlockTime(msgBlock *wire.MsgBlock, bManager *blockManager) error {
// The new timestamp is potentially adjusted to ensure it comes after // The new timestamp is potentially adjusted to ensure it comes after
// the median time of the last several blocks per the chain consensus // the median time of the last several blocks per the chain consensus
// rules. // rules.
@ -848,7 +848,7 @@ func UpdateBlockTime(msgBlock *btcwire.MsgBlock, bManager *blockManager) error {
// block by regenerating the coinbase script with the passed value and block // block by regenerating the coinbase script with the passed value and block
// height. It also recalculates and updates the new merkle root that results // height. It also recalculates and updates the new merkle root that results
// from changing the coinbase script. // from changing the coinbase script.
func UpdateExtraNonce(msgBlock *btcwire.MsgBlock, blockHeight int64, extraNonce uint64) error { func UpdateExtraNonce(msgBlock *wire.MsgBlock, blockHeight int64, extraNonce uint64) error {
coinbaseScript, err := standardCoinbaseScript(blockHeight, extraNonce) coinbaseScript, err := standardCoinbaseScript(blockHeight, extraNonce)
if err != nil { if err != nil {
return err return err

View file

@ -8,14 +8,14 @@ import (
"container/list" "container/list"
"fmt" "fmt"
"github.com/btcsuite/btcwire" "github.com/btcsuite/btcd/wire"
) )
// MruInventoryMap provides a map that is limited to a maximum number of items // MruInventoryMap provides a map that is limited to a maximum number of items
// with eviction for the oldest entry when the limit is exceeded. // with eviction for the oldest entry when the limit is exceeded.
type MruInventoryMap struct { type MruInventoryMap struct {
invMap map[btcwire.InvVect]*list.Element // nearly O(1) lookups invMap map[wire.InvVect]*list.Element // nearly O(1) lookups
invList *list.List // O(1) insert, update, delete invList *list.List // O(1) insert, update, delete
limit uint limit uint
} }
@ -25,7 +25,7 @@ func (m MruInventoryMap) String() string {
} }
// Exists returns whether or not the passed inventory item is in the map. // Exists returns whether or not the passed inventory item is in the map.
func (m *MruInventoryMap) Exists(iv *btcwire.InvVect) bool { func (m *MruInventoryMap) Exists(iv *wire.InvVect) bool {
if _, exists := m.invMap[*iv]; exists { if _, exists := m.invMap[*iv]; exists {
return true return true
} }
@ -34,7 +34,7 @@ func (m *MruInventoryMap) Exists(iv *btcwire.InvVect) bool {
// Add adds the passed inventory to the map and handles eviction of the oldest // Add adds the passed inventory to the map and handles eviction of the oldest
// item if adding the new item would exceed the max limit. // item if adding the new item would exceed the max limit.
func (m *MruInventoryMap) Add(iv *btcwire.InvVect) { func (m *MruInventoryMap) Add(iv *wire.InvVect) {
// When the limit is zero, nothing can be added to the map, so just // When the limit is zero, nothing can be added to the map, so just
// return. // return.
if m.limit == 0 { if m.limit == 0 {
@ -53,7 +53,7 @@ func (m *MruInventoryMap) Add(iv *btcwire.InvVect) {
// node so a new one doesn't have to be allocated. // node so a new one doesn't have to be allocated.
if uint(len(m.invMap))+1 > m.limit { if uint(len(m.invMap))+1 > m.limit {
node := m.invList.Back() node := m.invList.Back()
lru, ok := node.Value.(*btcwire.InvVect) lru, ok := node.Value.(*wire.InvVect)
if !ok { if !ok {
return return
} }
@ -76,7 +76,7 @@ func (m *MruInventoryMap) Add(iv *btcwire.InvVect) {
} }
// Delete deletes the passed inventory item from the map (if it exists). // Delete deletes the passed inventory item from the map (if it exists).
func (m *MruInventoryMap) Delete(iv *btcwire.InvVect) { func (m *MruInventoryMap) Delete(iv *wire.InvVect) {
if node, exists := m.invMap[*iv]; exists { if node, exists := m.invMap[*iv]; exists {
m.invList.Remove(node) m.invList.Remove(node)
delete(m.invMap, *iv) delete(m.invMap, *iv)
@ -89,7 +89,7 @@ func (m *MruInventoryMap) Delete(iv *btcwire.InvVect) {
// new entry. // new entry.
func NewMruInventoryMap(limit uint) *MruInventoryMap { func NewMruInventoryMap(limit uint) *MruInventoryMap {
m := MruInventoryMap{ m := MruInventoryMap{
invMap: make(map[btcwire.InvVect]*list.Element), invMap: make(map[wire.InvVect]*list.Element),
invList: list.New(), invList: list.New(),
limit: limit, limit: limit,
} }

View file

@ -8,7 +8,7 @@ import (
"crypto/rand" "crypto/rand"
"testing" "testing"
"github.com/btcsuite/btcwire" "github.com/btcsuite/btcd/wire"
) )
// BenchmarkMruInventoryList performs basic benchmarks on the most recently // BenchmarkMruInventoryList performs basic benchmarks on the most recently
@ -18,12 +18,12 @@ func BenchmarkMruInventoryList(b *testing.B) {
// the mru inventory code. // the mru inventory code.
b.StopTimer() b.StopTimer()
numInvVects := 100000 numInvVects := 100000
invVects := make([]*btcwire.InvVect, 0, numInvVects) invVects := make([]*wire.InvVect, 0, numInvVects)
for i := 0; i < numInvVects; i++ { for i := 0; i < numInvVects; i++ {
hashBytes := make([]byte, btcwire.HashSize) hashBytes := make([]byte, wire.HashSize)
rand.Read(hashBytes) rand.Read(hashBytes)
hash, _ := btcwire.NewShaHash(hashBytes) hash, _ := wire.NewShaHash(hashBytes)
iv := btcwire.NewInvVect(btcwire.InvTypeBlock, hash) iv := wire.NewInvVect(wire.InvTypeBlock, hash)
invVects = append(invVects, iv) invVects = append(invVects, iv)
} }
b.StartTimer() b.StartTimer()

View file

@ -5,8 +5,8 @@
package main package main
import ( import (
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcnet" "github.com/btcsuite/btcnet"
"github.com/btcsuite/btcwire"
) )
// activeNetParams is a pointer to the parameters specific to the // activeNetParams is a pointer to the parameters specific to the
@ -22,7 +22,7 @@ type params struct {
} }
// mainNetParams contains parameters specific to the main network // mainNetParams contains parameters specific to the main network
// (btcwire.MainNet). NOTE: The RPC port is intentionally different than the // (wire.MainNet). NOTE: The RPC port is intentionally different than the
// reference implementation because btcd does not handle wallet requests. The // reference implementation because btcd does not handle wallet requests. The
// separate wallet process listens on the well-known port and forwards requests // separate wallet process listens on the well-known port and forwards requests
// it does not handle on to btcd. This approach allows the wallet process // it does not handle on to btcd. This approach allows the wallet process
@ -42,7 +42,7 @@ var mainNetParams = params{
} }
// regressionNetParams contains parameters specific to the regression test // regressionNetParams contains parameters specific to the regression test
// network (btcwire.TestNet). NOTE: The RPC port is intentionally different // network (wire.TestNet). NOTE: The RPC port is intentionally different
// than the reference implementation - see the mainNetParams comment for // than the reference implementation - see the mainNetParams comment for
// details. // details.
var regressionNetParams = params{ var regressionNetParams = params{
@ -52,7 +52,7 @@ var regressionNetParams = params{
} }
// testNet3Params contains parameters specific to the test network (version 3) // testNet3Params contains parameters specific to the test network (version 3)
// (btcwire.TestNet3). NOTE: The RPC port is intentionally different than the // (wire.TestNet3). NOTE: The RPC port is intentionally different than the
// reference implementation - see the mainNetParams comment for details. // reference implementation - see the mainNetParams comment for details.
var testNet3Params = params{ var testNet3Params = params{
Params: &btcnet.TestNet3Params, Params: &btcnet.TestNet3Params,
@ -66,7 +66,7 @@ var testNet3Params = params{
} }
// simNetParams contains parameters specific to the simulation test network // simNetParams contains parameters specific to the simulation test network
// (btcwire.SimNet). // (wire.SimNet).
var simNetParams = params{ var simNetParams = params{
Params: &btcnet.SimNetParams, Params: &btcnet.SimNetParams,
rpcPort: "18556", rpcPort: "18556",
@ -77,14 +77,14 @@ var simNetParams = params{
// time of writing, btcd currently places blocks for testnet version 3 in the // time of writing, btcd currently places blocks for testnet version 3 in the
// data and log directory "testnet", which does not match the Name field of the // data and log directory "testnet", which does not match the Name field of the
// btcnet parameters. This function can be used to override this directory name // btcnet parameters. This function can be used to override this directory name
// as "testnet" when the passed active network matches btcwire.TestNet3. // as "testnet" when the passed active network matches wire.TestNet3.
// //
// A proper upgrade to move the data and log directories for this network to // A proper upgrade to move the data and log directories for this network to
// "testnet3" is planned for the future, at which point this function can be // "testnet3" is planned for the future, at which point this function can be
// removed and the network parameter's name used instead. // removed and the network parameter's name used instead.
func netName(netParams *params) string { func netName(netParams *params) string {
switch netParams.Net { switch netParams.Net {
case btcwire.TestNet3: case wire.TestNet3:
return "testnet" return "testnet"
default: default:
return netParams.Name return netParams.Name

280
peer.go
View file

@ -19,9 +19,9 @@ import (
"github.com/btcsuite/btcd/addrmgr" "github.com/btcsuite/btcd/addrmgr"
"github.com/btcsuite/btcd/blockchain" "github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcutil/bloom" "github.com/btcsuite/btcutil/bloom"
"github.com/btcsuite/btcwire"
"github.com/btcsuite/go-socks/socks" "github.com/btcsuite/go-socks/socks"
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
) )
@ -66,7 +66,7 @@ var (
) )
// zeroHash is the zero value hash (all zeros). It is defined as a convenience. // zeroHash is the zero value hash (all zeros). It is defined as a convenience.
var zeroHash btcwire.ShaHash var zeroHash wire.ShaHash
// minUint32 is a helper function to return the minimum of two uint32s. // minUint32 is a helper function to return the minimum of two uint32s.
// This avoids a math import and the need to cast to floats. // This avoids a math import and the need to cast to floats.
@ -80,12 +80,12 @@ func minUint32(a, b uint32) uint32 {
// newNetAddress attempts to extract the IP address and port from the passed // newNetAddress attempts to extract the IP address and port from the passed
// net.Addr interface and create a bitcoin NetAddress structure using that // net.Addr interface and create a bitcoin NetAddress structure using that
// information. // information.
func newNetAddress(addr net.Addr, services btcwire.ServiceFlag) (*btcwire.NetAddress, error) { func newNetAddress(addr net.Addr, services wire.ServiceFlag) (*wire.NetAddress, error) {
// addr will be a net.TCPAddr when not using a proxy. // addr will be a net.TCPAddr when not using a proxy.
if tcpAddr, ok := addr.(*net.TCPAddr); ok { if tcpAddr, ok := addr.(*net.TCPAddr); ok {
ip := tcpAddr.IP ip := tcpAddr.IP
port := uint16(tcpAddr.Port) port := uint16(tcpAddr.Port)
na := btcwire.NewNetAddressIPPort(ip, port, services) na := wire.NewNetAddressIPPort(ip, port, services)
return na, nil return na, nil
} }
@ -96,7 +96,7 @@ func newNetAddress(addr net.Addr, services btcwire.ServiceFlag) (*btcwire.NetAdd
ip = net.ParseIP("0.0.0.0") ip = net.ParseIP("0.0.0.0")
} }
port := uint16(proxiedAddr.Port) port := uint16(proxiedAddr.Port)
na := btcwire.NewNetAddressIPPort(ip, port, services) na := wire.NewNetAddressIPPort(ip, port, services)
return na, nil return na, nil
} }
@ -112,7 +112,7 @@ func newNetAddress(addr net.Addr, services btcwire.ServiceFlag) (*btcwire.NetAdd
if err != nil { if err != nil {
return nil, err return nil, err
} }
na := btcwire.NewNetAddressIPPort(ip, uint16(port), services) na := wire.NewNetAddressIPPort(ip, uint16(port), services)
return na, nil return na, nil
} }
@ -120,7 +120,7 @@ func newNetAddress(addr net.Addr, services btcwire.ServiceFlag) (*btcwire.NetAdd
// when the message has been sent (or won't be sent due to things such as // when the message has been sent (or won't be sent due to things such as
// shutdown) // shutdown)
type outMsg struct { type outMsg struct {
msg btcwire.Message msg wire.Message
doneChan chan struct{} doneChan chan struct{}
} }
@ -143,42 +143,42 @@ type outMsg struct {
// to push messages to the peer. Internally they use QueueMessage. // to push messages to the peer. Internally they use QueueMessage.
type peer struct { type peer struct {
server *server server *server
btcnet btcwire.BitcoinNet btcnet wire.BitcoinNet
started int32 started int32
connected int32 connected int32
disconnect int32 // only to be used atomically disconnect int32 // only to be used atomically
conn net.Conn conn net.Conn
addr string addr string
na *btcwire.NetAddress na *wire.NetAddress
inbound bool inbound bool
persistent bool persistent bool
knownAddresses map[string]struct{} knownAddresses map[string]struct{}
knownInventory *MruInventoryMap knownInventory *MruInventoryMap
knownInvMutex sync.Mutex knownInvMutex sync.Mutex
requestedTxns map[btcwire.ShaHash]struct{} // owned by blockmanager requestedTxns map[wire.ShaHash]struct{} // owned by blockmanager
requestedBlocks map[btcwire.ShaHash]struct{} // owned by blockmanager requestedBlocks map[wire.ShaHash]struct{} // owned by blockmanager
retryCount int64 retryCount int64
prevGetBlocksBegin *btcwire.ShaHash // owned by blockmanager prevGetBlocksBegin *wire.ShaHash // owned by blockmanager
prevGetBlocksStop *btcwire.ShaHash // owned by blockmanager prevGetBlocksStop *wire.ShaHash // owned by blockmanager
prevGetHdrsBegin *btcwire.ShaHash // owned by blockmanager prevGetHdrsBegin *wire.ShaHash // owned by blockmanager
prevGetHdrsStop *btcwire.ShaHash // owned by blockmanager prevGetHdrsStop *wire.ShaHash // owned by blockmanager
requestQueue []*btcwire.InvVect requestQueue []*wire.InvVect
filter *bloom.Filter filter *bloom.Filter
relayMtx sync.Mutex relayMtx sync.Mutex
disableRelayTx bool disableRelayTx bool
continueHash *btcwire.ShaHash continueHash *wire.ShaHash
outputQueue chan outMsg outputQueue chan outMsg
sendQueue chan outMsg sendQueue chan outMsg
sendDoneQueue chan struct{} sendDoneQueue chan struct{}
queueWg sync.WaitGroup // TODO(oga) wg -> single use channel? queueWg sync.WaitGroup // TODO(oga) wg -> single use channel?
outputInvChan chan *btcwire.InvVect outputInvChan chan *wire.InvVect
txProcessed chan struct{} txProcessed chan struct{}
blockProcessed chan struct{} blockProcessed chan struct{}
quit chan struct{} quit chan struct{}
StatsMtx sync.Mutex // protects all statistics below here. StatsMtx sync.Mutex // protects all statistics below here.
versionKnown bool versionKnown bool
protocolVersion uint32 protocolVersion uint32
services btcwire.ServiceFlag services wire.ServiceFlag
timeConnected time.Time timeConnected time.Time
lastSend time.Time lastSend time.Time
lastRecv time.Time lastRecv time.Time
@ -199,7 +199,7 @@ func (p *peer) String() string {
// isKnownInventory returns whether or not the peer is known to have the passed // isKnownInventory returns whether or not the peer is known to have the passed
// inventory. It is safe for concurrent access. // inventory. It is safe for concurrent access.
func (p *peer) isKnownInventory(invVect *btcwire.InvVect) bool { func (p *peer) isKnownInventory(invVect *wire.InvVect) bool {
p.knownInvMutex.Lock() p.knownInvMutex.Lock()
defer p.knownInvMutex.Unlock() defer p.knownInvMutex.Unlock()
@ -211,7 +211,7 @@ func (p *peer) isKnownInventory(invVect *btcwire.InvVect) bool {
// AddKnownInventory adds the passed inventory to the cache of known inventory // AddKnownInventory adds the passed inventory to the cache of known inventory
// for the peer. It is safe for concurrent access. // for the peer. It is safe for concurrent access.
func (p *peer) AddKnownInventory(invVect *btcwire.InvVect) { func (p *peer) AddKnownInventory(invVect *wire.InvVect) {
p.knownInvMutex.Lock() p.knownInvMutex.Lock()
defer p.knownInvMutex.Unlock() defer p.knownInvMutex.Unlock()
@ -262,7 +262,7 @@ func (p *peer) pushVersionMsg() error {
proxyaddress, _, err := net.SplitHostPort(cfg.Proxy) proxyaddress, _, err := net.SplitHostPort(cfg.Proxy)
// invalid proxy means poorly configured, be on the safe side. // invalid proxy means poorly configured, be on the safe side.
if err != nil || p.na.IP.String() == proxyaddress { if err != nil || p.na.IP.String() == proxyaddress {
theirNa = &btcwire.NetAddress{ theirNa = &wire.NetAddress{
Timestamp: time.Now(), Timestamp: time.Now(),
IP: net.IP([]byte{0, 0, 0, 0}), IP: net.IP([]byte{0, 0, 0, 0}),
} }
@ -270,7 +270,7 @@ func (p *peer) pushVersionMsg() error {
} }
// Version message. // Version message.
msg := btcwire.NewMsgVersion( msg := wire.NewMsgVersion(
p.server.addrManager.GetBestLocalAddress(p.na), theirNa, p.server.addrManager.GetBestLocalAddress(p.na), theirNa,
p.server.nonce, int32(blockNum)) p.server.nonce, int32(blockNum))
msg.AddUserAgent(userAgentName, userAgentVersion) msg.AddUserAgent(userAgentName, userAgentVersion)
@ -291,10 +291,10 @@ func (p *peer) pushVersionMsg() error {
// actually supports // actually supports
// - Set the remote netaddress services to the what was advertised by // - Set the remote netaddress services to the what was advertised by
// by the remote peer in its version message // by the remote peer in its version message
msg.AddrYou.Services = btcwire.SFNodeNetwork msg.AddrYou.Services = wire.SFNodeNetwork
// Advertise that we're a full node. // Advertise that we're a full node.
msg.Services = btcwire.SFNodeNetwork msg.Services = wire.SFNodeNetwork
// Advertise our max supported protocol version. // Advertise our max supported protocol version.
msg.ProtocolVersion = maxProtocolVersion msg.ProtocolVersion = maxProtocolVersion
@ -307,7 +307,7 @@ func (p *peer) pushVersionMsg() error {
// requests known addresses from the remote peer depending on whether the peer // requests known addresses from the remote peer depending on whether the peer
// is an inbound or outbound peer and other factors such as address routability // is an inbound or outbound peer and other factors such as address routability
// and the negotiated protocol version. // and the negotiated protocol version.
func (p *peer) updateAddresses(msg *btcwire.MsgVersion) { func (p *peer) updateAddresses(msg *wire.MsgVersion) {
// Outbound connections. // Outbound connections.
if !p.inbound { if !p.inbound {
// TODO(davec): Only do this if not doing the initial block // TODO(davec): Only do this if not doing the initial block
@ -316,7 +316,7 @@ func (p *peer) updateAddresses(msg *btcwire.MsgVersion) {
// Get address that best matches. // Get address that best matches.
lna := p.server.addrManager.GetBestLocalAddress(p.na) lna := p.server.addrManager.GetBestLocalAddress(p.na)
if addrmgr.IsRoutable(lna) { if addrmgr.IsRoutable(lna) {
addresses := []*btcwire.NetAddress{lna} addresses := []*wire.NetAddress{lna}
p.pushAddrMsg(addresses) p.pushAddrMsg(addresses)
} }
} }
@ -325,9 +325,9 @@ func (p *peer) updateAddresses(msg *btcwire.MsgVersion) {
// more and the peer has a protocol version new enough to // more and the peer has a protocol version new enough to
// include a timestamp with addresses. // include a timestamp with addresses.
hasTimestamp := p.ProtocolVersion() >= hasTimestamp := p.ProtocolVersion() >=
btcwire.NetAddressTimeVersion wire.NetAddressTimeVersion
if p.server.addrManager.NeedMoreAddresses() && hasTimestamp { if p.server.addrManager.NeedMoreAddresses() && hasTimestamp {
p.QueueMessage(btcwire.NewMsgGetAddr(), nil) p.QueueMessage(wire.NewMsgGetAddr(), nil)
} }
// Mark the address as a known good address. // Mark the address as a known good address.
@ -347,7 +347,7 @@ func (p *peer) updateAddresses(msg *btcwire.MsgVersion) {
// handleVersionMsg is invoked when a peer receives a version bitcoin message // handleVersionMsg is invoked when a peer receives a version bitcoin message
// and is used to negotiate the protocol version details as well as kick start // and is used to negotiate the protocol version details as well as kick start
// the communications. // the communications.
func (p *peer) handleVersionMsg(msg *btcwire.MsgVersion) { func (p *peer) handleVersionMsg(msg *wire.MsgVersion) {
// Detect self connections. // Detect self connections.
if msg.Nonce == p.server.nonce { if msg.Nonce == p.server.nonce {
peerLog.Debugf("Disconnecting peer connected to self %s", p) peerLog.Debugf("Disconnecting peer connected to self %s", p)
@ -357,13 +357,13 @@ func (p *peer) handleVersionMsg(msg *btcwire.MsgVersion) {
// Notify and disconnect clients that have a protocol version that is // Notify and disconnect clients that have a protocol version that is
// too old. // too old.
if msg.ProtocolVersion < int32(btcwire.MultipleAddressVersion) { if msg.ProtocolVersion < int32(wire.MultipleAddressVersion) {
// Send a reject message indicating the protocol version is // Send a reject message indicating the protocol version is
// obsolete and wait for the message to be sent before // obsolete and wait for the message to be sent before
// disconnecting. // disconnecting.
reason := fmt.Sprintf("protocol version must be %d or greater", reason := fmt.Sprintf("protocol version must be %d or greater",
btcwire.MultipleAddressVersion) wire.MultipleAddressVersion)
p.PushRejectMsg(msg.Command(), btcwire.RejectObsolete, reason, p.PushRejectMsg(msg.Command(), wire.RejectObsolete, reason,
nil, true) nil, true)
p.Disconnect() p.Disconnect()
return return
@ -381,7 +381,7 @@ func (p *peer) handleVersionMsg(msg *btcwire.MsgVersion) {
// Send an reject message indicating the version message was // Send an reject message indicating the version message was
// incorrectly sent twice and wait for the message to be sent // incorrectly sent twice and wait for the message to be sent
// before disconnecting. // before disconnecting.
p.PushRejectMsg(msg.Command(), btcwire.RejectDuplicate, p.PushRejectMsg(msg.Command(), wire.RejectDuplicate,
"duplicate version message", nil, true) "duplicate version message", nil, true)
p.Disconnect() p.Disconnect()
@ -434,7 +434,7 @@ func (p *peer) handleVersionMsg(msg *btcwire.MsgVersion) {
} }
// Send verack. // Send verack.
p.QueueMessage(btcwire.NewMsgVerAck(), nil) p.QueueMessage(wire.NewMsgVerAck(), nil)
// Update the address manager and request known addresses from the // Update the address manager and request known addresses from the
// remote peer for outbound connections. This is skipped when running // remote peer for outbound connections. This is skipped when running
@ -457,7 +457,7 @@ func (p *peer) handleVersionMsg(msg *btcwire.MsgVersion) {
// pushTxMsg sends a tx message for the provided transaction hash to the // pushTxMsg sends a tx message for the provided transaction hash to the
// connected peer. An error is returned if the transaction hash is not known. // connected peer. An error is returned if the transaction hash is not known.
func (p *peer) pushTxMsg(sha *btcwire.ShaHash, doneChan, waitChan chan struct{}) error { func (p *peer) pushTxMsg(sha *wire.ShaHash, doneChan, waitChan chan struct{}) error {
// Attempt to fetch the requested transaction from the pool. A // Attempt to fetch the requested transaction from the pool. A
// call could be made to check for existence first, but simply trying // call could be made to check for existence first, but simply trying
// to fetch a missing transaction results in the same behavior. // to fetch a missing transaction results in the same behavior.
@ -484,7 +484,7 @@ func (p *peer) pushTxMsg(sha *btcwire.ShaHash, doneChan, waitChan chan struct{})
// pushBlockMsg sends a block message for the provided block hash to the // pushBlockMsg sends a block message for the provided block hash to the
// connected peer. An error is returned if the block hash is not known. // connected peer. An error is returned if the block hash is not known.
func (p *peer) pushBlockMsg(sha *btcwire.ShaHash, doneChan, waitChan chan struct{}) error { func (p *peer) pushBlockMsg(sha *wire.ShaHash, doneChan, waitChan chan struct{}) error {
blk, err := p.server.db.FetchBlockBySha(sha) blk, err := p.server.db.FetchBlockBySha(sha)
if err != nil { if err != nil {
peerLog.Tracef("Unable to fetch requested block sha %v: %v", peerLog.Tracef("Unable to fetch requested block sha %v: %v",
@ -518,8 +518,8 @@ func (p *peer) pushBlockMsg(sha *btcwire.ShaHash, doneChan, waitChan chan struct
if p.continueHash != nil && p.continueHash.IsEqual(sha) { if p.continueHash != nil && p.continueHash.IsEqual(sha) {
hash, _, err := p.server.db.NewestSha() hash, _, err := p.server.db.NewestSha()
if err == nil { if err == nil {
invMsg := btcwire.NewMsgInvSizeHint(1) invMsg := wire.NewMsgInvSizeHint(1)
iv := btcwire.NewInvVect(btcwire.InvTypeBlock, hash) iv := wire.NewInvVect(wire.InvTypeBlock, hash)
invMsg.AddInvVect(iv) invMsg.AddInvVect(iv)
p.QueueMessage(invMsg, doneChan) p.QueueMessage(invMsg, doneChan)
p.continueHash = nil p.continueHash = nil
@ -534,7 +534,7 @@ func (p *peer) pushBlockMsg(sha *btcwire.ShaHash, doneChan, waitChan chan struct
// the connected peer. Since a merkle block requires the peer to have a filter // the connected peer. Since a merkle block requires the peer to have a filter
// loaded, this call will simply be ignored if there is no filter loaded. An // loaded, this call will simply be ignored if there is no filter loaded. An
// error is returned if the block hash is not known. // error is returned if the block hash is not known.
func (p *peer) pushMerkleBlockMsg(sha *btcwire.ShaHash, doneChan, waitChan chan struct{}) error { func (p *peer) pushMerkleBlockMsg(sha *wire.ShaHash, doneChan, waitChan chan struct{}) error {
// Do not send a response if the peer doesn't have a filter loaded. // Do not send a response if the peer doesn't have a filter loaded.
if !p.filter.IsLoaded() { if !p.filter.IsLoaded() {
if doneChan != nil { if doneChan != nil {
@ -608,11 +608,11 @@ func (p *peer) pushMerkleBlockMsg(sha *btcwire.ShaHash, doneChan, waitChan chan
// PushGetBlocksMsg sends a getblocks message for the provided block locator // PushGetBlocksMsg sends a getblocks message for the provided block locator
// and stop hash. It will ignore back-to-back duplicate requests. // and stop hash. It will ignore back-to-back duplicate requests.
func (p *peer) PushGetBlocksMsg(locator blockchain.BlockLocator, stopHash *btcwire.ShaHash) error { func (p *peer) PushGetBlocksMsg(locator blockchain.BlockLocator, stopHash *wire.ShaHash) error {
// Extract the begin hash from the block locator, if one was specified, // Extract the begin hash from the block locator, if one was specified,
// to use for filtering duplicate getblocks requests. // to use for filtering duplicate getblocks requests.
// request. // request.
var beginHash *btcwire.ShaHash var beginHash *wire.ShaHash
if len(locator) > 0 { if len(locator) > 0 {
beginHash = locator[0] beginHash = locator[0]
} }
@ -628,7 +628,7 @@ func (p *peer) PushGetBlocksMsg(locator blockchain.BlockLocator, stopHash *btcwi
} }
// Construct the getblocks request and queue it to be sent. // Construct the getblocks request and queue it to be sent.
msg := btcwire.NewMsgGetBlocks(stopHash) msg := wire.NewMsgGetBlocks(stopHash)
for _, hash := range locator { for _, hash := range locator {
err := msg.AddBlockLocatorHash(hash) err := msg.AddBlockLocatorHash(hash)
if err != nil { if err != nil {
@ -646,10 +646,10 @@ func (p *peer) PushGetBlocksMsg(locator blockchain.BlockLocator, stopHash *btcwi
// PushGetHeadersMsg sends a getblocks message for the provided block locator // PushGetHeadersMsg sends a getblocks message for the provided block locator
// and stop hash. It will ignore back-to-back duplicate requests. // and stop hash. It will ignore back-to-back duplicate requests.
func (p *peer) PushGetHeadersMsg(locator blockchain.BlockLocator, stopHash *btcwire.ShaHash) error { func (p *peer) PushGetHeadersMsg(locator blockchain.BlockLocator, stopHash *wire.ShaHash) error {
// Extract the begin hash from the block locator, if one was specified, // Extract the begin hash from the block locator, if one was specified,
// to use for filtering duplicate getheaders requests. // to use for filtering duplicate getheaders requests.
var beginHash *btcwire.ShaHash var beginHash *wire.ShaHash
if len(locator) > 0 { if len(locator) > 0 {
beginHash = locator[0] beginHash = locator[0]
} }
@ -665,7 +665,7 @@ func (p *peer) PushGetHeadersMsg(locator blockchain.BlockLocator, stopHash *btcw
} }
// Construct the getheaders request and queue it to be sent. // Construct the getheaders request and queue it to be sent.
msg := btcwire.NewMsgGetHeaders() msg := wire.NewMsgGetHeaders()
msg.HashStop = *stopHash msg.HashStop = *stopHash
for _, hash := range locator { for _, hash := range locator {
err := msg.AddBlockLocatorHash(hash) err := msg.AddBlockLocatorHash(hash)
@ -686,15 +686,15 @@ func (p *peer) PushGetHeadersMsg(locator blockchain.BlockLocator, stopHash *btcw
// and reject reason, and hash. The hash will only be used when the command // and reject reason, and hash. The hash will only be used when the command
// is a tx or block and should be nil in other cases. The wait parameter will // is a tx or block and should be nil in other cases. The wait parameter will
// cause the function to block until the reject message has actually been sent. // cause the function to block until the reject message has actually been sent.
func (p *peer) PushRejectMsg(command string, code btcwire.RejectCode, reason string, hash *btcwire.ShaHash, wait bool) { func (p *peer) PushRejectMsg(command string, code wire.RejectCode, reason string, hash *wire.ShaHash, wait bool) {
// Don't bother sending the reject message if the protocol version // Don't bother sending the reject message if the protocol version
// is too low. // is too low.
if p.VersionKnown() && p.ProtocolVersion() < btcwire.RejectVersion { if p.VersionKnown() && p.ProtocolVersion() < wire.RejectVersion {
return return
} }
msg := btcwire.NewMsgReject(command, code, reason) msg := wire.NewMsgReject(command, code, reason)
if command == btcwire.CmdTx || command == btcwire.CmdBlock { if command == wire.CmdTx || command == wire.CmdBlock {
if hash == nil { if hash == nil {
peerLog.Warnf("Sending a reject message for command "+ peerLog.Warnf("Sending a reject message for command "+
"type %v which should have specified a hash "+ "type %v which should have specified a hash "+
@ -720,14 +720,14 @@ func (p *peer) PushRejectMsg(command string, code btcwire.RejectCode, reason str
// It creates and sends an inventory message with the contents of the memory // It creates and sends an inventory message with the contents of the memory
// pool up to the maximum inventory allowed per message. When the peer has a // pool up to the maximum inventory allowed per message. When the peer has a
// bloom filter loaded, the contents are filtered accordingly. // bloom filter loaded, the contents are filtered accordingly.
func (p *peer) handleMemPoolMsg(msg *btcwire.MsgMemPool) { func (p *peer) handleMemPoolMsg(msg *wire.MsgMemPool) {
// Generate inventory message with the available transactions in the // Generate inventory message with the available transactions in the
// transaction memory pool. Limit it to the max allowed inventory // transaction memory pool. Limit it to the max allowed inventory
// per message. The the NewMsgInvSizeHint function automatically limits // per message. The the NewMsgInvSizeHint function automatically limits
// the passed hint to the maximum allowed, so it's safe to pass it // the passed hint to the maximum allowed, so it's safe to pass it
// without double checking it here. // without double checking it here.
txDescs := p.server.txMemPool.TxDescs() txDescs := p.server.txMemPool.TxDescs()
invMsg := btcwire.NewMsgInvSizeHint(uint(len(txDescs))) invMsg := wire.NewMsgInvSizeHint(uint(len(txDescs)))
for i, txDesc := range txDescs { for i, txDesc := range txDescs {
// Another thread might have removed the transaction from the // Another thread might have removed the transaction from the
@ -741,9 +741,9 @@ func (p *peer) handleMemPoolMsg(msg *btcwire.MsgMemPool) {
// or only the transactions that match the filter when there is // or only the transactions that match the filter when there is
// one. // one.
if !p.filter.IsLoaded() || p.filter.MatchTxAndUpdate(txDesc.Tx) { if !p.filter.IsLoaded() || p.filter.MatchTxAndUpdate(txDesc.Tx) {
iv := btcwire.NewInvVect(btcwire.InvTypeTx, hash) iv := wire.NewInvVect(wire.InvTypeTx, hash)
invMsg.AddInvVect(iv) invMsg.AddInvVect(iv)
if i+1 >= btcwire.MaxInvPerMsg { if i+1 >= wire.MaxInvPerMsg {
break break
} }
} }
@ -759,12 +759,12 @@ func (p *peer) handleMemPoolMsg(msg *btcwire.MsgMemPool) {
// until the bitcoin transaction has been fully processed. Unlock the block // until the bitcoin transaction has been fully processed. Unlock the block
// handler this does not serialize all transactions through a single thread // handler this does not serialize all transactions through a single thread
// transactions don't rely on the previous one in a linear fashion like blocks. // transactions don't rely on the previous one in a linear fashion like blocks.
func (p *peer) handleTxMsg(msg *btcwire.MsgTx) { func (p *peer) handleTxMsg(msg *wire.MsgTx) {
// Add the transaction to the known inventory for the peer. // Add the transaction to the known inventory for the peer.
// Convert the raw MsgTx to a btcutil.Tx which provides some convenience // Convert the raw MsgTx to a btcutil.Tx which provides some convenience
// methods and things such as hash caching. // methods and things such as hash caching.
tx := btcutil.NewTx(msg) tx := btcutil.NewTx(msg)
iv := btcwire.NewInvVect(btcwire.InvTypeTx, tx.Sha()) iv := wire.NewInvVect(wire.InvTypeTx, tx.Sha())
p.AddKnownInventory(iv) p.AddKnownInventory(iv)
// Queue the transaction up to be handled by the block manager and // Queue the transaction up to be handled by the block manager and
@ -778,7 +778,7 @@ func (p *peer) handleTxMsg(msg *btcwire.MsgTx) {
// handleBlockMsg is invoked when a peer receives a block bitcoin message. It // handleBlockMsg is invoked when a peer receives a block bitcoin message. It
// blocks until the bitcoin block has been fully processed. // blocks until the bitcoin block has been fully processed.
func (p *peer) handleBlockMsg(msg *btcwire.MsgBlock, buf []byte) { func (p *peer) handleBlockMsg(msg *wire.MsgBlock, buf []byte) {
// Convert the raw MsgBlock to a btcutil.Block which provides some // Convert the raw MsgBlock to a btcutil.Block which provides some
// convenience methods and things such as hash caching. // convenience methods and things such as hash caching.
block := btcutil.NewBlockFromBlockAndBytes(msg, buf) block := btcutil.NewBlockFromBlockAndBytes(msg, buf)
@ -789,7 +789,7 @@ func (p *peer) handleBlockMsg(msg *btcwire.MsgBlock, buf []byte) {
peerLog.Errorf("Unable to get block hash: %v", err) peerLog.Errorf("Unable to get block hash: %v", err)
return return
} }
iv := btcwire.NewInvVect(btcwire.InvTypeBlock, hash) iv := wire.NewInvVect(wire.InvTypeBlock, hash)
p.AddKnownInventory(iv) p.AddKnownInventory(iv)
// Queue the block up to be handled by the block // Queue the block up to be handled by the block
@ -811,21 +811,21 @@ func (p *peer) handleBlockMsg(msg *btcwire.MsgBlock, buf []byte) {
// used to examine the inventory being advertised by the remote peer and react // used to examine the inventory being advertised by the remote peer and react
// accordingly. We pass the message down to blockmanager which will call // accordingly. We pass the message down to blockmanager which will call
// QueueMessage with any appropriate responses. // QueueMessage with any appropriate responses.
func (p *peer) handleInvMsg(msg *btcwire.MsgInv) { func (p *peer) handleInvMsg(msg *wire.MsgInv) {
p.server.blockManager.QueueInv(msg, p) p.server.blockManager.QueueInv(msg, p)
} }
// handleHeadersMsg is invoked when a peer receives a headers bitcoin message. // handleHeadersMsg is invoked when a peer receives a headers bitcoin message.
// The message is passed down to the block manager. // The message is passed down to the block manager.
func (p *peer) handleHeadersMsg(msg *btcwire.MsgHeaders) { func (p *peer) handleHeadersMsg(msg *wire.MsgHeaders) {
p.server.blockManager.QueueHeaders(msg, p) p.server.blockManager.QueueHeaders(msg, p)
} }
// handleGetData is invoked when a peer receives a getdata bitcoin message and // handleGetData is invoked when a peer receives a getdata bitcoin message and
// is used to deliver block and transaction information. // is used to deliver block and transaction information.
func (p *peer) handleGetDataMsg(msg *btcwire.MsgGetData) { func (p *peer) handleGetDataMsg(msg *wire.MsgGetData) {
numAdded := 0 numAdded := 0
notFound := btcwire.NewMsgNotFound() notFound := wire.NewMsgNotFound()
// We wait on the this wait channel periodically to prevent queueing // We wait on the this wait channel periodically to prevent queueing
// far more data than we can send in a reasonable time, wasting memory. // far more data than we can send in a reasonable time, wasting memory.
@ -845,11 +845,11 @@ func (p *peer) handleGetDataMsg(msg *btcwire.MsgGetData) {
} }
var err error var err error
switch iv.Type { switch iv.Type {
case btcwire.InvTypeTx: case wire.InvTypeTx:
err = p.pushTxMsg(&iv.Hash, c, waitChan) err = p.pushTxMsg(&iv.Hash, c, waitChan)
case btcwire.InvTypeBlock: case wire.InvTypeBlock:
err = p.pushBlockMsg(&iv.Hash, c, waitChan) err = p.pushBlockMsg(&iv.Hash, c, waitChan)
case btcwire.InvTypeFilteredBlock: case wire.InvTypeFilteredBlock:
err = p.pushMerkleBlockMsg(&iv.Hash, c, waitChan) err = p.pushMerkleBlockMsg(&iv.Hash, c, waitChan)
default: default:
peerLog.Warnf("Unknown type in inventory request %d", peerLog.Warnf("Unknown type in inventory request %d",
@ -886,7 +886,7 @@ func (p *peer) handleGetDataMsg(msg *btcwire.MsgGetData) {
} }
// handleGetBlocksMsg is invoked when a peer receives a getblocks bitcoin message. // handleGetBlocksMsg is invoked when a peer receives a getblocks bitcoin message.
func (p *peer) handleGetBlocksMsg(msg *btcwire.MsgGetBlocks) { func (p *peer) handleGetBlocksMsg(msg *wire.MsgGetBlocks) {
// Return all block hashes to the latest one (up to max per message) if // Return all block hashes to the latest one (up to max per message) if
// no stop hash was specified. // no stop hash was specified.
// Attempt to find the ending index of the stop hash if specified. // Attempt to find the ending index of the stop hash if specified.
@ -915,8 +915,8 @@ func (p *peer) handleGetBlocksMsg(msg *btcwire.MsgGetBlocks) {
// Don't attempt to fetch more than we can put into a single message. // Don't attempt to fetch more than we can put into a single message.
autoContinue := false autoContinue := false
if endIdx-startIdx > btcwire.MaxBlocksPerMsg { if endIdx-startIdx > wire.MaxBlocksPerMsg {
endIdx = startIdx + btcwire.MaxBlocksPerMsg endIdx = startIdx + wire.MaxBlocksPerMsg
autoContinue = true autoContinue = true
} }
@ -926,7 +926,7 @@ func (p *peer) handleGetBlocksMsg(msg *btcwire.MsgGetBlocks) {
// per invocation. Since the maximum number of inventory per message // per invocation. Since the maximum number of inventory per message
// might be larger, call it multiple times with the appropriate indices // might be larger, call it multiple times with the appropriate indices
// as needed. // as needed.
invMsg := btcwire.NewMsgInv() invMsg := wire.NewMsgInv()
for start := startIdx; start < endIdx; { for start := startIdx; start < endIdx; {
// Fetch the inventory from the block database. // Fetch the inventory from the block database.
hashList, err := p.server.db.FetchHeightRange(start, endIdx) hashList, err := p.server.db.FetchHeightRange(start, endIdx)
@ -944,7 +944,7 @@ func (p *peer) handleGetBlocksMsg(msg *btcwire.MsgGetBlocks) {
// Add block inventory to the message. // Add block inventory to the message.
for _, hash := range hashList { for _, hash := range hashList {
hashCopy := hash hashCopy := hash
iv := btcwire.NewInvVect(btcwire.InvTypeBlock, &hashCopy) iv := wire.NewInvVect(wire.InvTypeBlock, &hashCopy)
invMsg.AddInvVect(iv) invMsg.AddInvVect(iv)
} }
start += int64(len(hashList)) start += int64(len(hashList))
@ -953,7 +953,7 @@ func (p *peer) handleGetBlocksMsg(msg *btcwire.MsgGetBlocks) {
// Send the inventory message if there is anything to send. // Send the inventory message if there is anything to send.
if len(invMsg.InvList) > 0 { if len(invMsg.InvList) > 0 {
invListLen := len(invMsg.InvList) invListLen := len(invMsg.InvList)
if autoContinue && invListLen == btcwire.MaxBlocksPerMsg { if autoContinue && invListLen == wire.MaxBlocksPerMsg {
// Intentionally use a copy of the final hash so there // Intentionally use a copy of the final hash so there
// is not a reference into the inventory slice which // is not a reference into the inventory slice which
// would prevent the entire slice from being eligible // would prevent the entire slice from being eligible
@ -967,7 +967,7 @@ func (p *peer) handleGetBlocksMsg(msg *btcwire.MsgGetBlocks) {
// handleGetHeadersMsg is invoked when a peer receives a getheaders bitcoin // handleGetHeadersMsg is invoked when a peer receives a getheaders bitcoin
// message. // message.
func (p *peer) handleGetHeadersMsg(msg *btcwire.MsgGetHeaders) { func (p *peer) handleGetHeadersMsg(msg *wire.MsgGetHeaders) {
// Attempt to look up the height of the provided stop hash. // Attempt to look up the height of the provided stop hash.
endIdx := database.AllShas endIdx := database.AllShas
height, err := p.server.db.FetchBlockHeightBySha(&msg.HashStop) height, err := p.server.db.FetchBlockHeightBySha(&msg.HashStop)
@ -993,7 +993,7 @@ func (p *peer) handleGetHeadersMsg(msg *btcwire.MsgGetHeaders) {
return return
} }
headersMsg := btcwire.NewMsgHeaders() headersMsg := wire.NewMsgHeaders()
headersMsg.AddBlockHeader(header) headersMsg.AddBlockHeader(header)
p.QueueMessage(headersMsg, nil) p.QueueMessage(headersMsg, nil)
return return
@ -1015,8 +1015,8 @@ func (p *peer) handleGetHeadersMsg(msg *btcwire.MsgGetHeaders) {
} }
// Don't attempt to fetch more than we can put into a single message. // Don't attempt to fetch more than we can put into a single message.
if endIdx-startIdx > btcwire.MaxBlockHeadersPerMsg { if endIdx-startIdx > wire.MaxBlockHeadersPerMsg {
endIdx = startIdx + btcwire.MaxBlockHeadersPerMsg endIdx = startIdx + wire.MaxBlockHeadersPerMsg
} }
// Generate headers message and send it. // Generate headers message and send it.
@ -1025,7 +1025,7 @@ func (p *peer) handleGetHeadersMsg(msg *btcwire.MsgGetHeaders) {
// per invocation. Since the maximum number of headers per message // per invocation. Since the maximum number of headers per message
// might be larger, call it multiple times with the appropriate indices // might be larger, call it multiple times with the appropriate indices
// as needed. // as needed.
headersMsg := btcwire.NewMsgHeaders() headersMsg := wire.NewMsgHeaders()
for start := startIdx; start < endIdx; { for start := startIdx; start < endIdx; {
// Fetch the inventory from the block database. // Fetch the inventory from the block database.
hashList, err := p.server.db.FetchHeightRange(start, endIdx) hashList, err := p.server.db.FetchHeightRange(start, endIdx)
@ -1062,7 +1062,7 @@ func (p *peer) handleGetHeadersMsg(msg *btcwire.MsgGetHeaders) {
// message and is used by remote peers to add data to an already loaded bloom // message and is used by remote peers to add data to an already loaded bloom
// filter. The peer will be disconnected if a filter is not loaded when this // filter. The peer will be disconnected if a filter is not loaded when this
// message is received. // message is received.
func (p *peer) handleFilterAddMsg(msg *btcwire.MsgFilterAdd) { func (p *peer) handleFilterAddMsg(msg *wire.MsgFilterAdd) {
if !p.filter.IsLoaded() { if !p.filter.IsLoaded() {
peerLog.Debugf("%s sent a filteradd request with no filter "+ peerLog.Debugf("%s sent a filteradd request with no filter "+
"loaded -- disconnecting", p) "loaded -- disconnecting", p)
@ -1077,7 +1077,7 @@ func (p *peer) handleFilterAddMsg(msg *btcwire.MsgFilterAdd) {
// message and is used by remote peers to clear an already loaded bloom filter. // message and is used by remote peers to clear an already loaded bloom filter.
// The peer will be disconnected if a filter is not loaded when this message is // The peer will be disconnected if a filter is not loaded when this message is
// received. // received.
func (p *peer) handleFilterClearMsg(msg *btcwire.MsgFilterClear) { func (p *peer) handleFilterClearMsg(msg *wire.MsgFilterClear) {
if !p.filter.IsLoaded() { if !p.filter.IsLoaded() {
peerLog.Debugf("%s sent a filterclear request with no "+ peerLog.Debugf("%s sent a filterclear request with no "+
"filter loaded -- disconnecting", p) "filter loaded -- disconnecting", p)
@ -1090,7 +1090,7 @@ func (p *peer) handleFilterClearMsg(msg *btcwire.MsgFilterClear) {
// handleFilterLoadMsg is invoked when a peer receives a filterload bitcoin // handleFilterLoadMsg is invoked when a peer receives a filterload bitcoin
// message and it used to load a bloom filter that should be used for delivering // message and it used to load a bloom filter that should be used for delivering
// merkle blocks and associated transactions that match the filter. // merkle blocks and associated transactions that match the filter.
func (p *peer) handleFilterLoadMsg(msg *btcwire.MsgFilterLoad) { func (p *peer) handleFilterLoadMsg(msg *wire.MsgFilterLoad) {
// Transaction relay is no longer disabled once a filterload message is // Transaction relay is no longer disabled once a filterload message is
// received regardless of its original state. // received regardless of its original state.
p.relayMtx.Lock() p.relayMtx.Lock()
@ -1103,7 +1103,7 @@ func (p *peer) handleFilterLoadMsg(msg *btcwire.MsgFilterLoad) {
// handleGetAddrMsg is invoked when a peer receives a getaddr bitcoin message // handleGetAddrMsg is invoked when a peer receives a getaddr bitcoin message
// and is used to provide the peer with known addresses from the address // and is used to provide the peer with known addresses from the address
// manager. // manager.
func (p *peer) handleGetAddrMsg(msg *btcwire.MsgGetAddr) { func (p *peer) handleGetAddrMsg(msg *wire.MsgGetAddr) {
// Don't return any addresses when running on the simulation test // Don't return any addresses when running on the simulation test
// network. This helps prevent the network from becoming another // network. This helps prevent the network from becoming another
// public test network since it will not be able to learn about other // public test network since it will not be able to learn about other
@ -1126,7 +1126,7 @@ func (p *peer) handleGetAddrMsg(msg *btcwire.MsgGetAddr) {
// pushAddrMsg sends one, or more, addr message(s) to the connected peer using // pushAddrMsg sends one, or more, addr message(s) to the connected peer using
// the provided addresses. // the provided addresses.
func (p *peer) pushAddrMsg(addresses []*btcwire.NetAddress) error { func (p *peer) pushAddrMsg(addresses []*wire.NetAddress) error {
// Nothing to send. // Nothing to send.
if len(addresses) == 0 { if len(addresses) == 0 {
return nil return nil
@ -1134,7 +1134,7 @@ func (p *peer) pushAddrMsg(addresses []*btcwire.NetAddress) error {
r := prand.New(prand.NewSource(time.Now().UnixNano())) r := prand.New(prand.NewSource(time.Now().UnixNano()))
numAdded := 0 numAdded := 0
msg := btcwire.NewMsgAddr() msg := wire.NewMsgAddr()
for _, na := range addresses { for _, na := range addresses {
// Filter addresses the peer already knows about. // Filter addresses the peer already knows about.
if _, exists := p.knownAddresses[addrmgr.NetAddressKey(na)]; exists { if _, exists := p.knownAddresses[addrmgr.NetAddressKey(na)]; exists {
@ -1143,8 +1143,8 @@ func (p *peer) pushAddrMsg(addresses []*btcwire.NetAddress) error {
// If the maxAddrs limit has been reached, randomize the list // If the maxAddrs limit has been reached, randomize the list
// with the remaining addresses. // with the remaining addresses.
if numAdded == btcwire.MaxAddrPerMsg { if numAdded == wire.MaxAddrPerMsg {
msg.AddrList[r.Intn(btcwire.MaxAddrPerMsg)] = na msg.AddrList[r.Intn(wire.MaxAddrPerMsg)] = na
continue continue
} }
@ -1168,7 +1168,7 @@ func (p *peer) pushAddrMsg(addresses []*btcwire.NetAddress) error {
// handleAddrMsg is invoked when a peer receives an addr bitcoin message and // handleAddrMsg is invoked when a peer receives an addr bitcoin message and
// is used to notify the server about advertised addresses. // is used to notify the server about advertised addresses.
func (p *peer) handleAddrMsg(msg *btcwire.MsgAddr) { func (p *peer) handleAddrMsg(msg *wire.MsgAddr) {
// Ignore addresses when running on the simulation test network. This // Ignore addresses when running on the simulation test network. This
// helps prevent the network from becoming another public test network // helps prevent the network from becoming another public test network
// since it will not be able to learn about other peers that have not // since it will not be able to learn about other peers that have not
@ -1178,7 +1178,7 @@ func (p *peer) handleAddrMsg(msg *btcwire.MsgAddr) {
} }
// Ignore old style addresses which don't include a timestamp. // Ignore old style addresses which don't include a timestamp.
if p.ProtocolVersion() < btcwire.NetAddressTimeVersion { if p.ProtocolVersion() < wire.NetAddressTimeVersion {
return return
} }
@ -1220,11 +1220,11 @@ func (p *peer) handleAddrMsg(msg *btcwire.MsgAddr) {
// recent clients (protocol version > BIP0031Version), it replies with a pong // recent clients (protocol version > BIP0031Version), it replies with a pong
// message. For older clients, it does nothing and anything other than failure // message. For older clients, it does nothing and anything other than failure
// is considered a successful ping. // is considered a successful ping.
func (p *peer) handlePingMsg(msg *btcwire.MsgPing) { func (p *peer) handlePingMsg(msg *wire.MsgPing) {
// Only Reply with pong is message comes from a new enough client. // Only Reply with pong is message comes from a new enough client.
if p.ProtocolVersion() > btcwire.BIP0031Version { if p.ProtocolVersion() > wire.BIP0031Version {
// Include nonce from ping so pong can be identified. // Include nonce from ping so pong can be identified.
p.QueueMessage(btcwire.NewMsgPong(msg.Nonce), nil) p.QueueMessage(wire.NewMsgPong(msg.Nonce), nil)
} }
} }
@ -1232,7 +1232,7 @@ func (p *peer) handlePingMsg(msg *btcwire.MsgPing) {
// recent clients (protocol version > BIP0031Version), and if we had send a ping // recent clients (protocol version > BIP0031Version), and if we had send a ping
// previosuly we update our ping time statistics. If the client is too old or // previosuly we update our ping time statistics. If the client is too old or
// we had not send a ping we ignore it. // we had not send a ping we ignore it.
func (p *peer) handlePongMsg(msg *btcwire.MsgPong) { func (p *peer) handlePongMsg(msg *wire.MsgPong) {
p.StatsMtx.Lock() p.StatsMtx.Lock()
defer p.StatsMtx.Unlock() defer p.StatsMtx.Unlock()
@ -1244,7 +1244,7 @@ func (p *peer) handlePongMsg(msg *btcwire.MsgPong) {
// without large usage of the ping rpc call since we ping // without large usage of the ping rpc call since we ping
// infrequently enough that if they overlap we would have timed out // infrequently enough that if they overlap we would have timed out
// the peer. // the peer.
if p.protocolVersion > btcwire.BIP0031Version && if p.protocolVersion > wire.BIP0031Version &&
p.lastPingNonce != 0 && msg.Nonce == p.lastPingNonce { p.lastPingNonce != 0 && msg.Nonce == p.lastPingNonce {
p.lastPingMicros = time.Now().Sub(p.lastPingTime).Nanoseconds() p.lastPingMicros = time.Now().Sub(p.lastPingTime).Nanoseconds()
p.lastPingMicros /= 1000 // convert to usec. p.lastPingMicros /= 1000 // convert to usec.
@ -1253,8 +1253,8 @@ func (p *peer) handlePongMsg(msg *btcwire.MsgPong) {
} }
// readMessage reads the next bitcoin message from the peer with logging. // readMessage reads the next bitcoin message from the peer with logging.
func (p *peer) readMessage() (btcwire.Message, []byte, error) { func (p *peer) readMessage() (wire.Message, []byte, error) {
n, msg, buf, err := btcwire.ReadMessageN(p.conn, p.ProtocolVersion(), n, msg, buf, err := wire.ReadMessageN(p.conn, p.ProtocolVersion(),
p.btcnet) p.btcnet)
p.StatsMtx.Lock() p.StatsMtx.Lock()
p.bytesReceived += uint64(n) p.bytesReceived += uint64(n)
@ -1286,16 +1286,16 @@ func (p *peer) readMessage() (btcwire.Message, []byte, error) {
} }
// writeMessage sends a bitcoin Message to the peer with logging. // writeMessage sends a bitcoin Message to the peer with logging.
func (p *peer) writeMessage(msg btcwire.Message) { func (p *peer) writeMessage(msg wire.Message) {
// Don't do anything if we're disconnecting. // Don't do anything if we're disconnecting.
if atomic.LoadInt32(&p.disconnect) != 0 { if atomic.LoadInt32(&p.disconnect) != 0 {
return return
} }
if !p.VersionKnown() { if !p.VersionKnown() {
switch msg.(type) { switch msg.(type) {
case *btcwire.MsgVersion: case *wire.MsgVersion:
// This is OK. // This is OK.
case *btcwire.MsgReject: case *wire.MsgReject:
// This is OK. // This is OK.
default: default:
// Drop all messages other than version and reject if // Drop all messages other than version and reject if
@ -1320,7 +1320,7 @@ func (p *peer) writeMessage(msg btcwire.Message) {
})) }))
peerLog.Tracef("%v", newLogClosure(func() string { peerLog.Tracef("%v", newLogClosure(func() string {
var buf bytes.Buffer var buf bytes.Buffer
err := btcwire.WriteMessage(&buf, msg, p.ProtocolVersion(), err := wire.WriteMessage(&buf, msg, p.ProtocolVersion(),
p.btcnet) p.btcnet)
if err != nil { if err != nil {
return err.Error() return err.Error()
@ -1329,7 +1329,7 @@ func (p *peer) writeMessage(msg btcwire.Message) {
})) }))
// Write the message to the peer. // Write the message to the peer.
n, err := btcwire.WriteMessageN(p.conn, msg, p.ProtocolVersion(), n, err := wire.WriteMessageN(p.conn, msg, p.ProtocolVersion(),
p.btcnet) p.btcnet)
p.StatsMtx.Lock() p.StatsMtx.Lock()
p.bytesSent += uint64(n) p.bytesSent += uint64(n)
@ -1349,7 +1349,7 @@ func (p *peer) writeMessage(msg btcwire.Message) {
func (p *peer) isAllowedByRegression(err error) bool { func (p *peer) isAllowedByRegression(err error) bool {
// Don't allow the error if it's not specifically a malformed message // Don't allow the error if it's not specifically a malformed message
// error. // error.
if _, ok := err.(*btcwire.MessageError); !ok { if _, ok := err.(*wire.MessageError); !ok {
return false return false
} }
@ -1420,7 +1420,7 @@ out:
// btcwire, so just used malformed for // btcwire, so just used malformed for
// the command. // the command.
p.PushRejectMsg("malformed", p.PushRejectMsg("malformed",
btcwire.RejectMalformed, errMsg, wire.RejectMalformed, errMsg,
nil, true) nil, true)
} }
@ -1432,13 +1432,13 @@ out:
p.StatsMtx.Unlock() p.StatsMtx.Unlock()
// Ensure version message comes first. // Ensure version message comes first.
if vmsg, ok := rmsg.(*btcwire.MsgVersion); !ok && !p.VersionKnown() { if vmsg, ok := rmsg.(*wire.MsgVersion); !ok && !p.VersionKnown() {
errStr := "A version message must precede all others" errStr := "A version message must precede all others"
p.logError(errStr) p.logError(errStr)
// Push a reject message and wait for the message to be // Push a reject message and wait for the message to be
// sent before disconnecting. // sent before disconnecting.
p.PushRejectMsg(vmsg.Command(), btcwire.RejectMalformed, p.PushRejectMsg(vmsg.Command(), wire.RejectMalformed,
errStr, nil, true) errStr, nil, true)
break out break out
} }
@ -1446,28 +1446,28 @@ out:
// Handle each supported message type. // Handle each supported message type.
markConnected := false markConnected := false
switch msg := rmsg.(type) { switch msg := rmsg.(type) {
case *btcwire.MsgVersion: case *wire.MsgVersion:
p.handleVersionMsg(msg) p.handleVersionMsg(msg)
markConnected = true markConnected = true
case *btcwire.MsgVerAck: case *wire.MsgVerAck:
// Do nothing. // Do nothing.
case *btcwire.MsgGetAddr: case *wire.MsgGetAddr:
p.handleGetAddrMsg(msg) p.handleGetAddrMsg(msg)
case *btcwire.MsgAddr: case *wire.MsgAddr:
p.handleAddrMsg(msg) p.handleAddrMsg(msg)
markConnected = true markConnected = true
case *btcwire.MsgPing: case *wire.MsgPing:
p.handlePingMsg(msg) p.handlePingMsg(msg)
markConnected = true markConnected = true
case *btcwire.MsgPong: case *wire.MsgPong:
p.handlePongMsg(msg) p.handlePongMsg(msg)
case *btcwire.MsgAlert: case *wire.MsgAlert:
// Intentionally ignore alert messages. // Intentionally ignore alert messages.
// //
// The reference client currently bans peers that send // The reference client currently bans peers that send
@ -1477,48 +1477,48 @@ out:
// implementions' alert messages, we will not relay // implementions' alert messages, we will not relay
// theirs. // theirs.
case *btcwire.MsgMemPool: case *wire.MsgMemPool:
p.handleMemPoolMsg(msg) p.handleMemPoolMsg(msg)
case *btcwire.MsgTx: case *wire.MsgTx:
p.handleTxMsg(msg) p.handleTxMsg(msg)
case *btcwire.MsgBlock: case *wire.MsgBlock:
p.handleBlockMsg(msg, buf) p.handleBlockMsg(msg, buf)
case *btcwire.MsgInv: case *wire.MsgInv:
p.handleInvMsg(msg) p.handleInvMsg(msg)
markConnected = true markConnected = true
case *btcwire.MsgHeaders: case *wire.MsgHeaders:
p.handleHeadersMsg(msg) p.handleHeadersMsg(msg)
case *btcwire.MsgNotFound: case *wire.MsgNotFound:
// TODO(davec): Ignore this for now, but ultimately // TODO(davec): Ignore this for now, but ultimately
// it should probably be used to detect when something // it should probably be used to detect when something
// we requested needs to be re-requested from another // we requested needs to be re-requested from another
// peer. // peer.
case *btcwire.MsgGetData: case *wire.MsgGetData:
p.handleGetDataMsg(msg) p.handleGetDataMsg(msg)
markConnected = true markConnected = true
case *btcwire.MsgGetBlocks: case *wire.MsgGetBlocks:
p.handleGetBlocksMsg(msg) p.handleGetBlocksMsg(msg)
case *btcwire.MsgGetHeaders: case *wire.MsgGetHeaders:
p.handleGetHeadersMsg(msg) p.handleGetHeadersMsg(msg)
case *btcwire.MsgFilterAdd: case *wire.MsgFilterAdd:
p.handleFilterAddMsg(msg) p.handleFilterAddMsg(msg)
case *btcwire.MsgFilterClear: case *wire.MsgFilterClear:
p.handleFilterClearMsg(msg) p.handleFilterClearMsg(msg)
case *btcwire.MsgFilterLoad: case *wire.MsgFilterLoad:
p.handleFilterLoadMsg(msg) p.handleFilterLoadMsg(msg)
case *btcwire.MsgReject: case *wire.MsgReject:
// Nothing to do currently. Logging of the rejected // Nothing to do currently. Logging of the rejected
// message is handled already in readMessage. // message is handled already in readMessage.
@ -1632,9 +1632,9 @@ out:
// Create and send as many inv messages as needed to // Create and send as many inv messages as needed to
// drain the inventory send queue. // drain the inventory send queue.
invMsg := btcwire.NewMsgInv() invMsg := wire.NewMsgInv()
for e := invSendQueue.Front(); e != nil; e = invSendQueue.Front() { for e := invSendQueue.Front(); e != nil; e = invSendQueue.Front() {
iv := invSendQueue.Remove(e).(*btcwire.InvVect) iv := invSendQueue.Remove(e).(*wire.InvVect)
// Don't send inventory that became known after // Don't send inventory that became known after
// the initial check. // the initial check.
@ -1647,7 +1647,7 @@ out:
waiting = queuePacket( waiting = queuePacket(
outMsg{msg: invMsg}, outMsg{msg: invMsg},
pendingMsgs, waiting) pendingMsgs, waiting)
invMsg = btcwire.NewMsgInv() invMsg = wire.NewMsgInv()
} }
// Add the inventory that is being relayed to // Add the inventory that is being relayed to
@ -1696,13 +1696,13 @@ cleanup:
// allowing the sender to continue running asynchronously. // allowing the sender to continue running asynchronously.
func (p *peer) outHandler() { func (p *peer) outHandler() {
pingTimer := time.AfterFunc(pingTimeoutMinutes*time.Minute, func() { pingTimer := time.AfterFunc(pingTimeoutMinutes*time.Minute, func() {
nonce, err := btcwire.RandomUint64() nonce, err := wire.RandomUint64()
if err != nil { if err != nil {
peerLog.Errorf("Not sending ping on timeout to %s: %v", peerLog.Errorf("Not sending ping on timeout to %s: %v",
p, err) p, err)
return return
} }
p.QueueMessage(btcwire.NewMsgPing(nonce), nil) p.QueueMessage(wire.NewMsgPing(nonce), nil)
}) })
out: out:
for { for {
@ -1719,24 +1719,24 @@ out:
peerLog.Tracef("%s: received from queuehandler", p) peerLog.Tracef("%s: received from queuehandler", p)
reset := true reset := true
switch m := msg.msg.(type) { switch m := msg.msg.(type) {
case *btcwire.MsgVersion: case *wire.MsgVersion:
// should get an ack // should get an ack
case *btcwire.MsgGetAddr: case *wire.MsgGetAddr:
// should get addresses // should get addresses
case *btcwire.MsgPing: case *wire.MsgPing:
// expects pong // expects pong
// Also set up statistics. // Also set up statistics.
p.StatsMtx.Lock() p.StatsMtx.Lock()
if p.protocolVersion > btcwire.BIP0031Version { if p.protocolVersion > wire.BIP0031Version {
p.lastPingNonce = m.Nonce p.lastPingNonce = m.Nonce
p.lastPingTime = time.Now() p.lastPingTime = time.Now()
} }
p.StatsMtx.Unlock() p.StatsMtx.Unlock()
case *btcwire.MsgMemPool: case *wire.MsgMemPool:
// Should return an inv. // Should return an inv.
case *btcwire.MsgGetData: case *wire.MsgGetData:
// Should get us block, tx, or not found. // Should get us block, tx, or not found.
case *btcwire.MsgGetHeaders: case *wire.MsgGetHeaders:
// Should get us headers back. // Should get us headers back.
default: default:
// Not one of the above, no sure reply. // Not one of the above, no sure reply.
@ -1789,7 +1789,7 @@ cleanup:
// QueueMessage adds the passed bitcoin message to the peer send queue. It // QueueMessage adds the passed bitcoin message to the peer send queue. It
// uses a buffered channel to communicate with the output handler goroutine so // uses a buffered channel to communicate with the output handler goroutine so
// it is automatically rate limited and safe for concurrent access. // it is automatically rate limited and safe for concurrent access.
func (p *peer) QueueMessage(msg btcwire.Message, doneChan chan struct{}) { func (p *peer) QueueMessage(msg wire.Message, doneChan chan struct{}) {
// Avoid risk of deadlock if goroutine already exited. The goroutine // Avoid risk of deadlock if goroutine already exited. The goroutine
// we will be sending to hangs around until it knows for a fact that // we will be sending to hangs around until it knows for a fact that
// it is marked as disconnected. *then* it drains the channels. // it is marked as disconnected. *then* it drains the channels.
@ -1809,7 +1809,7 @@ func (p *peer) QueueMessage(msg btcwire.Message, doneChan chan struct{}) {
// might not be sent right away, rather it is trickled to the peer in batches. // might not be sent right away, rather it is trickled to the peer in batches.
// Inventory that the peer is already known to have is ignored. It is safe for // Inventory that the peer is already known to have is ignored. It is safe for
// concurrent access. // concurrent access.
func (p *peer) QueueInventory(invVect *btcwire.InvVect) { func (p *peer) QueueInventory(invVect *wire.InvVect) {
// Don't add the inventory to the send queue if the peer is // Don't add the inventory to the send queue if the peer is
// already known to have it. // already known to have it.
if p.isKnownInventory(invVect) { if p.isKnownInventory(invVect) {
@ -1891,17 +1891,17 @@ func newPeerBase(s *server, inbound bool) *peer {
server: s, server: s,
protocolVersion: maxProtocolVersion, protocolVersion: maxProtocolVersion,
btcnet: s.netParams.Net, btcnet: s.netParams.Net,
services: btcwire.SFNodeNetwork, services: wire.SFNodeNetwork,
inbound: inbound, inbound: inbound,
knownAddresses: make(map[string]struct{}), knownAddresses: make(map[string]struct{}),
knownInventory: NewMruInventoryMap(maxKnownInventory), knownInventory: NewMruInventoryMap(maxKnownInventory),
requestedTxns: make(map[btcwire.ShaHash]struct{}), requestedTxns: make(map[wire.ShaHash]struct{}),
requestedBlocks: make(map[btcwire.ShaHash]struct{}), requestedBlocks: make(map[wire.ShaHash]struct{}),
filter: bloom.LoadFilter(nil), filter: bloom.LoadFilter(nil),
outputQueue: make(chan outMsg, outputBufferSize), outputQueue: make(chan outMsg, outputBufferSize),
sendQueue: make(chan outMsg, 1), // nonblocking sync sendQueue: make(chan outMsg, 1), // nonblocking sync
sendDoneQueue: make(chan struct{}, 1), // nonblocking sync sendDoneQueue: make(chan struct{}, 1), // nonblocking sync
outputInvChan: make(chan *btcwire.InvVect, outputBufferSize), outputInvChan: make(chan *wire.InvVect, outputBufferSize),
txProcessed: make(chan struct{}, 1), txProcessed: make(chan struct{}, 1),
blockProcessed: make(chan struct{}, 1), blockProcessed: make(chan struct{}, 1),
quit: make(chan struct{}), quit: make(chan struct{}),

View file

@ -29,11 +29,11 @@ import (
"github.com/btcsuite/btcd/blockchain" "github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcd/txscript" "github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcec" "github.com/btcsuite/btcec"
"github.com/btcsuite/btcjson" "github.com/btcsuite/btcjson"
"github.com/btcsuite/btcnet" "github.com/btcsuite/btcnet"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
"github.com/btcsuite/btcws" "github.com/btcsuite/btcws"
"github.com/btcsuite/fastsha256" "github.com/btcsuite/fastsha256"
"github.com/btcsuite/websocket" "github.com/btcsuite/websocket"
@ -56,14 +56,14 @@ const (
// by length of the message in bits encoded as a big-endian uint64 // by length of the message in bits encoded as a big-endian uint64
// (8 bytes). Thus, the resulting length is a multiple of the sha256 // (8 bytes). Thus, the resulting length is a multiple of the sha256
// block size (64 bytes). // block size (64 bytes).
getworkDataLen = (1 + ((btcwire.MaxBlockHeaderPayload + 8) / getworkDataLen = (1 + ((wire.MaxBlockHeaderPayload + 8) /
fastsha256.BlockSize)) * fastsha256.BlockSize fastsha256.BlockSize)) * fastsha256.BlockSize
// hash1Len is the length of the hash1 field of the getwork RPC. It // hash1Len is the length of the hash1 field of the getwork RPC. It
// consists of a zero hash plus the internal sha256 padding. See // consists of a zero hash plus the internal sha256 padding. See
// the getworkDataLen comment for details about the internal sha256 // the getworkDataLen comment for details about the internal sha256
// padding format. // padding format.
hash1Len = (1 + ((btcwire.HashSize + 8) / fastsha256.BlockSize)) * hash1Len = (1 + ((wire.HashSize + 8) / fastsha256.BlockSize)) *
fastsha256.BlockSize fastsha256.BlockSize
// gbtNonceRange is two 32-bit big-endian hexadecimal integers which // gbtNonceRange is two 32-bit big-endian hexadecimal integers which
@ -225,7 +225,7 @@ func builderScript(builder *txscript.ScriptBuilder) []byte {
// workStateBlockInfo houses information about how to reconstruct a block given // workStateBlockInfo houses information about how to reconstruct a block given
// its template and signature script. // its template and signature script.
type workStateBlockInfo struct { type workStateBlockInfo struct {
msgBlock *btcwire.MsgBlock msgBlock *wire.MsgBlock
signatureScript []byte signatureScript []byte
} }
@ -235,17 +235,17 @@ type workState struct {
sync.Mutex sync.Mutex
lastTxUpdate time.Time lastTxUpdate time.Time
lastGenerated time.Time lastGenerated time.Time
prevHash *btcwire.ShaHash prevHash *wire.ShaHash
msgBlock *btcwire.MsgBlock msgBlock *wire.MsgBlock
extraNonce uint64 extraNonce uint64
blockInfo map[btcwire.ShaHash]*workStateBlockInfo blockInfo map[wire.ShaHash]*workStateBlockInfo
} }
// newWorkState returns a new instance of a workState with all internal fields // newWorkState returns a new instance of a workState with all internal fields
// initialized and ready to use. // initialized and ready to use.
func newWorkState() *workState { func newWorkState() *workState {
return &workState{ return &workState{
blockInfo: make(map[btcwire.ShaHash]*workStateBlockInfo), blockInfo: make(map[wire.ShaHash]*workStateBlockInfo),
} }
} }
@ -255,10 +255,10 @@ type gbtWorkState struct {
sync.Mutex sync.Mutex
lastTxUpdate time.Time lastTxUpdate time.Time
lastGenerated time.Time lastGenerated time.Time
prevHash *btcwire.ShaHash prevHash *wire.ShaHash
minTimestamp time.Time minTimestamp time.Time
template *BlockTemplate template *BlockTemplate
notifyMap map[btcwire.ShaHash]map[int64]chan struct{} notifyMap map[wire.ShaHash]map[int64]chan struct{}
timeSource blockchain.MedianTimeSource timeSource blockchain.MedianTimeSource
} }
@ -266,7 +266,7 @@ type gbtWorkState struct {
// fields initialized and ready to use. // fields initialized and ready to use.
func newGbtWorkState(timeSource blockchain.MedianTimeSource) *gbtWorkState { func newGbtWorkState(timeSource blockchain.MedianTimeSource) *gbtWorkState {
return &gbtWorkState{ return &gbtWorkState{
notifyMap: make(map[btcwire.ShaHash]map[int64]chan struct{}), notifyMap: make(map[wire.ShaHash]map[int64]chan struct{}),
timeSource: timeSource, timeSource: timeSource,
} }
} }
@ -727,7 +727,7 @@ func handleAddNode(s *rpcServer, cmd btcjson.Cmd, closeChan <-chan struct{}) (in
// messageToHex serializes a message to the wire protocol encoding using the // messageToHex serializes a message to the wire protocol encoding using the
// latest protocol version and returns a hex-encoded string of the result. // latest protocol version and returns a hex-encoded string of the result.
func messageToHex(msg btcwire.Message) (string, error) { func messageToHex(msg wire.Message) (string, error) {
var buf bytes.Buffer var buf bytes.Buffer
err := msg.BtcEncode(&buf, maxProtocolVersion) err := msg.BtcEncode(&buf, maxProtocolVersion)
if err != nil { if err != nil {
@ -745,9 +745,9 @@ func handleCreateRawTransaction(s *rpcServer, cmd btcjson.Cmd, closeChan <-chan
// Add all transaction inputs to a new transaction after performing // Add all transaction inputs to a new transaction after performing
// some validity checks. // some validity checks.
mtx := btcwire.NewMsgTx() mtx := wire.NewMsgTx()
for _, input := range c.Inputs { for _, input := range c.Inputs {
txHash, err := btcwire.NewShaHashFromStr(input.Txid) txHash, err := wire.NewShaHashFromStr(input.Txid)
if err != nil { if err != nil {
return nil, btcjson.ErrDecodeHexString return nil, btcjson.ErrDecodeHexString
} }
@ -759,8 +759,8 @@ func handleCreateRawTransaction(s *rpcServer, cmd btcjson.Cmd, closeChan <-chan
} }
} }
prevOut := btcwire.NewOutPoint(txHash, uint32(input.Vout)) prevOut := wire.NewOutPoint(txHash, uint32(input.Vout))
txIn := btcwire.NewTxIn(prevOut, []byte{}) txIn := wire.NewTxIn(prevOut, []byte{})
mtx.AddTxIn(txIn) mtx.AddTxIn(txIn)
} }
@ -813,7 +813,7 @@ func handleCreateRawTransaction(s *rpcServer, cmd btcjson.Cmd, closeChan <-chan
} }
} }
txOut := btcwire.NewTxOut(amount, pkScript) txOut := wire.NewTxOut(amount, pkScript)
mtx.AddTxOut(txOut) mtx.AddTxOut(txOut)
} }
@ -848,7 +848,7 @@ func handleDebugLevel(s *rpcServer, cmd btcjson.Cmd, closeChan <-chan struct{})
// createVinList returns a slice of JSON objects for the inputs of the passed // createVinList returns a slice of JSON objects for the inputs of the passed
// transaction. // transaction.
func createVinList(mtx *btcwire.MsgTx) []btcjson.Vin { func createVinList(mtx *wire.MsgTx) []btcjson.Vin {
tx := btcutil.NewTx(mtx) tx := btcutil.NewTx(mtx)
vinList := make([]btcjson.Vin, len(mtx.TxIn)) vinList := make([]btcjson.Vin, len(mtx.TxIn))
for i, v := range mtx.TxIn { for i, v := range mtx.TxIn {
@ -874,7 +874,7 @@ func createVinList(mtx *btcwire.MsgTx) []btcjson.Vin {
// createVoutList returns a slice of JSON objects for the outputs of the passed // createVoutList returns a slice of JSON objects for the outputs of the passed
// transaction. // transaction.
func createVoutList(mtx *btcwire.MsgTx, net *btcnet.Params) []btcjson.Vout { func createVoutList(mtx *wire.MsgTx, net *btcnet.Params) []btcjson.Vout {
voutList := make([]btcjson.Vout, len(mtx.TxOut)) voutList := make([]btcjson.Vout, len(mtx.TxOut))
for i, v := range mtx.TxOut { for i, v := range mtx.TxOut {
voutList[i].N = uint32(i) voutList[i].N = uint32(i)
@ -908,9 +908,9 @@ func createVoutList(mtx *btcwire.MsgTx, net *btcnet.Params) []btcjson.Vout {
// createTxRawResult converts the passed transaction and associated parameters // createTxRawResult converts the passed transaction and associated parameters
// to a raw transaction JSON object. // to a raw transaction JSON object.
func createTxRawResult(net *btcnet.Params, txSha string, mtx *btcwire.MsgTx, func createTxRawResult(net *btcnet.Params, txSha string, mtx *wire.MsgTx,
blk *btcutil.Block, maxidx int64, blk *btcutil.Block, maxidx int64,
blksha *btcwire.ShaHash) (*btcjson.TxRawResult, error) { blksha *wire.ShaHash) (*btcjson.TxRawResult, error) {
mtxHex, err := messageToHex(mtx) mtxHex, err := messageToHex(mtx)
if err != nil { if err != nil {
@ -957,7 +957,7 @@ func handleDecodeRawTransaction(s *rpcServer, cmd btcjson.Cmd, closeChan <-chan
"string (not %q)", hexStr), "string (not %q)", hexStr),
} }
} }
var mtx btcwire.MsgTx var mtx wire.MsgTx
err = mtx.Deserialize(bytes.NewReader(serializedTx)) err = mtx.Deserialize(bytes.NewReader(serializedTx))
if err != nil { if err != nil {
return nil, btcjson.Error{ return nil, btcjson.Error{
@ -1144,7 +1144,7 @@ func handleGetBestBlockHash(s *rpcServer, cmd btcjson.Cmd, closeChan <-chan stru
// handleGetBlock implements the getblock command. // handleGetBlock implements the getblock command.
func handleGetBlock(s *rpcServer, cmd btcjson.Cmd, closeChan <-chan struct{}) (interface{}, error) { func handleGetBlock(s *rpcServer, cmd btcjson.Cmd, closeChan <-chan struct{}) (interface{}, error) {
c := cmd.(*btcjson.GetBlockCmd) c := cmd.(*btcjson.GetBlockCmd)
sha, err := btcwire.NewShaHashFromStr(c.Hash) sha, err := wire.NewShaHashFromStr(c.Hash)
if err != nil { if err != nil {
rpcsLog.Errorf("Error generating sha: %v", err) rpcsLog.Errorf("Error generating sha: %v", err)
return nil, btcjson.ErrBlockNotFound return nil, btcjson.ErrBlockNotFound
@ -1225,7 +1225,7 @@ func handleGetBlock(s *rpcServer, cmd btcjson.Cmd, closeChan <-chan struct{}) (i
// Get next block unless we are already at the top. // Get next block unless we are already at the top.
if idx < maxidx { if idx < maxidx {
var shaNext *btcwire.ShaHash var shaNext *wire.ShaHash
shaNext, err = s.server.db.FetchBlockShaByHeight(int64(idx + 1)) shaNext, err = s.server.db.FetchBlockShaByHeight(int64(idx + 1))
if err != nil { if err != nil {
rpcsLog.Errorf("No next block: %v", err) rpcsLog.Errorf("No next block: %v", err)
@ -1262,7 +1262,7 @@ func handleGetBlockHash(s *rpcServer, cmd btcjson.Cmd, closeChan <-chan struct{}
// encodeTemplateID encodes the passed details into an ID that can be used to // encodeTemplateID encodes the passed details into an ID that can be used to
// uniquely identify a block template. // uniquely identify a block template.
func encodeTemplateID(prevHash *btcwire.ShaHash, lastGenerated time.Time) string { func encodeTemplateID(prevHash *wire.ShaHash, lastGenerated time.Time) string {
return fmt.Sprintf("%s-%d", prevHash.String(), lastGenerated.Unix()) return fmt.Sprintf("%s-%d", prevHash.String(), lastGenerated.Unix())
} }
@ -1271,13 +1271,13 @@ func encodeTemplateID(prevHash *btcwire.ShaHash, lastGenerated time.Time) string
// that are using long polling for block templates. The ID consists of the // that are using long polling for block templates. The ID consists of the
// previous block hash for the associated template and the time the associated // previous block hash for the associated template and the time the associated
// template was generated. // template was generated.
func decodeTemplateID(templateID string) (*btcwire.ShaHash, int64, error) { func decodeTemplateID(templateID string) (*wire.ShaHash, int64, error) {
fields := strings.Split(templateID, "-") fields := strings.Split(templateID, "-")
if len(fields) != 2 { if len(fields) != 2 {
return nil, 0, errors.New("invalid longpollid format") return nil, 0, errors.New("invalid longpollid format")
} }
prevHash, err := btcwire.NewShaHashFromStr(fields[0]) prevHash, err := wire.NewShaHashFromStr(fields[0])
if err != nil { if err != nil {
return nil, 0, errors.New("invalid longpollid format") return nil, 0, errors.New("invalid longpollid format")
} }
@ -1293,7 +1293,7 @@ func decodeTemplateID(templateID string) (*btcwire.ShaHash, int64, error) {
// notified when block templates are stale. // notified when block templates are stale.
// //
// This function MUST be called with the state locked. // This function MUST be called with the state locked.
func (state *gbtWorkState) notifyLongPollers(latestHash *btcwire.ShaHash, lastGenerated time.Time) { func (state *gbtWorkState) notifyLongPollers(latestHash *wire.ShaHash, lastGenerated time.Time) {
// Notify anything that is waiting for a block template update from a // Notify anything that is waiting for a block template update from a
// hash which is not the hash of the tip of the best chain since their // hash which is not the hash of the tip of the best chain since their
// work is now invalid. // work is now invalid.
@ -1340,7 +1340,7 @@ func (state *gbtWorkState) notifyLongPollers(latestHash *btcwire.ShaHash, lastGe
// NotifyBlockConnected uses the newly-connected block to notify any long poll // NotifyBlockConnected uses the newly-connected block to notify any long poll
// clients with a new block template when their existing block template is // clients with a new block template when their existing block template is
// stale due to the newly connected block. // stale due to the newly connected block.
func (state *gbtWorkState) NotifyBlockConnected(blockSha *btcwire.ShaHash) { func (state *gbtWorkState) NotifyBlockConnected(blockSha *wire.ShaHash) {
go func() { go func() {
state.Lock() state.Lock()
defer state.Unlock() defer state.Unlock()
@ -1379,7 +1379,7 @@ func (state *gbtWorkState) NotifyMempoolTx(lastUpdated time.Time) {
// without requiring a different channel for each client. // without requiring a different channel for each client.
// //
// This function MUST be called with the state locked. // This function MUST be called with the state locked.
func (state *gbtWorkState) templateUpdateChan(prevHash *btcwire.ShaHash, lastGenerated int64) chan struct{} { func (state *gbtWorkState) templateUpdateChan(prevHash *wire.ShaHash, lastGenerated int64) chan struct{} {
// Either get the current list of channels waiting for updates about // Either get the current list of channels waiting for updates about
// changes to block template for the previous hash or create a new one. // changes to block template for the previous hash or create a new one.
channels, ok := state.notifyMap[*prevHash] channels, ok := state.notifyMap[*prevHash]
@ -1422,7 +1422,7 @@ func (state *gbtWorkState) updateBlockTemplate(s *rpcServer, useCoinbaseValue bo
// changed or the transactions in the memory pool have been updated and // changed or the transactions in the memory pool have been updated and
// it has been at least gbtRegenerateSecond since the last template was // it has been at least gbtRegenerateSecond since the last template was
// generated. // generated.
var msgBlock *btcwire.MsgBlock var msgBlock *wire.MsgBlock
var targetDifficulty string var targetDifficulty string
latestHash, _ := s.server.blockManager.chainState.Best() latestHash, _ := s.server.blockManager.chainState.Best()
template := state.template template := state.template
@ -1577,7 +1577,7 @@ func (state *gbtWorkState) blockTemplateResult(useCoinbaseValue bool, submitOld
// the adjustments to the various lengths and indices. // the adjustments to the various lengths and indices.
numTx := len(msgBlock.Transactions) numTx := len(msgBlock.Transactions)
transactions := make([]btcjson.GetBlockTemplateResultTx, 0, numTx-1) transactions := make([]btcjson.GetBlockTemplateResultTx, 0, numTx-1)
txIndex := make(map[btcwire.ShaHash]int64, numTx) txIndex := make(map[wire.ShaHash]int64, numTx)
for i, tx := range msgBlock.Transactions { for i, tx := range msgBlock.Transactions {
txHash, _ := tx.TxSha() txHash, _ := tx.TxSha()
txIndex[txHash] = int64(i) txIndex[txHash] = int64(i)
@ -1635,7 +1635,7 @@ func (state *gbtWorkState) blockTemplateResult(useCoinbaseValue bool, submitOld
Height: template.height, Height: template.height,
PreviousHash: header.PrevBlock.String(), PreviousHash: header.PrevBlock.String(),
SigOpLimit: blockchain.MaxSigOpsPerBlock, SigOpLimit: blockchain.MaxSigOpsPerBlock,
SizeLimit: btcwire.MaxBlockPayload, SizeLimit: wire.MaxBlockPayload,
Transactions: transactions, Transactions: transactions,
Version: header.Version, Version: header.Version,
LongPollID: templateID, LongPollID: templateID,
@ -1982,7 +1982,7 @@ func handleGetBlockTemplateProposal(s *rpcServer, request *btcjson.TemplateReque
"hexadecimal string (not %q)", hexData), "hexadecimal string (not %q)", hexData),
} }
} }
var msgBlock btcwire.MsgBlock var msgBlock wire.MsgBlock
if err := msgBlock.Deserialize(bytes.NewReader(dataBytes)); err != nil { if err := msgBlock.Deserialize(bytes.NewReader(dataBytes)); err != nil {
return nil, btcjson.Error{ return nil, btcjson.Error{
Code: btcjson.ErrDeserialization.Code, Code: btcjson.ErrDeserialization.Code,
@ -2343,7 +2343,7 @@ func handleGetRawTransaction(s *rpcServer, cmd btcjson.Cmd, closeChan <-chan str
c := cmd.(*btcjson.GetRawTransactionCmd) c := cmd.(*btcjson.GetRawTransactionCmd)
// Convert the provided transaction hash hex to a ShaHash. // Convert the provided transaction hash hex to a ShaHash.
txSha, err := btcwire.NewShaHashFromStr(c.Txid) txSha, err := wire.NewShaHashFromStr(c.Txid)
if err != nil { if err != nil {
rpcsLog.Errorf("Error generating sha: %v", err) rpcsLog.Errorf("Error generating sha: %v", err)
return nil, btcjson.Error{ return nil, btcjson.Error{
@ -2354,8 +2354,8 @@ func handleGetRawTransaction(s *rpcServer, cmd btcjson.Cmd, closeChan <-chan str
// Try to fetch the transaction from the memory pool and if that fails, // Try to fetch the transaction from the memory pool and if that fails,
// try the block database. // try the block database.
var mtx *btcwire.MsgTx var mtx *wire.MsgTx
var blksha *btcwire.ShaHash var blksha *wire.ShaHash
tx, err := s.server.txMemPool.FetchTransaction(txSha) tx, err := s.server.txMemPool.FetchTransaction(txSha)
if err != nil { if err != nil {
txList, err := s.server.db.FetchTxBySha(txSha) txList, err := s.server.db.FetchTxBySha(txSha)
@ -2450,7 +2450,7 @@ func handleGetTxOut(s *rpcServer, cmd btcjson.Cmd, closeChan <-chan struct{}) (i
c := cmd.(*btcjson.GetTxOutCmd) c := cmd.(*btcjson.GetTxOutCmd)
// Convert the provided transaction hash hex to a ShaHash. // Convert the provided transaction hash hex to a ShaHash.
txSha, err := btcwire.NewShaHashFromStr(c.Txid) txSha, err := wire.NewShaHashFromStr(c.Txid)
if err != nil { if err != nil {
return nil, btcjson.Error{ return nil, btcjson.Error{
Code: btcjson.ErrInvalidParameter.Code, Code: btcjson.ErrInvalidParameter.Code,
@ -2461,7 +2461,7 @@ func handleGetTxOut(s *rpcServer, cmd btcjson.Cmd, closeChan <-chan struct{}) (i
// If requested and the tx is available in the mempool try to fetch it from // If requested and the tx is available in the mempool try to fetch it from
// there, otherwise attempt to fetch from the block database. // there, otherwise attempt to fetch from the block database.
var mtx *btcwire.MsgTx var mtx *wire.MsgTx
var bestBlockSha string var bestBlockSha string
var confirmations int64 var confirmations int64
var dbSpentInfo []bool var dbSpentInfo []bool
@ -2571,7 +2571,7 @@ func handleGetWorkRequest(s *rpcServer) (interface{}, error) {
// variations if the best block changed. // variations if the best block changed.
if state.prevHash != nil && !state.prevHash.IsEqual(latestHash) { if state.prevHash != nil && !state.prevHash.IsEqual(latestHash) {
state.extraNonce = 0 state.extraNonce = 0
state.blockInfo = make(map[btcwire.ShaHash]*workStateBlockInfo) state.blockInfo = make(map[wire.ShaHash]*workStateBlockInfo)
} }
// Reset the previous best hash the block template was generated // Reset the previous best hash the block template was generated
@ -2690,17 +2690,17 @@ func handleGetWorkRequest(s *rpcServer) (interface{}, error) {
// caller to make use of only the second chunk along with the midstate // caller to make use of only the second chunk along with the midstate
// for the first chunk. // for the first chunk.
data = data[:getworkDataLen] data = data[:getworkDataLen]
data[btcwire.MaxBlockHeaderPayload] = 0x80 data[wire.MaxBlockHeaderPayload] = 0x80
binary.BigEndian.PutUint64(data[len(data)-8:], binary.BigEndian.PutUint64(data[len(data)-8:],
btcwire.MaxBlockHeaderPayload*8) wire.MaxBlockHeaderPayload*8)
// Create the hash1 field which is a zero hash along with the internal // Create the hash1 field which is a zero hash along with the internal
// sha256 padding as described above. This field is really quite // sha256 padding as described above. This field is really quite
// useless, but it is required for compatibility with the reference // useless, but it is required for compatibility with the reference
// implementation. // implementation.
var hash1 [hash1Len]byte var hash1 [hash1Len]byte
hash1[btcwire.HashSize] = 0x80 hash1[wire.HashSize] = 0x80
binary.BigEndian.PutUint64(hash1[len(hash1)-8:], btcwire.HashSize*8) binary.BigEndian.PutUint64(hash1[len(hash1)-8:], wire.HashSize*8)
// The final result reverses the each of the fields to little endian. // The final result reverses the each of the fields to little endian.
// In particular, the data, hash1, and midstate fields are treated as // In particular, the data, hash1, and midstate fields are treated as
@ -2759,8 +2759,8 @@ func handleGetWorkSubmission(s *rpcServer, hexData string) (interface{}, error)
reverseUint32Array(data) reverseUint32Array(data)
// Deserialize the block header from the data. // Deserialize the block header from the data.
var submittedHeader btcwire.BlockHeader var submittedHeader wire.BlockHeader
bhBuf := bytes.NewReader(data[0:btcwire.MaxBlockHeaderPayload]) bhBuf := bytes.NewReader(data[0:wire.MaxBlockHeaderPayload])
err = submittedHeader.Deserialize(bhBuf) err = submittedHeader.Deserialize(bhBuf)
if err != nil { if err != nil {
return false, btcjson.Error{ return false, btcjson.Error{
@ -2937,12 +2937,12 @@ func handleHelp(s *rpcServer, cmd btcjson.Cmd, closeChan <-chan struct{}) (inter
// handlePing implements the ping command. // handlePing implements the ping command.
func handlePing(s *rpcServer, cmd btcjson.Cmd, closeChan <-chan struct{}) (interface{}, error) { func handlePing(s *rpcServer, cmd btcjson.Cmd, closeChan <-chan struct{}) (interface{}, error) {
// Ask server to ping \o_ // Ask server to ping \o_
nonce, err := btcwire.RandomUint64() nonce, err := wire.RandomUint64()
if err != nil { if err != nil {
return nil, fmt.Errorf("Not sending ping - can not generate "+ return nil, fmt.Errorf("Not sending ping - can not generate "+
"nonce: %v", err) "nonce: %v", err)
} }
s.server.BroadcastMessage(btcwire.NewMsgPing(nonce)) s.server.BroadcastMessage(wire.NewMsgPing(nonce))
return nil, nil return nil, nil
} }
@ -2963,7 +2963,7 @@ func handleSendRawTransaction(s *rpcServer, cmd btcjson.Cmd, closeChan <-chan st
"string (not %q)", hexStr), "string (not %q)", hexStr),
} }
} }
msgtx := btcwire.NewMsgTx() msgtx := wire.NewMsgTx()
err = msgtx.Deserialize(bytes.NewReader(serializedTx)) err = msgtx.Deserialize(bytes.NewReader(serializedTx))
if err != nil { if err != nil {
err := btcjson.Error{ err := btcjson.Error{
@ -2998,7 +2998,7 @@ func handleSendRawTransaction(s *rpcServer, cmd btcjson.Cmd, closeChan <-chan st
// We keep track of all the sendrawtransaction request txs so that we // We keep track of all the sendrawtransaction request txs so that we
// can rebroadcast them if they don't make their way into a block. // can rebroadcast them if they don't make their way into a block.
iv := btcwire.NewInvVect(btcwire.InvTypeTx, tx.Sha()) iv := wire.NewInvVect(wire.InvTypeTx, tx.Sha())
s.server.AddRebroadcastInventory(iv, tx) s.server.AddRebroadcastInventory(iv, tx)
return tx.Sha().String(), nil return tx.Sha().String(), nil
@ -3188,7 +3188,7 @@ func handleVerifyMessage(s *rpcServer, cmd btcjson.Cmd, closeChan <-chan struct{
// Validate the signature - this just shows that it was valid at all. // Validate the signature - this just shows that it was valid at all.
// we will compare it with the key next. // we will compare it with the key next.
pk, wasCompressed, err := btcec.RecoverCompact(btcec.S256(), sig, pk, wasCompressed, err := btcec.RecoverCompact(btcec.S256(), sig,
btcwire.DoubleSha256([]byte("Bitcoin Signed Message:\n"+c.Message))) wire.DoubleSha256([]byte("Bitcoin Signed Message:\n"+c.Message)))
if err != nil { if err != nil {
// Mirror Bitcoin Core behavior, which treats error in RecoverCompact as // Mirror Bitcoin Core behavior, which treats error in RecoverCompact as
// invalid signature. // invalid signature.

View file

@ -21,9 +21,9 @@ import (
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcd/txscript" "github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcjson" "github.com/btcsuite/btcjson"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
"github.com/btcsuite/btcws" "github.com/btcsuite/btcws"
"github.com/btcsuite/fastsha256" "github.com/btcsuite/fastsha256"
"github.com/btcsuite/websocket" "github.com/btcsuite/websocket"
@ -244,11 +244,11 @@ type notificationRegisterNewMempoolTxs wsClient
type notificationUnregisterNewMempoolTxs wsClient type notificationUnregisterNewMempoolTxs wsClient
type notificationRegisterSpent struct { type notificationRegisterSpent struct {
wsc *wsClient wsc *wsClient
op *btcwire.OutPoint op *wire.OutPoint
} }
type notificationUnregisterSpent struct { type notificationUnregisterSpent struct {
wsc *wsClient wsc *wsClient
op *btcwire.OutPoint op *wire.OutPoint
} }
type notificationRegisterAddr struct { type notificationRegisterAddr struct {
wsc *wsClient wsc *wsClient
@ -274,7 +274,7 @@ func (m *wsNotificationManager) notificationHandler() {
// since it is quite a bit more efficient than using the entire struct. // since it is quite a bit more efficient than using the entire struct.
blockNotifications := make(map[chan struct{}]*wsClient) blockNotifications := make(map[chan struct{}]*wsClient)
txNotifications := make(map[chan struct{}]*wsClient) txNotifications := make(map[chan struct{}]*wsClient)
watchedOutPoints := make(map[btcwire.OutPoint]map[chan struct{}]*wsClient) watchedOutPoints := make(map[wire.OutPoint]map[chan struct{}]*wsClient)
watchedAddrs := make(map[string]map[chan struct{}]*wsClient) watchedAddrs := make(map[string]map[chan struct{}]*wsClient)
out: out:
@ -515,7 +515,7 @@ func (m *wsNotificationManager) notifyForNewTx(clients map[chan struct{}]*wsClie
// confirmed spent (contained in a block connected to the main chain) for the // confirmed spent (contained in a block connected to the main chain) for the
// passed websocket client. The request is automatically removed once the // passed websocket client. The request is automatically removed once the
// notification has been sent. // notification has been sent.
func (m *wsNotificationManager) RegisterSpentRequest(wsc *wsClient, op *btcwire.OutPoint) { func (m *wsNotificationManager) RegisterSpentRequest(wsc *wsClient, op *wire.OutPoint) {
m.queueNotification <- &notificationRegisterSpent{ m.queueNotification <- &notificationRegisterSpent{
wsc: wsc, wsc: wsc,
op: op, op: op,
@ -525,8 +525,8 @@ func (m *wsNotificationManager) RegisterSpentRequest(wsc *wsClient, op *btcwire.
// addSpentRequest modifies a map of watched outpoints to sets of websocket // addSpentRequest modifies a map of watched outpoints to sets of websocket
// clients to add a new request watch the outpoint op and create and send // clients to add a new request watch the outpoint op and create and send
// a notification when spent to the websocket client wsc. // a notification when spent to the websocket client wsc.
func (*wsNotificationManager) addSpentRequest(ops map[btcwire.OutPoint]map[chan struct{}]*wsClient, func (*wsNotificationManager) addSpentRequest(ops map[wire.OutPoint]map[chan struct{}]*wsClient,
wsc *wsClient, op *btcwire.OutPoint) { wsc *wsClient, op *wire.OutPoint) {
// Track the request in the client as well so it can be quickly be // Track the request in the client as well so it can be quickly be
// removed on disconnect. // removed on disconnect.
@ -545,7 +545,7 @@ func (*wsNotificationManager) addSpentRequest(ops map[btcwire.OutPoint]map[chan
// UnregisterSpentRequest removes a request from the passed websocket client // UnregisterSpentRequest removes a request from the passed websocket client
// to be notified when the passed outpoint is confirmed spent (contained in a // to be notified when the passed outpoint is confirmed spent (contained in a
// block connected to the main chain). // block connected to the main chain).
func (m *wsNotificationManager) UnregisterSpentRequest(wsc *wsClient, op *btcwire.OutPoint) { func (m *wsNotificationManager) UnregisterSpentRequest(wsc *wsClient, op *wire.OutPoint) {
m.queueNotification <- &notificationUnregisterSpent{ m.queueNotification <- &notificationUnregisterSpent{
wsc: wsc, wsc: wsc,
op: op, op: op,
@ -556,8 +556,8 @@ func (m *wsNotificationManager) UnregisterSpentRequest(wsc *wsClient, op *btcwir
// websocket client wsc from the set of clients to be notified when a // websocket client wsc from the set of clients to be notified when a
// watched outpoint is spent. If wsc is the last client, the outpoint // watched outpoint is spent. If wsc is the last client, the outpoint
// key is removed from the map. // key is removed from the map.
func (*wsNotificationManager) removeSpentRequest(ops map[btcwire.OutPoint]map[chan struct{}]*wsClient, func (*wsNotificationManager) removeSpentRequest(ops map[wire.OutPoint]map[chan struct{}]*wsClient,
wsc *wsClient, op *btcwire.OutPoint) { wsc *wsClient, op *wire.OutPoint) {
// Remove the request tracking from the client. // Remove the request tracking from the client.
delete(wsc.spentRequests, *op) delete(wsc.spentRequests, *op)
@ -613,7 +613,7 @@ func newRedeemingTxNotification(txHex string, index int, block *btcutil.Block) (
// websocket clients of the transaction if an output spends to a watched // websocket clients of the transaction if an output spends to a watched
// address. A spent notification request is automatically registered for // address. A spent notification request is automatically registered for
// the client for each matching output. // the client for each matching output.
func (m *wsNotificationManager) notifyForTxOuts(ops map[btcwire.OutPoint]map[chan struct{}]*wsClient, func (m *wsNotificationManager) notifyForTxOuts(ops map[wire.OutPoint]map[chan struct{}]*wsClient,
addrs map[string]map[chan struct{}]*wsClient, tx *btcutil.Tx, block *btcutil.Block) { addrs map[string]map[chan struct{}]*wsClient, tx *btcutil.Tx, block *btcutil.Block) {
// Nothing to do if nobody is listening for address notifications. // Nothing to do if nobody is listening for address notifications.
@ -647,7 +647,7 @@ func (m *wsNotificationManager) notifyForTxOuts(ops map[btcwire.OutPoint]map[cha
continue continue
} }
op := btcwire.NewOutPoint(tx.Sha(), uint32(i)) op := wire.NewOutPoint(tx.Sha(), uint32(i))
for wscQuit, wsc := range cmap { for wscQuit, wsc := range cmap {
m.addSpentRequest(ops, wsc, op) m.addSpentRequest(ops, wsc, op)
@ -663,7 +663,7 @@ func (m *wsNotificationManager) notifyForTxOuts(ops map[btcwire.OutPoint]map[cha
// notifyForTx examines the inputs and outputs of the passed transaction, // notifyForTx examines the inputs and outputs of the passed transaction,
// notifying websocket clients of outputs spending to a watched address // notifying websocket clients of outputs spending to a watched address
// and inputs spending a watched outpoint. // and inputs spending a watched outpoint.
func (m *wsNotificationManager) notifyForTx(ops map[btcwire.OutPoint]map[chan struct{}]*wsClient, func (m *wsNotificationManager) notifyForTx(ops map[wire.OutPoint]map[chan struct{}]*wsClient,
addrs map[string]map[chan struct{}]*wsClient, tx *btcutil.Tx, block *btcutil.Block) { addrs map[string]map[chan struct{}]*wsClient, tx *btcutil.Tx, block *btcutil.Block) {
if len(ops) != 0 { if len(ops) != 0 {
@ -678,7 +678,7 @@ func (m *wsNotificationManager) notifyForTx(ops map[btcwire.OutPoint]map[chan st
// interested websocket clients a redeemingtx notification if any inputs // interested websocket clients a redeemingtx notification if any inputs
// spend a watched output. If block is non-nil, any matching spent // spend a watched output. If block is non-nil, any matching spent
// requests are removed. // requests are removed.
func (m *wsNotificationManager) notifyForTxIns(ops map[btcwire.OutPoint]map[chan struct{}]*wsClient, func (m *wsNotificationManager) notifyForTxIns(ops map[wire.OutPoint]map[chan struct{}]*wsClient,
tx *btcutil.Tx, block *btcutil.Block) { tx *btcutil.Tx, block *btcutil.Block) {
// Nothing to do if nobody is watching outpoints. // Nothing to do if nobody is watching outpoints.
@ -906,7 +906,7 @@ type wsClient struct {
// spentRequests is a set of unspent Outpoints a wallet has requested // spentRequests is a set of unspent Outpoints a wallet has requested
// notifications for when they are spent by a processed transaction. // notifications for when they are spent by a processed transaction.
// Owned by the notification manager. // Owned by the notification manager.
spentRequests map[btcwire.OutPoint]struct{} spentRequests map[wire.OutPoint]struct{}
// Networking infrastructure. // Networking infrastructure.
asyncStarted bool asyncStarted bool
@ -1375,7 +1375,7 @@ func newWebsocketClient(server *rpcServer, conn *websocket.Conn,
authenticated: authenticated, authenticated: authenticated,
server: server, server: server,
addrRequests: make(map[string]struct{}), addrRequests: make(map[string]struct{}),
spentRequests: make(map[btcwire.OutPoint]struct{}), spentRequests: make(map[wire.OutPoint]struct{}),
ntfnChan: make(chan []byte, 1), // nonblocking sync ntfnChan: make(chan []byte, 1), // nonblocking sync
asyncChan: make(chan btcjson.Cmd, 1), // nonblocking sync asyncChan: make(chan btcjson.Cmd, 1), // nonblocking sync
sendChan: make(chan wsResponse, websocketSendBufferSize), sendChan: make(chan wsResponse, websocketSendBufferSize),
@ -1398,9 +1398,9 @@ func handleNotifySpent(wsc *wsClient, icmd btcjson.Cmd) (interface{}, *btcjson.E
return nil, &btcjson.ErrInternal return nil, &btcjson.ErrInternal
} }
outpoints := make([]*btcwire.OutPoint, 0, len(cmd.OutPoints)) outpoints := make([]*wire.OutPoint, 0, len(cmd.OutPoints))
for i := range cmd.OutPoints { for i := range cmd.OutPoints {
blockHash, err := btcwire.NewShaHashFromStr(cmd.OutPoints[i].Hash) blockHash, err := wire.NewShaHashFromStr(cmd.OutPoints[i].Hash)
if err != nil { if err != nil {
return nil, &btcjson.Error{ return nil, &btcjson.Error{
Code: btcjson.ErrParse.Code, Code: btcjson.ErrParse.Code,
@ -1408,7 +1408,7 @@ func handleNotifySpent(wsc *wsClient, icmd btcjson.Cmd) (interface{}, *btcjson.E
} }
} }
index := cmd.OutPoints[i].Index index := cmd.OutPoints[i].Index
outpoints = append(outpoints, btcwire.NewOutPoint(blockHash, index)) outpoints = append(outpoints, wire.NewOutPoint(blockHash, index))
} }
for _, outpoint := range outpoints { for _, outpoint := range outpoints {
wsc.server.ntfnMgr.RegisterSpentRequest(wsc, outpoint) wsc.server.ntfnMgr.RegisterSpentRequest(wsc, outpoint)
@ -1459,7 +1459,7 @@ type rescanKeys struct {
scriptHashes map[[ripemd160.Size]byte]struct{} scriptHashes map[[ripemd160.Size]byte]struct{}
compressedPubkeys map[[33]byte]struct{} compressedPubkeys map[[33]byte]struct{}
uncompressedPubkeys map[[65]byte]struct{} uncompressedPubkeys map[[65]byte]struct{}
unspent map[btcwire.OutPoint]struct{} unspent map[wire.OutPoint]struct{}
} }
// ErrRescanReorg defines the error that is returned when an unrecoverable // ErrRescanReorg defines the error that is returned when an unrecoverable
@ -1569,7 +1569,7 @@ func rescanBlock(wsc *wsClient, lookups *rescanKeys, blk *btcutil.Block) {
} }
} }
outpoint := btcwire.OutPoint{ outpoint := wire.OutPoint{
Hash: *tx.Sha(), Hash: *tx.Sha(),
Index: uint32(txOutIdx), Index: uint32(txOutIdx),
} }
@ -1608,7 +1608,7 @@ func rescanBlock(wsc *wsClient, lookups *rescanKeys, blk *btcutil.Block) {
// range of blocks. If this condition does not hold true, the JSON-RPC error // range of blocks. If this condition does not hold true, the JSON-RPC error
// for an unrecoverable reorganize is returned. // for an unrecoverable reorganize is returned.
func recoverFromReorg(db database.Db, minBlock, maxBlock int64, func recoverFromReorg(db database.Db, minBlock, maxBlock int64,
lastBlock *btcutil.Block) ([]btcwire.ShaHash, *btcjson.Error) { lastBlock *btcutil.Block) ([]wire.ShaHash, *btcjson.Error) {
hashList, err := db.FetchHeightRange(minBlock, maxBlock) hashList, err := db.FetchHeightRange(minBlock, maxBlock)
if err != nil { if err != nil {
@ -1665,9 +1665,9 @@ func handleRescan(wsc *wsClient, icmd btcjson.Cmd) (interface{}, *btcjson.Error)
return nil, &btcjson.ErrInternal return nil, &btcjson.ErrInternal
} }
outpoints := make([]*btcwire.OutPoint, 0, len(cmd.OutPoints)) outpoints := make([]*wire.OutPoint, 0, len(cmd.OutPoints))
for i := range cmd.OutPoints { for i := range cmd.OutPoints {
blockHash, err := btcwire.NewShaHashFromStr(cmd.OutPoints[i].Hash) blockHash, err := wire.NewShaHashFromStr(cmd.OutPoints[i].Hash)
if err != nil { if err != nil {
return nil, &btcjson.Error{ return nil, &btcjson.Error{
Code: btcjson.ErrParse.Code, Code: btcjson.ErrParse.Code,
@ -1675,7 +1675,7 @@ func handleRescan(wsc *wsClient, icmd btcjson.Cmd) (interface{}, *btcjson.Error)
} }
} }
index := cmd.OutPoints[i].Index index := cmd.OutPoints[i].Index
outpoints = append(outpoints, btcwire.NewOutPoint(blockHash, index)) outpoints = append(outpoints, wire.NewOutPoint(blockHash, index))
} }
numAddrs := len(cmd.Addresses) numAddrs := len(cmd.Addresses)
@ -1692,7 +1692,7 @@ func handleRescan(wsc *wsClient, icmd btcjson.Cmd) (interface{}, *btcjson.Error)
scriptHashes: map[[ripemd160.Size]byte]struct{}{}, scriptHashes: map[[ripemd160.Size]byte]struct{}{},
compressedPubkeys: map[[33]byte]struct{}{}, compressedPubkeys: map[[33]byte]struct{}{},
uncompressedPubkeys: map[[65]byte]struct{}{}, uncompressedPubkeys: map[[65]byte]struct{}{},
unspent: map[btcwire.OutPoint]struct{}{}, unspent: map[wire.OutPoint]struct{}{},
} }
var compressedPubkey [33]byte var compressedPubkey [33]byte
var uncompressedPubkey [65]byte var uncompressedPubkey [65]byte
@ -1744,7 +1744,7 @@ func handleRescan(wsc *wsClient, icmd btcjson.Cmd) (interface{}, *btcjson.Error)
db := wsc.server.server.db db := wsc.server.server.db
minBlockSha, err := btcwire.NewShaHashFromStr(cmd.BeginBlock) minBlockSha, err := wire.NewShaHashFromStr(cmd.BeginBlock)
if err != nil { if err != nil {
return nil, &btcjson.ErrDecodeHexString return nil, &btcjson.ErrDecodeHexString
} }
@ -1755,7 +1755,7 @@ func handleRescan(wsc *wsClient, icmd btcjson.Cmd) (interface{}, *btcjson.Error)
maxBlock := database.AllShas maxBlock := database.AllShas
if cmd.EndBlock != "" { if cmd.EndBlock != "" {
maxBlockSha, err := btcwire.NewShaHashFromStr(cmd.EndBlock) maxBlockSha, err := wire.NewShaHashFromStr(cmd.EndBlock)
if err != nil { if err != nil {
return nil, &btcjson.ErrDecodeHexString return nil, &btcjson.ErrDecodeHexString
} }

View file

@ -22,10 +22,10 @@ import (
"github.com/btcsuite/btcd/addrmgr" "github.com/btcsuite/btcd/addrmgr"
"github.com/btcsuite/btcd/blockchain" "github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcjson" "github.com/btcsuite/btcjson"
"github.com/btcsuite/btcnet" "github.com/btcsuite/btcnet"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
) )
const ( const (
@ -38,7 +38,7 @@ const (
const ( const (
// supportedServices describes which services are supported by the // supportedServices describes which services are supported by the
// server. // server.
supportedServices = btcwire.SFNodeNetwork supportedServices = wire.SFNodeNetwork
// connectionRetryInterval is the amount of time to wait in between // connectionRetryInterval is the amount of time to wait in between
// retries when connecting to persistent peers. // retries when connecting to persistent peers.
@ -51,7 +51,7 @@ const (
// broadcastMsg provides the ability to house a bitcoin message to be broadcast // broadcastMsg provides the ability to house a bitcoin message to be broadcast
// to all connected peers except specified excluded peers. // to all connected peers except specified excluded peers.
type broadcastMsg struct { type broadcastMsg struct {
message btcwire.Message message wire.Message
excludePeers []*peer excludePeers []*peer
} }
@ -61,12 +61,12 @@ type broadcastInventoryAdd relayMsg
// broadcastInventoryDel is a type used to declare that the InvVect it contains // broadcastInventoryDel is a type used to declare that the InvVect it contains
// needs to be removed from the rebroadcast map // needs to be removed from the rebroadcast map
type broadcastInventoryDel *btcwire.InvVect type broadcastInventoryDel *wire.InvVect
// relayMsg packages an inventory vector along with the newly discovered // relayMsg packages an inventory vector along with the newly discovered
// inventory so the relay has access to that information. // inventory so the relay has access to that information.
type relayMsg struct { type relayMsg struct {
invVect *btcwire.InvVect invVect *wire.InvVect
data interface{} data interface{}
} }
@ -131,7 +131,7 @@ func randomUint16Number(max uint16) uint16 {
// AddRebroadcastInventory adds 'iv' to the list of inventories to be // AddRebroadcastInventory adds 'iv' to the list of inventories to be
// rebroadcasted at random intervals until they show up in a block. // rebroadcasted at random intervals until they show up in a block.
func (s *server) AddRebroadcastInventory(iv *btcwire.InvVect, data interface{}) { func (s *server) AddRebroadcastInventory(iv *wire.InvVect, data interface{}) {
// Ignore if shutting down. // Ignore if shutting down.
if atomic.LoadInt32(&s.shutdown) != 0 { if atomic.LoadInt32(&s.shutdown) != 0 {
return return
@ -142,7 +142,7 @@ func (s *server) AddRebroadcastInventory(iv *btcwire.InvVect, data interface{})
// RemoveRebroadcastInventory removes 'iv' from the list of items to be // RemoveRebroadcastInventory removes 'iv' from the list of items to be
// rebroadcasted if present. // rebroadcasted if present.
func (s *server) RemoveRebroadcastInventory(iv *btcwire.InvVect) { func (s *server) RemoveRebroadcastInventory(iv *wire.InvVect) {
// Ignore if shutting down. // Ignore if shutting down.
if atomic.LoadInt32(&s.shutdown) != 0 { if atomic.LoadInt32(&s.shutdown) != 0 {
return return
@ -301,7 +301,7 @@ func (s *server) handleRelayInvMsg(state *peerState, msg relayMsg) {
return return
} }
if msg.invVect.Type == btcwire.InvTypeTx { if msg.invVect.Type == wire.InvTypeTx {
// Don't relay the transaction to the peer when it has // Don't relay the transaction to the peer when it has
// transaction relaying disabled. // transaction relaying disabled.
if p.RelayTxDisabled() { if p.RelayTxDisabled() {
@ -523,11 +523,11 @@ func (s *server) seedFromDNS() {
if numPeers == 0 { if numPeers == 0 {
return return
} }
addresses := make([]*btcwire.NetAddress, len(seedpeers)) addresses := make([]*wire.NetAddress, len(seedpeers))
// if this errors then we have *real* problems // if this errors then we have *real* problems
intPort, _ := strconv.Atoi(activeNetParams.DefaultPort) intPort, _ := strconv.Atoi(activeNetParams.DefaultPort)
for i, peer := range seedpeers { for i, peer := range seedpeers {
addresses[i] = new(btcwire.NetAddress) addresses[i] = new(wire.NetAddress)
addresses[i].SetAddress(peer, uint16(intPort)) addresses[i].SetAddress(peer, uint16(intPort))
// bitcoind seeds with addresses from // bitcoind seeds with addresses from
// a time randomly selected between 3 // a time randomly selected between 3
@ -724,13 +724,13 @@ func (s *server) BanPeer(p *peer) {
// RelayInventory relays the passed inventory to all connected peers that are // RelayInventory relays the passed inventory to all connected peers that are
// not already known to have it. // not already known to have it.
func (s *server) RelayInventory(invVect *btcwire.InvVect, data interface{}) { func (s *server) RelayInventory(invVect *wire.InvVect, data interface{}) {
s.relayInv <- relayMsg{invVect: invVect, data: data} s.relayInv <- relayMsg{invVect: invVect, data: data}
} }
// BroadcastMessage sends msg to all peers currently connected to the server // BroadcastMessage sends msg to all peers currently connected to the server
// except those in the passed peers to exclude. // except those in the passed peers to exclude.
func (s *server) BroadcastMessage(msg btcwire.Message, exclPeers ...*peer) { func (s *server) BroadcastMessage(msg wire.Message, exclPeers ...*peer) {
// XXX: Need to determine if this is an alert that has already been // XXX: Need to determine if this is an alert that has already been
// broadcast and refrain from broadcasting again. // broadcast and refrain from broadcasting again.
bmsg := broadcastMsg{message: msg, excludePeers: exclPeers} bmsg := broadcastMsg{message: msg, excludePeers: exclPeers}
@ -818,7 +818,7 @@ func (s *server) NetTotals() (uint64, uint64) {
func (s *server) rebroadcastHandler() { func (s *server) rebroadcastHandler() {
// Wait 5 min before first tx rebroadcast. // Wait 5 min before first tx rebroadcast.
timer := time.NewTimer(5 * time.Minute) timer := time.NewTimer(5 * time.Minute)
pendingInvs := make(map[btcwire.InvVect]interface{}) pendingInvs := make(map[wire.InvVect]interface{})
out: out:
for { for {
@ -1061,8 +1061,8 @@ out:
srvrLog.Warnf("UPnP can't get external address: %v", err) srvrLog.Warnf("UPnP can't get external address: %v", err)
continue out continue out
} }
na := btcwire.NewNetAddressIPPort(externalip, uint16(listenPort), na := wire.NewNetAddressIPPort(externalip, uint16(listenPort),
btcwire.SFNodeNetwork) wire.SFNodeNetwork)
err = s.addrManager.AddLocalAddress(na, addrmgr.UpnpPrio) err = s.addrManager.AddLocalAddress(na, addrmgr.UpnpPrio)
if err != nil { if err != nil {
// XXX DeletePortMapping? // XXX DeletePortMapping?
@ -1091,7 +1091,7 @@ out:
// bitcoin network type specified by netParams. Use start to begin accepting // bitcoin network type specified by netParams. Use start to begin accepting
// connections from peers. // connections from peers.
func newServer(listenAddrs []string, db database.Db, netParams *btcnet.Params) (*server, error) { func newServer(listenAddrs []string, db database.Db, netParams *btcnet.Params) (*server, error) {
nonce, err := btcwire.RandomUint64() nonce, err := wire.RandomUint64()
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -1133,7 +1133,7 @@ func newServer(listenAddrs []string, db database.Db, netParams *btcnet.Params) (
eport = uint16(port) eport = uint16(port)
} }
na, err := amgr.HostToNetAddress(host, eport, na, err := amgr.HostToNetAddress(host, eport,
btcwire.SFNodeNetwork) wire.SFNodeNetwork)
if err != nil { if err != nil {
srvrLog.Warnf("Not adding %s as "+ srvrLog.Warnf("Not adding %s as "+
"externalip: %v", sip, err) "externalip: %v", sip, err)
@ -1168,8 +1168,8 @@ func newServer(listenAddrs []string, db database.Db, netParams *btcnet.Params) (
if err != nil { if err != nil {
continue continue
} }
na := btcwire.NewNetAddressIPPort(ip, na := wire.NewNetAddressIPPort(ip,
uint16(port), btcwire.SFNodeNetwork) uint16(port), wire.SFNodeNetwork)
if discover { if discover {
err = amgr.AddLocalAddress(na, addrmgr.InterfacePrio) err = amgr.AddLocalAddress(na, addrmgr.InterfacePrio)
if err != nil { if err != nil {

View file

@ -14,8 +14,8 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
) )
// TstMaxScriptSize makes the internal maxScriptSize constant available to the // TstMaxScriptSize makes the internal maxScriptSize constant available to the
@ -3798,23 +3798,23 @@ func ParseShortForm(script string) ([]byte, error) {
// createSpendTx generates a basic spending transaction given the passed // createSpendTx generates a basic spending transaction given the passed
// signature and public key scripts. // signature and public key scripts.
func createSpendingTx(sigScript, pkScript []byte) (*btcwire.MsgTx, error) { func createSpendingTx(sigScript, pkScript []byte) (*wire.MsgTx, error) {
coinbaseTx := btcwire.NewMsgTx() coinbaseTx := wire.NewMsgTx()
outPoint := btcwire.NewOutPoint(&btcwire.ShaHash{}, ^uint32(0)) outPoint := wire.NewOutPoint(&wire.ShaHash{}, ^uint32(0))
txIn := btcwire.NewTxIn(outPoint, []byte{OP_0, OP_0}) txIn := wire.NewTxIn(outPoint, []byte{OP_0, OP_0})
txOut := btcwire.NewTxOut(0, pkScript) txOut := wire.NewTxOut(0, pkScript)
coinbaseTx.AddTxIn(txIn) coinbaseTx.AddTxIn(txIn)
coinbaseTx.AddTxOut(txOut) coinbaseTx.AddTxOut(txOut)
spendingTx := btcwire.NewMsgTx() spendingTx := wire.NewMsgTx()
coinbaseTxSha, err := coinbaseTx.TxSha() coinbaseTxSha, err := coinbaseTx.TxSha()
if err != nil { if err != nil {
return nil, err return nil, err
} }
outPoint = btcwire.NewOutPoint(&coinbaseTxSha, 0) outPoint = wire.NewOutPoint(&coinbaseTxSha, 0)
txIn = btcwire.NewTxIn(outPoint, sigScript) txIn = wire.NewTxIn(outPoint, sigScript)
txOut = btcwire.NewTxOut(0, nil) txOut = wire.NewTxOut(0, nil)
spendingTx.AddTxIn(txIn) spendingTx.AddTxIn(txIn)
spendingTx.AddTxOut(txOut) spendingTx.AddTxOut(txOut)
@ -3998,7 +3998,7 @@ testloop:
continue continue
} }
prevOuts := make(map[btcwire.OutPoint][]byte) prevOuts := make(map[wire.OutPoint][]byte)
for j, iinput := range inputs { for j, iinput := range inputs {
input, ok := iinput.([]interface{}) input, ok := iinput.([]interface{})
if !ok { if !ok {
@ -4020,7 +4020,7 @@ testloop:
continue continue
} }
prevhash, err := btcwire.NewShaHashFromStr(previoustx) prevhash, err := wire.NewShaHashFromStr(previoustx)
if err != nil { if err != nil {
t.Errorf("bad test (%dth input sha not sha %v)"+ t.Errorf("bad test (%dth input sha not sha %v)"+
"%d: %v", j, err, i, test) "%d: %v", j, err, i, test)
@ -4050,7 +4050,7 @@ testloop:
continue continue
} }
prevOuts[*btcwire.NewOutPoint(prevhash, idx)] = script prevOuts[*wire.NewOutPoint(prevhash, idx)] = script
} }
for k, txin := range tx.MsgTx().TxIn { for k, txin := range tx.MsgTx().TxIn {
@ -4141,7 +4141,7 @@ testloop:
continue continue
} }
prevOuts := make(map[btcwire.OutPoint][]byte) prevOuts := make(map[wire.OutPoint][]byte)
for j, iinput := range inputs { for j, iinput := range inputs {
input, ok := iinput.([]interface{}) input, ok := iinput.([]interface{})
if !ok { if !ok {
@ -4163,7 +4163,7 @@ testloop:
continue testloop continue testloop
} }
prevhash, err := btcwire.NewShaHashFromStr(previoustx) prevhash, err := wire.NewShaHashFromStr(previoustx)
if err != nil { if err != nil {
t.Errorf("bad test (%dth input sha not sha %v)"+ t.Errorf("bad test (%dth input sha not sha %v)"+
"%d: %v", j, err, i, test) "%d: %v", j, err, i, test)
@ -4193,7 +4193,7 @@ testloop:
continue testloop continue testloop
} }
prevOuts[*btcwire.NewOutPoint(prevhash, idx)] = script prevOuts[*wire.NewOutPoint(prevhash, idx)] = script
} }
for k, txin := range tx.MsgTx().TxIn { for k, txin := range tx.MsgTx().TxIn {

View file

@ -15,8 +15,8 @@ import (
"golang.org/x/crypto/ripemd160" "golang.org/x/crypto/ripemd160"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcec" "github.com/btcsuite/btcec"
"github.com/btcsuite/btcwire"
"github.com/btcsuite/fastsha256" "github.com/btcsuite/fastsha256"
) )
@ -1746,7 +1746,7 @@ func opcodeHash256(op *parsedOpcode, s *Script) error {
return err return err
} }
s.dstack.PushByteArray(btcwire.DoubleSha256(buf)) s.dstack.PushByteArray(wire.DoubleSha256(buf))
return nil return nil
} }

View file

@ -9,7 +9,7 @@ import (
"testing" "testing"
"github.com/btcsuite/btcd/txscript" "github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcwire" "github.com/btcsuite/btcd/wire"
) )
// TestScripts tests script execution for a wide variety of opcodes. All tests // TestScripts tests script execution for a wide variety of opcodes. All tests
@ -480,19 +480,19 @@ func TestScripts(t *testing.T) {
} }
// Mock up fake tx used during script execution. // Mock up fake tx used during script execution.
mockTx := &btcwire.MsgTx{ mockTx := &wire.MsgTx{
Version: 1, Version: 1,
TxIn: []*btcwire.TxIn{ TxIn: []*wire.TxIn{
{ {
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash{}, Hash: wire.ShaHash{},
Index: 0xffffffff, Index: 0xffffffff,
}, },
SignatureScript: []byte{txscript.OP_NOP}, SignatureScript: []byte{txscript.OP_NOP},
Sequence: 0xffffffff, Sequence: 0xffffffff,
}, },
}, },
TxOut: []*btcwire.TxOut{ TxOut: []*wire.TxOut{
{ {
Value: 0x12a05f200, Value: 0x12a05f200,
PkScript: []byte{}, PkScript: []byte{},
@ -4263,19 +4263,19 @@ func stacksEqual(a, b [][]byte) bool {
func testOpcode(t *testing.T, test *detailedTest) { func testOpcode(t *testing.T, test *detailedTest) {
// mock up fake tx. // mock up fake tx.
tx := &btcwire.MsgTx{ tx := &wire.MsgTx{
Version: 1, Version: 1,
TxIn: []*btcwire.TxIn{ TxIn: []*wire.TxIn{
{ {
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash{}, Hash: wire.ShaHash{},
Index: 0xffffffff, Index: 0xffffffff,
}, },
SignatureScript: []byte{}, SignatureScript: []byte{},
Sequence: 0xffffffff, Sequence: 0xffffffff,
}, },
}, },
TxOut: []*btcwire.TxOut{ TxOut: []*wire.TxOut{
{ {
Value: 0x12a05f200, Value: 0x12a05f200,
PkScript: []byte{}, PkScript: []byte{},

View file

@ -11,10 +11,10 @@ import (
"fmt" "fmt"
"time" "time"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcec" "github.com/btcsuite/btcec"
"github.com/btcsuite/btcnet" "github.com/btcsuite/btcnet"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
) )
var ( var (
@ -201,7 +201,7 @@ type Script struct {
lastcodesep int lastcodesep int
dstack Stack // data stack dstack Stack // data stack
astack Stack // alt stack astack Stack // alt stack
tx btcwire.MsgTx tx wire.MsgTx
txidx int txidx int
condStack []int condStack []int
numOps int numOps int
@ -532,7 +532,7 @@ const (
// a signature script scriptSig and a pubkeyscript scriptPubKey. If bip16 is // a signature script scriptSig and a pubkeyscript scriptPubKey. If bip16 is
// true then it will be treated as if the bip16 threshhold has passed and thus // true then it will be treated as if the bip16 threshhold has passed and thus
// pay-to-script hash transactions will be fully validated. // pay-to-script hash transactions will be fully validated.
func NewScript(scriptSig []byte, scriptPubKey []byte, txidx int, tx *btcwire.MsgTx, flags ScriptFlags) (*Script, error) { func NewScript(scriptSig []byte, scriptPubKey []byte, txidx int, tx *wire.MsgTx, flags ScriptFlags) (*Script, error) {
var m Script var m Script
if flags&ScriptVerifySigPushOnly == ScriptVerifySigPushOnly && !IsPushOnlyScript(scriptSig) { if flags&ScriptVerifySigPushOnly == ScriptVerifySigPushOnly && !IsPushOnlyScript(scriptSig) {
return nil, ErrStackNonPushOnly return nil, ErrStackNonPushOnly
@ -825,7 +825,7 @@ func DisasmString(buf []byte) (string, error) {
// calcScriptHash will, given the a script and hashtype for the current // calcScriptHash will, given the a script and hashtype for the current
// scriptmachine, calculate the doubleSha256 hash of the transaction and // scriptmachine, calculate the doubleSha256 hash of the transaction and
// script to be used for signature signing and verification. // script to be used for signature signing and verification.
func calcScriptHash(script []parsedOpcode, hashType SigHashType, tx *btcwire.MsgTx, idx int) []byte { func calcScriptHash(script []parsedOpcode, hashType SigHashType, tx *wire.MsgTx, idx int) []byte {
// remove all instances of OP_CODESEPARATOR still left in the script // remove all instances of OP_CODESEPARATOR still left in the script
script = removeOpcode(script, OP_CODESEPARATOR) script = removeOpcode(script, OP_CODESEPARATOR)
@ -834,7 +834,7 @@ func calcScriptHash(script []parsedOpcode, hashType SigHashType, tx *btcwire.Msg
// for all inputs that are not currently being processed. // for all inputs that are not currently being processed.
txCopy := tx.Copy() txCopy := tx.Copy()
for i := range txCopy.TxIn { for i := range txCopy.TxIn {
var txIn btcwire.TxIn var txIn wire.TxIn
txIn = *txCopy.TxIn[i] txIn = *txCopy.TxIn[i]
txCopy.TxIn[i] = &txIn txCopy.TxIn[i] = &txIn
if i == idx { if i == idx {
@ -848,7 +848,7 @@ func calcScriptHash(script []parsedOpcode, hashType SigHashType, tx *btcwire.Msg
} }
// Default behaviour has all outputs set up. // Default behaviour has all outputs set up.
for i := range txCopy.TxOut { for i := range txCopy.TxOut {
var txOut btcwire.TxOut var txOut wire.TxOut
txOut = *txCopy.TxOut[i] txOut = *txCopy.TxOut[i]
txCopy.TxOut[i] = &txOut txCopy.TxOut[i] = &txOut
} }
@ -905,7 +905,7 @@ func calcScriptHash(script []parsedOpcode, hashType SigHashType, tx *btcwire.Msg
// Append LE 4 bytes hash type // Append LE 4 bytes hash type
binary.Write(&wbuf, binary.LittleEndian, uint32(hashType)) binary.Write(&wbuf, binary.LittleEndian, uint32(hashType))
return btcwire.DoubleSha256(wbuf.Bytes()) return wire.DoubleSha256(wbuf.Bytes())
} }
// getStack returns the contents of stack as a byte array bottom up // getStack returns the contents of stack as a byte array bottom up
@ -1117,7 +1117,7 @@ func MultiSigScript(pubkeys []*btcutil.AddressPubKey, nrequired int) ([]byte, er
// serialized in either a compressed or uncompressed format based on // serialized in either a compressed or uncompressed format based on
// compress. This format must match the same format used to generate // compress. This format must match the same format used to generate
// the payment address, or the script validation will fail. // the payment address, or the script validation will fail.
func SignatureScript(tx *btcwire.MsgTx, idx int, subscript []byte, hashType SigHashType, privKey *btcec.PrivateKey, compress bool) ([]byte, error) { func SignatureScript(tx *wire.MsgTx, idx int, subscript []byte, hashType SigHashType, privKey *btcec.PrivateKey, compress bool) ([]byte, error) {
sig, err := RawTxInSignature(tx, idx, subscript, hashType, privKey) sig, err := RawTxInSignature(tx, idx, subscript, hashType, privKey)
if err != nil { if err != nil {
return nil, err return nil, err
@ -1136,7 +1136,7 @@ func SignatureScript(tx *btcwire.MsgTx, idx int, subscript []byte, hashType SigH
// RawTxInSignature returns the serialized ECDSA signature for the input // RawTxInSignature returns the serialized ECDSA signature for the input
// idx of the given transaction, with hashType appended to it. // idx of the given transaction, with hashType appended to it.
func RawTxInSignature(tx *btcwire.MsgTx, idx int, subScript []byte, func RawTxInSignature(tx *wire.MsgTx, idx int, subScript []byte,
hashType SigHashType, key *btcec.PrivateKey) ([]byte, error) { hashType SigHashType, key *btcec.PrivateKey) ([]byte, error) {
parsedScript, err := parseScript(subScript) parsedScript, err := parseScript(subScript)
if err != nil { if err != nil {
@ -1151,7 +1151,7 @@ func RawTxInSignature(tx *btcwire.MsgTx, idx int, subScript []byte,
return append(signature.Serialize(), byte(hashType)), nil return append(signature.Serialize(), byte(hashType)), nil
} }
func p2pkSignatureScript(tx *btcwire.MsgTx, idx int, subScript []byte, hashType SigHashType, privKey *btcec.PrivateKey) ([]byte, error) { func p2pkSignatureScript(tx *wire.MsgTx, idx int, subScript []byte, hashType SigHashType, privKey *btcec.PrivateKey) ([]byte, error) {
sig, err := RawTxInSignature(tx, idx, subScript, hashType, privKey) sig, err := RawTxInSignature(tx, idx, subScript, hashType, privKey)
if err != nil { if err != nil {
return nil, err return nil, err
@ -1164,7 +1164,7 @@ func p2pkSignatureScript(tx *btcwire.MsgTx, idx int, subScript []byte, hashType
// possible. It returns the generated script and a boolean if the script fulfils // possible. It returns the generated script and a boolean if the script fulfils
// the contract (i.e. nrequired signatures are provided). Since it is arguably // the contract (i.e. nrequired signatures are provided). Since it is arguably
// legal to not be able to sign any of the outputs, no error is returned. // legal to not be able to sign any of the outputs, no error is returned.
func signMultiSig(tx *btcwire.MsgTx, idx int, subScript []byte, hashType SigHashType, func signMultiSig(tx *wire.MsgTx, idx int, subScript []byte, hashType SigHashType,
addresses []btcutil.Address, nRequired int, kdb KeyDB) ([]byte, bool) { addresses []btcutil.Address, nRequired int, kdb KeyDB) ([]byte, bool) {
// We start with a single OP_FALSE to work around the (now standard) // We start with a single OP_FALSE to work around the (now standard)
// but in the reference implementation that causes a spurious pop at // but in the reference implementation that causes a spurious pop at
@ -1193,7 +1193,7 @@ func signMultiSig(tx *btcwire.MsgTx, idx int, subScript []byte, hashType SigHash
return script, signed == nRequired return script, signed == nRequired
} }
func sign(net *btcnet.Params, tx *btcwire.MsgTx, idx int, subScript []byte, func sign(net *btcnet.Params, tx *wire.MsgTx, idx int, subScript []byte,
hashType SigHashType, kdb KeyDB, sdb ScriptDB) ([]byte, ScriptClass, hashType SigHashType, kdb KeyDB, sdb ScriptDB) ([]byte, ScriptClass,
[]btcutil.Address, int, error) { []btcutil.Address, int, error) {
@ -1257,7 +1257,7 @@ func sign(net *btcnet.Params, tx *btcwire.MsgTx, idx int, subScript []byte,
// The return value is the best effort merging of the two scripts. Calling this // The return value is the best effort merging of the two scripts. Calling this
// function with addresses, class and nrequired that do not match pkScript is // function with addresses, class and nrequired that do not match pkScript is
// an error and results in undefined behaviour. // an error and results in undefined behaviour.
func mergeScripts(net *btcnet.Params, tx *btcwire.MsgTx, idx int, func mergeScripts(net *btcnet.Params, tx *wire.MsgTx, idx int,
pkScript []byte, class ScriptClass, addresses []btcutil.Address, pkScript []byte, class ScriptClass, addresses []btcutil.Address,
nRequired int, sigScript, prevScript []byte) []byte { nRequired int, sigScript, prevScript []byte) []byte {
@ -1324,7 +1324,7 @@ func mergeScripts(net *btcnet.Params, tx *btcwire.MsgTx, idx int,
// pkScript. Since this function is internal only we assume that the arguments // pkScript. Since this function is internal only we assume that the arguments
// have come from other functions internally and thus are all consistent with // have come from other functions internally and thus are all consistent with
// each other, behaviour is undefined if this contract is broken. // each other, behaviour is undefined if this contract is broken.
func mergeMultiSig(tx *btcwire.MsgTx, idx int, addresses []btcutil.Address, func mergeMultiSig(tx *wire.MsgTx, idx int, addresses []btcutil.Address,
nRequired int, pkScript, sigScript, prevScript []byte) []byte { nRequired int, pkScript, sigScript, prevScript []byte) []byte {
// This is an internal only function and we already parsed this script // This is an internal only function and we already parsed this script
@ -1469,7 +1469,7 @@ func (sc ScriptClosure) GetScript(address btcutil.Address) ([]byte, error) {
// getScript. If previousScript is provided then the results in previousScript // getScript. If previousScript is provided then the results in previousScript
// will be merged in a type-dependant manner with the newly generated. // will be merged in a type-dependant manner with the newly generated.
// signature script. // signature script.
func SignTxOutput(net *btcnet.Params, tx *btcwire.MsgTx, idx int, func SignTxOutput(net *btcnet.Params, tx *wire.MsgTx, idx int,
pkScript []byte, hashType SigHashType, kdb KeyDB, sdb ScriptDB, pkScript []byte, hashType SigHashType, kdb KeyDB, sdb ScriptDB,
previousScript []byte) ([]byte, error) { previousScript []byte) ([]byte, error) {

View file

@ -11,10 +11,10 @@ import (
"testing" "testing"
"github.com/btcsuite/btcd/txscript" "github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcec" "github.com/btcsuite/btcec"
"github.com/btcsuite/btcnet" "github.com/btcsuite/btcnet"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire"
) )
// builderScript is a convenience function which is used in the tests. It // builderScript is a convenience function which is used in the tests. It
@ -132,7 +132,7 @@ func TestStandardPushes(t *testing.T) {
type txTest struct { type txTest struct {
name string name string
tx *btcwire.MsgTx tx *wire.MsgTx
pkScript []byte // output script of previous tx pkScript []byte // output script of previous tx
idx int // tx idx to be run. idx int // tx idx to be run.
bip16 bool // is bip16 active? bip16 bool // is bip16 active?
@ -150,12 +150,12 @@ var txTests = []txTest{
// blockchain that verifies signatures. // blockchain that verifies signatures.
{ {
name: "CheckSig", name: "CheckSig",
tx: &btcwire.MsgTx{ tx: &wire.MsgTx{
Version: 1, Version: 1,
TxIn: []*btcwire.TxIn{ TxIn: []*wire.TxIn{
{ {
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash([32]byte{ Hash: wire.ShaHash([32]byte{
0xc9, 0x97, 0xa5, 0xe5, 0xc9, 0x97, 0xa5, 0xe5,
0x6e, 0x10, 0x41, 0x02, 0x6e, 0x10, 0x41, 0x02,
0xfa, 0x20, 0x9c, 0x6a, 0xfa, 0x20, 0x9c, 0x6a,
@ -189,7 +189,7 @@ var txTests = []txTest{
Sequence: 4294967295, Sequence: 4294967295,
}, },
}, },
TxOut: []*btcwire.TxOut{ TxOut: []*wire.TxOut{
{ {
Value: 1000000000, Value: 1000000000,
PkScript: []byte{ PkScript: []byte{
@ -256,12 +256,12 @@ var txTests = []txTest{
// Previous test with the value of one output changed. // Previous test with the value of one output changed.
{ {
name: "CheckSig Failure", name: "CheckSig Failure",
tx: &btcwire.MsgTx{ tx: &wire.MsgTx{
Version: 1, Version: 1,
TxIn: []*btcwire.TxIn{ TxIn: []*wire.TxIn{
{ {
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash([32]byte{ Hash: wire.ShaHash([32]byte{
0xc9, 0x97, 0xa5, 0xe5, 0xc9, 0x97, 0xa5, 0xe5,
0x6e, 0x10, 0x41, 0x02, 0x6e, 0x10, 0x41, 0x02,
0xfa, 0x20, 0x9c, 0x6a, 0xfa, 0x20, 0x9c, 0x6a,
@ -295,7 +295,7 @@ var txTests = []txTest{
Sequence: 4294967295, Sequence: 4294967295,
}, },
}, },
TxOut: []*btcwire.TxOut{ TxOut: []*wire.TxOut{
{ {
Value: 1000000000, Value: 1000000000,
PkScript: []byte{ PkScript: []byte{
@ -362,12 +362,12 @@ var txTests = []txTest{
}, },
{ {
name: "CheckSig invalid signature", name: "CheckSig invalid signature",
tx: &btcwire.MsgTx{ tx: &wire.MsgTx{
Version: 1, Version: 1,
TxIn: []*btcwire.TxIn{ TxIn: []*wire.TxIn{
{ {
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash([32]byte{ Hash: wire.ShaHash([32]byte{
0xc9, 0x97, 0xa5, 0xe5, 0xc9, 0x97, 0xa5, 0xe5,
0x6e, 0x10, 0x41, 0x02, 0x6e, 0x10, 0x41, 0x02,
0xfa, 0x20, 0x9c, 0x6a, 0xfa, 0x20, 0x9c, 0x6a,
@ -403,7 +403,7 @@ var txTests = []txTest{
Sequence: 4294967295, Sequence: 4294967295,
}, },
}, },
TxOut: []*btcwire.TxOut{ TxOut: []*wire.TxOut{
{ {
Value: 1000000000, Value: 1000000000,
PkScript: []byte{ PkScript: []byte{
@ -470,12 +470,12 @@ var txTests = []txTest{
}, },
{ {
name: "CheckSig invalid pubkey", name: "CheckSig invalid pubkey",
tx: &btcwire.MsgTx{ tx: &wire.MsgTx{
Version: 1, Version: 1,
TxIn: []*btcwire.TxIn{ TxIn: []*wire.TxIn{
{ {
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash([32]byte{ Hash: wire.ShaHash([32]byte{
0xc9, 0x97, 0xa5, 0xe5, 0xc9, 0x97, 0xa5, 0xe5,
0x6e, 0x10, 0x41, 0x02, 0x6e, 0x10, 0x41, 0x02,
0xfa, 0x20, 0x9c, 0x6a, 0xfa, 0x20, 0x9c, 0x6a,
@ -509,7 +509,7 @@ var txTests = []txTest{
Sequence: 4294967295, Sequence: 4294967295,
}, },
}, },
TxOut: []*btcwire.TxOut{ TxOut: []*wire.TxOut{
{ {
Value: 1000000000, Value: 1000000000,
PkScript: []byte{ PkScript: []byte{
@ -579,12 +579,12 @@ var txTests = []txTest{
// uses checksig with SigHashNone. // uses checksig with SigHashNone.
{ {
name: "CheckSigHashNone", name: "CheckSigHashNone",
tx: &btcwire.MsgTx{ tx: &wire.MsgTx{
Version: 1, Version: 1,
TxIn: []*btcwire.TxIn{ TxIn: []*wire.TxIn{
{ {
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash([32]byte{ Hash: wire.ShaHash([32]byte{
0x5f, 0x38, 0x6c, 0x8a, 0x5f, 0x38, 0x6c, 0x8a,
0x38, 0x42, 0xc9, 0xa9, 0x38, 0x42, 0xc9, 0xa9,
0xdc, 0xfa, 0x9b, 0x78, 0xdc, 0xfa, 0x9b, 0x78,
@ -631,7 +631,7 @@ var txTests = []txTest{
Sequence: 4294967295, Sequence: 4294967295,
}, },
}, },
TxOut: []*btcwire.TxOut{ TxOut: []*wire.TxOut{
{ {
Value: 1000000, Value: 1000000,
PkScript: []byte{ PkScript: []byte{
@ -685,12 +685,12 @@ var txTests = []txTest{
}, },
{ {
name: "Non-canonical signature: R value negative", name: "Non-canonical signature: R value negative",
tx: &btcwire.MsgTx{ tx: &wire.MsgTx{
Version: 1, Version: 1,
TxIn: []*btcwire.TxIn{ TxIn: []*wire.TxIn{
{ {
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash([32]byte{ Hash: wire.ShaHash([32]byte{
0xfe, 0x15, 0x62, 0xc4, 0xfe, 0x15, 0x62, 0xc4,
0x8b, 0x3a, 0xa6, 0x37, 0x8b, 0x3a, 0xa6, 0x37,
0x3f, 0x42, 0xe9, 0x61, 0x3f, 0x42, 0xe9, 0x61,
@ -737,8 +737,8 @@ var txTests = []txTest{
Sequence: 4294967295, Sequence: 4294967295,
}, },
{ {
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash([32]byte{ Hash: wire.ShaHash([32]byte{
0x2a, 0xc7, 0xee, 0xf8, 0x2a, 0xc7, 0xee, 0xf8,
0xa9, 0x62, 0x2d, 0xda, 0xa9, 0x62, 0x2d, 0xda,
0xec, 0x18, 0x3b, 0xba, 0xec, 0x18, 0x3b, 0xba,
@ -785,7 +785,7 @@ var txTests = []txTest{
Sequence: 4294967295, Sequence: 4294967295,
}, },
}, },
TxOut: []*btcwire.TxOut{ TxOut: []*wire.TxOut{
{ {
Value: 630320000, Value: 630320000,
PkScript: []byte{ PkScript: []byte{
@ -859,12 +859,12 @@ var txTests = []txTest{
// first instance of an AnyoneCanPay signature in the blockchain // first instance of an AnyoneCanPay signature in the blockchain
{ {
name: "CheckSigHashAnyoneCanPay", name: "CheckSigHashAnyoneCanPay",
tx: &btcwire.MsgTx{ tx: &wire.MsgTx{
Version: 1, Version: 1,
TxIn: []*btcwire.TxIn{ TxIn: []*wire.TxIn{
{ {
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash([32]byte{ Hash: wire.ShaHash([32]byte{
0xf6, 0x04, 0x4c, 0x0a, 0xf6, 0x04, 0x4c, 0x0a,
0xd4, 0x85, 0xf6, 0x33, 0xd4, 0x85, 0xf6, 0x33,
0xb4, 0x1f, 0x97, 0xd0, 0xb4, 0x1f, 0x97, 0xd0,
@ -905,8 +905,8 @@ var txTests = []txTest{
Sequence: 4294967295, Sequence: 4294967295,
}, },
{ {
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash([32]byte{ Hash: wire.ShaHash([32]byte{
0x9c, 0x6a, 0xf0, 0xdf, 0x9c, 0x6a, 0xf0, 0xdf,
0x66, 0x69, 0xbc, 0xde, 0x66, 0x69, 0xbc, 0xde,
0xd1, 0x9e, 0x31, 0x7e, 0xd1, 0x9e, 0x31, 0x7e,
@ -947,7 +947,7 @@ var txTests = []txTest{
Sequence: 4294967295, Sequence: 4294967295,
}, },
}, },
TxOut: []*btcwire.TxOut{ TxOut: []*wire.TxOut{
{ {
Value: 300000, Value: 300000,
PkScript: []byte{ PkScript: []byte{
@ -989,12 +989,12 @@ var txTests = []txTest{
// Uses OP_CODESEPARATOR and OP_CHECKMULTISIG // Uses OP_CODESEPARATOR and OP_CHECKMULTISIG
{ {
name: "CheckMultiSig", name: "CheckMultiSig",
tx: &btcwire.MsgTx{ tx: &wire.MsgTx{
Version: 1, Version: 1,
TxIn: []*btcwire.TxIn{ TxIn: []*wire.TxIn{
{ {
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash([32]byte{ Hash: wire.ShaHash([32]byte{
0x37, 0xb1, 0x7d, 0x76, 0x37, 0xb1, 0x7d, 0x76,
0x38, 0x51, 0xcd, 0x1a, 0x38, 0x51, 0xcd, 0x1a,
0xb0, 0x4a, 0x42, 0x44, 0xb0, 0x4a, 0x42, 0x44,
@ -1031,8 +1031,8 @@ var txTests = []txTest{
Sequence: 4294967295, Sequence: 4294967295,
}, },
{ {
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash([32]byte{ Hash: wire.ShaHash([32]byte{
0x37, 0xb1, 0x7d, 0x76, 0x37, 0xb1, 0x7d, 0x76,
0x38, 0x51, 0xcd, 0x1a, 0x38, 0x51, 0xcd, 0x1a,
0xb0, 0x4a, 0x42, 0x44, 0xb0, 0x4a, 0x42, 0x44,
@ -1078,7 +1078,7 @@ var txTests = []txTest{
Sequence: 4294967295, Sequence: 4294967295,
}, },
}, },
TxOut: []*btcwire.TxOut{ TxOut: []*wire.TxOut{
{ {
Value: 4800000, Value: 4800000,
PkScript: []byte{ PkScript: []byte{
@ -1112,12 +1112,12 @@ var txTests = []txTest{
// same as previous but with one byte changed to make signature fail // same as previous but with one byte changed to make signature fail
{ {
name: "CheckMultiSig fail", name: "CheckMultiSig fail",
tx: &btcwire.MsgTx{ tx: &wire.MsgTx{
Version: 1, Version: 1,
TxIn: []*btcwire.TxIn{ TxIn: []*wire.TxIn{
{ {
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash([32]byte{ Hash: wire.ShaHash([32]byte{
0x37, 0xb1, 0x7d, 0x76, 0x37, 0xb1, 0x7d, 0x76,
0x38, 0x51, 0xcd, 0x1a, 0x38, 0x51, 0xcd, 0x1a,
0xb0, 0x4a, 0x42, 0x44, 0xb0, 0x4a, 0x42, 0x44,
@ -1154,8 +1154,8 @@ var txTests = []txTest{
Sequence: 4294967295, Sequence: 4294967295,
}, },
{ {
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash([32]byte{ Hash: wire.ShaHash([32]byte{
0x37, 0xb1, 0x7d, 0x76, 0x37, 0xb1, 0x7d, 0x76,
0x38, 0x51, 0xcd, 0x1a, 0x38, 0x51, 0xcd, 0x1a,
0xb0, 0x4a, 0x42, 0x44, 0xb0, 0x4a, 0x42, 0x44,
@ -1201,7 +1201,7 @@ var txTests = []txTest{
Sequence: 4294967295, Sequence: 4294967295,
}, },
}, },
TxOut: []*btcwire.TxOut{ TxOut: []*wire.TxOut{
{ {
Value: 5800000, Value: 5800000,
PkScript: []byte{ PkScript: []byte{
@ -1238,12 +1238,12 @@ var txTests = []txTest{
// multisig with zero required signatures // multisig with zero required signatures
{ {
name: "CheckMultiSig zero required signatures", name: "CheckMultiSig zero required signatures",
tx: &btcwire.MsgTx{ tx: &wire.MsgTx{
Version: 1, Version: 1,
TxIn: []*btcwire.TxIn{ TxIn: []*wire.TxIn{
{ {
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash([32]byte{ Hash: wire.ShaHash([32]byte{
0x37, 0xb1, 0x7d, 0x76, 0x37, 0xb1, 0x7d, 0x76,
0x38, 0x51, 0xcd, 0x1a, 0x38, 0x51, 0xcd, 0x1a,
0xb0, 0x4a, 0x42, 0x44, 0xb0, 0x4a, 0x42, 0x44,
@ -1273,7 +1273,7 @@ var txTests = []txTest{
Sequence: 4294967295, Sequence: 4294967295,
}, },
}, },
TxOut: []*btcwire.TxOut{}, TxOut: []*wire.TxOut{},
LockTime: 0, LockTime: 0,
}, },
pkScript: []byte{ pkScript: []byte{
@ -1298,12 +1298,12 @@ var txTests = []txTest{
// First P2SH transaction in the blockchain // First P2SH transaction in the blockchain
{ {
name: "P2SH", name: "P2SH",
tx: &btcwire.MsgTx{ tx: &wire.MsgTx{
Version: 1, Version: 1,
TxIn: []*btcwire.TxIn{ TxIn: []*wire.TxIn{
{ {
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash([32]byte{ Hash: wire.ShaHash([32]byte{
0x6d, 0x58, 0xf8, 0xa3, 0x6d, 0x58, 0xf8, 0xa3,
0xaa, 0x43, 0x0b, 0x84, 0xaa, 0x43, 0x0b, 0x84,
0x78, 0x52, 0x3a, 0x65, 0x78, 0x52, 0x3a, 0x65,
@ -1323,7 +1323,7 @@ var txTests = []txTest{
Sequence: 4294967295, Sequence: 4294967295,
}, },
}, },
TxOut: []*btcwire.TxOut{ TxOut: []*wire.TxOut{
{ {
Value: 1000000, Value: 1000000,
PkScript: []byte{ PkScript: []byte{
@ -1364,12 +1364,12 @@ var txTests = []txTest{
{ {
// sigscript changed so that pkscript hash will not match. // sigscript changed so that pkscript hash will not match.
name: "P2SH - bad hash", name: "P2SH - bad hash",
tx: &btcwire.MsgTx{ tx: &wire.MsgTx{
Version: 1, Version: 1,
TxIn: []*btcwire.TxIn{ TxIn: []*wire.TxIn{
{ {
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash([32]byte{ Hash: wire.ShaHash([32]byte{
0x6d, 0x58, 0xf8, 0xa3, 0x6d, 0x58, 0xf8, 0xa3,
0xaa, 0x43, 0x0b, 0x84, 0xaa, 0x43, 0x0b, 0x84,
0x78, 0x52, 0x3a, 0x65, 0x78, 0x52, 0x3a, 0x65,
@ -1389,7 +1389,7 @@ var txTests = []txTest{
Sequence: 4294967295, Sequence: 4294967295,
}, },
}, },
TxOut: []*btcwire.TxOut{ TxOut: []*wire.TxOut{
{ {
Value: 1000000, Value: 1000000,
PkScript: []byte{ PkScript: []byte{
@ -1429,12 +1429,12 @@ var txTests = []txTest{
{ {
// sigscript changed so that pkscript hash will not match. // sigscript changed so that pkscript hash will not match.
name: "P2SH - doesn't parse", name: "P2SH - doesn't parse",
tx: &btcwire.MsgTx{ tx: &wire.MsgTx{
Version: 1, Version: 1,
TxIn: []*btcwire.TxIn{ TxIn: []*wire.TxIn{
{ {
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash([32]byte{ Hash: wire.ShaHash([32]byte{
0x6d, 0x58, 0xf8, 0xa3, 0x6d, 0x58, 0xf8, 0xa3,
0xaa, 0x43, 0x0b, 0x84, 0xaa, 0x43, 0x0b, 0x84,
0x78, 0x52, 0x3a, 0x65, 0x78, 0x52, 0x3a, 0x65,
@ -1454,7 +1454,7 @@ var txTests = []txTest{
Sequence: 4294967295, Sequence: 4294967295,
}, },
}, },
TxOut: []*btcwire.TxOut{ TxOut: []*wire.TxOut{
{ {
Value: 1000000, Value: 1000000,
PkScript: []byte{ PkScript: []byte{
@ -1488,12 +1488,12 @@ var txTests = []txTest{
{ {
// sigscript changed so to be non pushonly. // sigscript changed so to be non pushonly.
name: "P2SH - non pushonly", name: "P2SH - non pushonly",
tx: &btcwire.MsgTx{ tx: &wire.MsgTx{
Version: 1, Version: 1,
TxIn: []*btcwire.TxIn{ TxIn: []*wire.TxIn{
{ {
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash([32]byte{ Hash: wire.ShaHash([32]byte{
0x6d, 0x58, 0xf8, 0xa3, 0x6d, 0x58, 0xf8, 0xa3,
0xaa, 0x43, 0x0b, 0x84, 0xaa, 0x43, 0x0b, 0x84,
0x78, 0x52, 0x3a, 0x65, 0x78, 0x52, 0x3a, 0x65,
@ -1517,7 +1517,7 @@ var txTests = []txTest{
Sequence: 4294967295, Sequence: 4294967295,
}, },
}, },
TxOut: []*btcwire.TxOut{ TxOut: []*wire.TxOut{
{ {
Value: 1000000, Value: 1000000,
PkScript: []byte{ PkScript: []byte{
@ -1552,12 +1552,12 @@ var txTests = []txTest{
{ {
// sigscript changed so to be non pushonly. // sigscript changed so to be non pushonly.
name: "empty pkScript", name: "empty pkScript",
tx: &btcwire.MsgTx{ tx: &wire.MsgTx{
Version: 1, Version: 1,
TxIn: []*btcwire.TxIn{ TxIn: []*wire.TxIn{
{ {
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash([32]byte{ Hash: wire.ShaHash([32]byte{
0x6d, 0x58, 0xf8, 0xa3, 0x6d, 0x58, 0xf8, 0xa3,
0xaa, 0x43, 0x0b, 0x84, 0xaa, 0x43, 0x0b, 0x84,
0x78, 0x52, 0x3a, 0x65, 0x78, 0x52, 0x3a, 0x65,
@ -1577,7 +1577,7 @@ var txTests = []txTest{
Sequence: 4294967295, Sequence: 4294967295,
}, },
}, },
TxOut: []*btcwire.TxOut{ TxOut: []*wire.TxOut{
{ {
Value: 1000000, Value: 1000000,
PkScript: []byte{ PkScript: []byte{
@ -2414,12 +2414,12 @@ func TestBadPC(t *testing.T) {
}, },
} }
// tx with almost empty scripts. // tx with almost empty scripts.
tx := &btcwire.MsgTx{ tx := &wire.MsgTx{
Version: 1, Version: 1,
TxIn: []*btcwire.TxIn{ TxIn: []*wire.TxIn{
{ {
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash([32]byte{ Hash: wire.ShaHash([32]byte{
0xc9, 0x97, 0xa5, 0xe5, 0xc9, 0x97, 0xa5, 0xe5,
0x6e, 0x10, 0x41, 0x02, 0x6e, 0x10, 0x41, 0x02,
0xfa, 0x20, 0x9c, 0x6a, 0xfa, 0x20, 0x9c, 0x6a,
@ -2435,7 +2435,7 @@ func TestBadPC(t *testing.T) {
Sequence: 4294967295, Sequence: 4294967295,
}, },
}, },
TxOut: []*btcwire.TxOut{ TxOut: []*wire.TxOut{
{ {
Value: 1000000000, Value: 1000000000,
PkScript: []byte{}, PkScript: []byte{},
@ -2475,12 +2475,12 @@ func TestCheckErrorCondition(t *testing.T) {
t.Parallel() t.Parallel()
// tx with almost empty scripts. // tx with almost empty scripts.
tx := &btcwire.MsgTx{ tx := &wire.MsgTx{
Version: 1, Version: 1,
TxIn: []*btcwire.TxIn{ TxIn: []*wire.TxIn{
{ {
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash([32]byte{ Hash: wire.ShaHash([32]byte{
0xc9, 0x97, 0xa5, 0xe5, 0xc9, 0x97, 0xa5, 0xe5,
0x6e, 0x10, 0x41, 0x02, 0x6e, 0x10, 0x41, 0x02,
0xfa, 0x20, 0x9c, 0x6a, 0xfa, 0x20, 0x9c, 0x6a,
@ -2496,7 +2496,7 @@ func TestCheckErrorCondition(t *testing.T) {
Sequence: 4294967295, Sequence: 4294967295,
}, },
}, },
TxOut: []*btcwire.TxOut{ TxOut: []*wire.TxOut{
{ {
Value: 1000000000, Value: 1000000000,
PkScript: []byte{}, PkScript: []byte{},
@ -2567,13 +2567,13 @@ type TstSigScript struct {
} }
type TstInput struct { type TstInput struct {
txout *btcwire.TxOut txout *wire.TxOut
sigscriptGenerates bool sigscriptGenerates bool
inputValidates bool inputValidates bool
indexOutOfRange bool indexOutOfRange bool
} }
var coinbaseOutPoint = &btcwire.OutPoint{ var coinbaseOutPoint = &wire.OutPoint{
Index: (1 << 32) - 1, Index: (1 << 32) - 1,
} }
@ -2614,7 +2614,7 @@ var SigScriptTests = []TstSigScript{
name: "one input uncompressed", name: "one input uncompressed",
inputs: []TstInput{ inputs: []TstInput{
{ {
txout: btcwire.NewTxOut(coinbaseVal, uncompressedPkScript), txout: wire.NewTxOut(coinbaseVal, uncompressedPkScript),
sigscriptGenerates: true, sigscriptGenerates: true,
inputValidates: true, inputValidates: true,
indexOutOfRange: false, indexOutOfRange: false,
@ -2628,13 +2628,13 @@ var SigScriptTests = []TstSigScript{
name: "two inputs uncompressed", name: "two inputs uncompressed",
inputs: []TstInput{ inputs: []TstInput{
{ {
txout: btcwire.NewTxOut(coinbaseVal, uncompressedPkScript), txout: wire.NewTxOut(coinbaseVal, uncompressedPkScript),
sigscriptGenerates: true, sigscriptGenerates: true,
inputValidates: true, inputValidates: true,
indexOutOfRange: false, indexOutOfRange: false,
}, },
{ {
txout: btcwire.NewTxOut(coinbaseVal+fee, uncompressedPkScript), txout: wire.NewTxOut(coinbaseVal+fee, uncompressedPkScript),
sigscriptGenerates: true, sigscriptGenerates: true,
inputValidates: true, inputValidates: true,
indexOutOfRange: false, indexOutOfRange: false,
@ -2648,7 +2648,7 @@ var SigScriptTests = []TstSigScript{
name: "one input compressed", name: "one input compressed",
inputs: []TstInput{ inputs: []TstInput{
{ {
txout: btcwire.NewTxOut(coinbaseVal, compressedPkScript), txout: wire.NewTxOut(coinbaseVal, compressedPkScript),
sigscriptGenerates: true, sigscriptGenerates: true,
inputValidates: true, inputValidates: true,
indexOutOfRange: false, indexOutOfRange: false,
@ -2662,13 +2662,13 @@ var SigScriptTests = []TstSigScript{
name: "two inputs compressed", name: "two inputs compressed",
inputs: []TstInput{ inputs: []TstInput{
{ {
txout: btcwire.NewTxOut(coinbaseVal, compressedPkScript), txout: wire.NewTxOut(coinbaseVal, compressedPkScript),
sigscriptGenerates: true, sigscriptGenerates: true,
inputValidates: true, inputValidates: true,
indexOutOfRange: false, indexOutOfRange: false,
}, },
{ {
txout: btcwire.NewTxOut(coinbaseVal+fee, compressedPkScript), txout: wire.NewTxOut(coinbaseVal+fee, compressedPkScript),
sigscriptGenerates: true, sigscriptGenerates: true,
inputValidates: true, inputValidates: true,
indexOutOfRange: false, indexOutOfRange: false,
@ -2682,7 +2682,7 @@ var SigScriptTests = []TstSigScript{
name: "hashType SigHashNone", name: "hashType SigHashNone",
inputs: []TstInput{ inputs: []TstInput{
{ {
txout: btcwire.NewTxOut(coinbaseVal, uncompressedPkScript), txout: wire.NewTxOut(coinbaseVal, uncompressedPkScript),
sigscriptGenerates: true, sigscriptGenerates: true,
inputValidates: true, inputValidates: true,
indexOutOfRange: false, indexOutOfRange: false,
@ -2696,7 +2696,7 @@ var SigScriptTests = []TstSigScript{
name: "hashType SigHashSingle", name: "hashType SigHashSingle",
inputs: []TstInput{ inputs: []TstInput{
{ {
txout: btcwire.NewTxOut(coinbaseVal, uncompressedPkScript), txout: wire.NewTxOut(coinbaseVal, uncompressedPkScript),
sigscriptGenerates: true, sigscriptGenerates: true,
inputValidates: true, inputValidates: true,
indexOutOfRange: false, indexOutOfRange: false,
@ -2710,7 +2710,7 @@ var SigScriptTests = []TstSigScript{
name: "hashType SigHashAnyoneCanPay", name: "hashType SigHashAnyoneCanPay",
inputs: []TstInput{ inputs: []TstInput{
{ {
txout: btcwire.NewTxOut(coinbaseVal, uncompressedPkScript), txout: wire.NewTxOut(coinbaseVal, uncompressedPkScript),
sigscriptGenerates: true, sigscriptGenerates: true,
inputValidates: true, inputValidates: true,
indexOutOfRange: false, indexOutOfRange: false,
@ -2724,7 +2724,7 @@ var SigScriptTests = []TstSigScript{
name: "hashType non-standard", name: "hashType non-standard",
inputs: []TstInput{ inputs: []TstInput{
{ {
txout: btcwire.NewTxOut(coinbaseVal, uncompressedPkScript), txout: wire.NewTxOut(coinbaseVal, uncompressedPkScript),
sigscriptGenerates: true, sigscriptGenerates: true,
inputValidates: true, inputValidates: true,
indexOutOfRange: false, indexOutOfRange: false,
@ -2738,7 +2738,7 @@ var SigScriptTests = []TstSigScript{
name: "invalid compression", name: "invalid compression",
inputs: []TstInput{ inputs: []TstInput{
{ {
txout: btcwire.NewTxOut(coinbaseVal, uncompressedPkScript), txout: wire.NewTxOut(coinbaseVal, uncompressedPkScript),
sigscriptGenerates: true, sigscriptGenerates: true,
inputValidates: false, inputValidates: false,
indexOutOfRange: false, indexOutOfRange: false,
@ -2752,7 +2752,7 @@ var SigScriptTests = []TstSigScript{
name: "short PkScript", name: "short PkScript",
inputs: []TstInput{ inputs: []TstInput{
{ {
txout: btcwire.NewTxOut(coinbaseVal, shortPkScript), txout: wire.NewTxOut(coinbaseVal, shortPkScript),
sigscriptGenerates: false, sigscriptGenerates: false,
indexOutOfRange: false, indexOutOfRange: false,
}, },
@ -2765,13 +2765,13 @@ var SigScriptTests = []TstSigScript{
name: "valid script at wrong index", name: "valid script at wrong index",
inputs: []TstInput{ inputs: []TstInput{
{ {
txout: btcwire.NewTxOut(coinbaseVal, uncompressedPkScript), txout: wire.NewTxOut(coinbaseVal, uncompressedPkScript),
sigscriptGenerates: true, sigscriptGenerates: true,
inputValidates: true, inputValidates: true,
indexOutOfRange: false, indexOutOfRange: false,
}, },
{ {
txout: btcwire.NewTxOut(coinbaseVal+fee, uncompressedPkScript), txout: wire.NewTxOut(coinbaseVal+fee, uncompressedPkScript),
sigscriptGenerates: true, sigscriptGenerates: true,
inputValidates: true, inputValidates: true,
indexOutOfRange: false, indexOutOfRange: false,
@ -2785,13 +2785,13 @@ var SigScriptTests = []TstSigScript{
name: "index out of range", name: "index out of range",
inputs: []TstInput{ inputs: []TstInput{
{ {
txout: btcwire.NewTxOut(coinbaseVal, uncompressedPkScript), txout: wire.NewTxOut(coinbaseVal, uncompressedPkScript),
sigscriptGenerates: true, sigscriptGenerates: true,
inputValidates: true, inputValidates: true,
indexOutOfRange: false, indexOutOfRange: false,
}, },
{ {
txout: btcwire.NewTxOut(coinbaseVal+fee, uncompressedPkScript), txout: wire.NewTxOut(coinbaseVal+fee, uncompressedPkScript),
sigscriptGenerates: true, sigscriptGenerates: true,
inputValidates: true, inputValidates: true,
indexOutOfRange: false, indexOutOfRange: false,
@ -2815,13 +2815,13 @@ func TestSignatureScript(t *testing.T) {
nexttest: nexttest:
for i := range SigScriptTests { for i := range SigScriptTests {
tx := btcwire.NewMsgTx() tx := wire.NewMsgTx()
output := btcwire.NewTxOut(500, []byte{txscript.OP_RETURN}) output := wire.NewTxOut(500, []byte{txscript.OP_RETURN})
tx.AddTxOut(output) tx.AddTxOut(output)
for _ = range SigScriptTests[i].inputs { for _ = range SigScriptTests[i].inputs {
txin := btcwire.NewTxIn(coinbaseOutPoint, nil) txin := wire.NewTxIn(coinbaseOutPoint, nil)
tx.AddTxIn(txin) tx.AddTxIn(txin)
} }
@ -3279,7 +3279,7 @@ func TestMultiSigScript(t *testing.T) {
} }
} }
func signAndCheck(msg string, tx *btcwire.MsgTx, idx int, pkScript []byte, func signAndCheck(msg string, tx *wire.MsgTx, idx int, pkScript []byte,
hashType txscript.SigHashType, kdb txscript.KeyDB, sdb txscript.ScriptDB, hashType txscript.SigHashType, kdb txscript.KeyDB, sdb txscript.ScriptDB,
previousScript []byte) error { previousScript []byte) error {
@ -3293,7 +3293,7 @@ func signAndCheck(msg string, tx *btcwire.MsgTx, idx int, pkScript []byte,
return checkScripts(msg, tx, idx, sigScript, pkScript) return checkScripts(msg, tx, idx, sigScript, pkScript)
} }
func checkScripts(msg string, tx *btcwire.MsgTx, idx int, func checkScripts(msg string, tx *wire.MsgTx, idx int,
sigScript, pkScript []byte) error { sigScript, pkScript []byte) error {
engine, err := txscript.NewScript(sigScript, pkScript, idx, tx, engine, err := txscript.NewScript(sigScript, pkScript, idx, tx,
txscript.ScriptBip16| txscript.ScriptBip16|
@ -3366,39 +3366,39 @@ func TestSignTxOutput(t *testing.T) {
txscript.SigHashNone | txscript.SigHashAnyOneCanPay, txscript.SigHashNone | txscript.SigHashAnyOneCanPay,
txscript.SigHashSingle | txscript.SigHashAnyOneCanPay, txscript.SigHashSingle | txscript.SigHashAnyOneCanPay,
} }
tx := &btcwire.MsgTx{ tx := &wire.MsgTx{
Version: 1, Version: 1,
TxIn: []*btcwire.TxIn{ TxIn: []*wire.TxIn{
&btcwire.TxIn{ &wire.TxIn{
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash{}, Hash: wire.ShaHash{},
Index: 0, Index: 0,
}, },
Sequence: 4294967295, Sequence: 4294967295,
}, },
&btcwire.TxIn{ &wire.TxIn{
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash{}, Hash: wire.ShaHash{},
Index: 1, Index: 1,
}, },
Sequence: 4294967295, Sequence: 4294967295,
}, },
&btcwire.TxIn{ &wire.TxIn{
PreviousOutPoint: btcwire.OutPoint{ PreviousOutPoint: wire.OutPoint{
Hash: btcwire.ShaHash{}, Hash: wire.ShaHash{},
Index: 2, Index: 2,
}, },
Sequence: 4294967295, Sequence: 4294967295,
}, },
}, },
TxOut: []*btcwire.TxOut{ TxOut: []*wire.TxOut{
&btcwire.TxOut{ &wire.TxOut{
Value: 1, Value: 1,
}, },
&btcwire.TxOut{ &wire.TxOut{
Value: 2, Value: 2,
}, },
&btcwire.TxOut{ &wire.TxOut{
Value: 3, Value: 3,
}, },
}, },