From 8e170cf327bf9f134eceedb2a81bbbacc5bfbe9a Mon Sep 17 00:00:00 2001 From: Ori Newman Date: Sun, 9 Aug 2020 12:39:15 +0300 Subject: [PATCH] [NOD-1225] Rename wire to domainmessage and get rid of InvType (#853) * [NOD-1225] Rename wire to domainmessage * [NOD-1225] Get rid of references to package wire in the code, and get rid of InvType --- addressmanager/addressmanager.go | 64 +++---- addressmanager/addressmanager_test.go | 86 ++++----- addressmanager/internal_test.go | 4 +- addressmanager/knownaddress.go | 10 +- addressmanager/knownaddress_test.go | 20 +- addressmanager/network.go | 38 ++-- addressmanager/network_test.go | 8 +- app/app.go | 6 +- blockdag/blocknode.go | 8 +- blockdag/coinbase.go | 12 +- blockdag/common_test.go | 10 +- blockdag/dag.go | 44 ++--- blockdag/dag_test.go | 104 +++++------ blockdag/dagio.go | 22 +-- blockdag/external_dag_test.go | 108 +++++------ blockdag/indexers/acceptanceindex.go | 4 +- blockdag/indexers/acceptanceindex_test.go | 14 +- blockdag/mining.go | 8 +- blockdag/reachabilitystore.go | 30 +-- blockdag/scriptval.go | 4 +- blockdag/subnetworks.go | 12 +- blockdag/test_utils.go | 26 +-- blockdag/utxo_ecmh.go | 6 +- blockdag/utxodiffstore_test.go | 6 +- blockdag/utxoio.go | 24 +-- blockdag/utxoset.go | 46 ++--- blockdag/utxoset_test.go | 90 ++++----- blockdag/validate.go | 38 ++-- blockdag/validate_test.go | 114 ++++++------ cmd/addblock/import.go | 6 +- cmd/kaspaminer/client.go | 4 +- cmd/txsigner/txsigner.go | 10 +- dagconfig/genesis.go | 52 +++--- dagconfig/genesis_test.go | 10 +- dagconfig/params.go | 18 +- dnsseed/seed.go | 12 +- {wire => domainmessage}/README.md | 2 +- {wire => domainmessage}/bench_test.go | 2 +- {wire => domainmessage}/blockheader.go | 14 +- {wire => domainmessage}/blockheader_test.go | 18 +- {wire => domainmessage}/common.go | 20 +- {wire => domainmessage}/common_test.go | 111 ++++++----- {wire => domainmessage}/doc.go | 38 ++-- {wire => domainmessage}/error.go | 2 +- {wire => domainmessage}/fakemessage_test.go | 6 +- {wire => domainmessage}/fixedIO_test.go | 2 +- {wire => domainmessage}/message.go | 2 +- {wire => domainmessage}/msgaddresses.go | 2 +- {wire => domainmessage}/msgaddresses_test.go | 2 +- {wire => domainmessage}/msgblock.go | 20 +- {wire => domainmessage}/msgblock_test.go | 38 ++-- {wire => domainmessage}/msgblocklocator.go | 2 +- .../msgblocklocator_test.go | 2 +- {wire => domainmessage}/msgdoneibdblocks.go | 2 +- {wire => domainmessage}/msgibdblock.go | 2 +- {wire => domainmessage}/msgibdblock_test.go | 14 +- {wire => domainmessage}/msginvrelayblock.go | 2 +- {wire => domainmessage}/msginvtransaction.go | 2 +- {wire => domainmessage}/msgping.go | 2 +- {wire => domainmessage}/msgping_test.go | 2 +- {wire => domainmessage}/msgpong.go | 2 +- {wire => domainmessage}/msgpong_test.go | 2 +- .../msgrequestaddresses.go | 2 +- .../msgrequestaddresses_test.go | 2 +- .../msgrequestblocklocator.go | 2 +- .../msgrequestblocklocator_test.go | 2 +- .../msgrequestibdblocks.go | 2 +- .../msgrequestibdblocks_test.go | 2 +- .../msgrequestnextibdblocks.go | 2 +- .../msgrequestrelayblocks.go | 2 +- .../msgrequestselectedtip.go | 2 +- .../msgrequestselectedtip_test.go | 2 +- .../msgrequesttransactions.go | 2 +- {wire => domainmessage}/msgselectedtip.go | 2 +- .../msgselectedtip_test.go | 2 +- .../msgtransactionnotfound.go | 2 +- {wire => domainmessage}/msgtx.go | 22 +-- {wire => domainmessage}/msgtx_test.go | 38 ++-- {wire => domainmessage}/msgverack.go | 2 +- {wire => domainmessage}/msgverack_test.go | 2 +- {wire => domainmessage}/msgversion.go | 8 +- {wire => domainmessage}/msgversion_test.go | 2 +- {wire => domainmessage}/netaddress.go | 4 +- {wire => domainmessage}/netaddress_test.go | 2 +- {wire => domainmessage}/protocol.go | 2 +- {wire => domainmessage}/protocol_test.go | 2 +- .../testdata/megatx.bin.bz2 | Bin integration/64_incoming_connections_test.go | 4 +- integration/basic_sync_test.go | 12 +- integration/ibd_test.go | 4 +- integration/mining_test.go | 4 +- integration/notifications_test.go | 4 +- integration/rpc_test.go | 6 +- integration/tx_relay_test.go | 18 +- mempool/error.go | 2 +- mempool/mempool.go | 36 ++-- mempool/mempool_test.go | 126 ++++++------- mempool/policy.go | 4 +- mempool/policy_test.go | 56 +++--- mining/mining.go | 6 +- mining/test_utils.go | 8 +- netadapter/netadapter.go | 10 +- netadapter/netconnection.go | 6 +- netadapter/router/route.go | 12 +- netadapter/router/router.go | 22 +-- .../server/grpcserver/connection_loops.go | 4 +- .../server/grpcserver/protowire/common.go | 10 +- .../grpcserver/protowire/message_addresses.go | 18 +- .../grpcserver/protowire/message_block.go | 34 ++-- .../protowire/message_block_locator.go | 16 +- .../protowire/message_done_ibd_blocks.go | 8 +- .../grpcserver/protowire/message_ibd_block.go | 12 +- .../protowire/message_inv_relay_block.go | 8 +- .../protowire/message_inv_transactions.go | 16 +- .../grpcserver/protowire/message_ping.go | 8 +- .../grpcserver/protowire/message_pong.go | 8 +- .../protowire/message_request_addresses.go | 8 +- .../message_request_block_locator.go | 8 +- .../protowire/message_request_ibd_blocks.go | 8 +- .../message_request_next_ibd_blocks.go | 8 +- .../protowire/message_request_relay_blocks.go | 16 +- .../protowire/message_request_selected_tip.go | 8 +- .../protowire/message_request_transactions.go | 16 +- .../protowire/message_selected_tip.go | 8 +- .../protowire/message_transaction.go | 26 +-- .../message_transaction_not_found.go | 8 +- .../grpcserver/protowire/message_verack.go | 8 +- .../grpcserver/protowire/message_version.go | 16 +- .../server/grpcserver/protowire/wire.go | 100 +++++----- netadapter/standalone/minimal_net_adapter.go | 28 +-- netadapter/standalone/routes.go | 4 +- protocol/flowcontext/blocks.go | 10 +- protocol/flowcontext/network.go | 4 +- protocol/flowcontext/transactions.go | 4 +- .../flows/addressexchange/receiveaddresses.go | 8 +- .../flows/addressexchange/sendaddresses.go | 14 +- .../blockrelay/handle_relay_block_requests.go | 6 +- .../flows/blockrelay/handle_relay_invs.go | 30 +-- protocol/flows/handshake/handshake.go | 4 +- protocol/flows/handshake/receiveversion.go | 14 +- protocol/flows/handshake/sendversion.go | 10 +- .../flows/ibd/handle_request_block_locator.go | 6 +- .../flows/ibd/handle_request_ibd_blocks.go | 20 +- protocol/flows/ibd/ibd.go | 22 +-- .../handle_request_selected_tip.go | 8 +- .../ibd/selectedtip/request_selected_tip.go | 6 +- protocol/flows/ping/receive.go | 6 +- protocol/flows/ping/send.go | 6 +- .../handle_relayed_transactions.go | 32 ++-- .../handle_requested_transactions.go | 10 +- protocol/peer/peer.go | 6 +- protocol/protocol.go | 40 ++-- rpc/client/dag.go | 14 +- rpc/client/examples/websockets/main.go | 4 +- rpc/client/infrastructure.go | 2 +- rpc/client/mining.go | 8 +- rpc/client/net.go | 24 +-- rpc/client/notify.go | 12 +- rpc/client/rawtransactions.go | 6 +- rpc/common.go | 16 +- rpc/handle_get_block_template.go | 8 +- rpc/handle_get_tx_out.go | 4 +- rpc/handle_load_tx_filter.go | 6 +- rpc/handle_rescan_block_filter.go | 4 +- rpc/handle_send_raw_transaction.go | 4 +- rpc/model/doc.go | 8 +- rpc/model/error.go | 2 +- rpc/model/example_test.go | 12 +- rpc/model/jsonrpc.go | 2 +- rpc/rpcserverhelp.go | 4 +- rpc/rpcwebsocket.go | 18 +- txscript/engine.go | 6 +- txscript/engine_test.go | 34 ++-- txscript/opcode.go | 16 +- txscript/reference_test.go | 20 +- txscript/script.go | 20 +- txscript/sign.go | 12 +- txscript/sign_test.go | 64 +++---- util/block.go | 34 ++-- util/block_test.go | 34 ++-- util/coinbasepayload/coinbasepayload.go | 8 +- util/doc.go | 4 +- util/testtools/testtools.go | 18 +- util/tx.go | 24 +-- util/txsort/txsort.go | 12 +- util/txsort/txsort_test.go | 4 +- wire/invvect.go | 98 ---------- wire/invvect_test.go | 173 ------------------ 188 files changed, 1486 insertions(+), 1774 deletions(-) rename {wire => domainmessage}/README.md (97%) rename {wire => domainmessage}/bench_test.go (99%) rename {wire => domainmessage}/blockheader.go (94%) rename {wire => domainmessage}/blockheader_test.go (95%) rename {wire => domainmessage}/common.go (97%) rename {wire => domainmessage}/common_test.go (87%) rename {wire => domainmessage}/doc.go (80%) rename {wire => domainmessage}/error.go (98%) rename {wire => domainmessage}/fakemessage_test.go (91%) rename {wire => domainmessage}/fixedIO_test.go (98%) rename {wire => domainmessage}/message.go (99%) rename {wire => domainmessage}/msgaddresses.go (99%) rename {wire => domainmessage}/msgaddresses_test.go (98%) rename {wire => domainmessage}/msgblock.go (91%) rename {wire => domainmessage}/msgblock_test.go (95%) rename {wire => domainmessage}/msgblocklocator.go (97%) rename {wire => domainmessage}/msgblocklocator_test.go (97%) rename {wire => domainmessage}/msgdoneibdblocks.go (96%) rename {wire => domainmessage}/msgibdblock.go (97%) rename {wire => domainmessage}/msgibdblock_test.go (89%) rename {wire => domainmessage}/msginvrelayblock.go (97%) rename {wire => domainmessage}/msginvtransaction.go (97%) rename {wire => domainmessage}/msgping.go (98%) rename {wire => domainmessage}/msgping_test.go (97%) rename {wire => domainmessage}/msgpong.go (97%) rename {wire => domainmessage}/msgpong_test.go (97%) rename {wire => domainmessage}/msgrequestaddresses.go (98%) rename {wire => domainmessage}/msgrequestaddresses_test.go (95%) rename {wire => domainmessage}/msgrequestblocklocator.go (97%) rename {wire => domainmessage}/msgrequestblocklocator_test.go (96%) rename {wire => domainmessage}/msgrequestibdblocks.go (97%) rename {wire => domainmessage}/msgrequestibdblocks_test.go (98%) rename {wire => domainmessage}/msgrequestnextibdblocks.go (96%) rename {wire => domainmessage}/msgrequestrelayblocks.go (97%) rename {wire => domainmessage}/msgrequestselectedtip.go (96%) rename {wire => domainmessage}/msgrequestselectedtip_test.go (95%) rename {wire => domainmessage}/msgrequesttransactions.go (97%) rename {wire => domainmessage}/msgselectedtip.go (97%) rename {wire => domainmessage}/msgselectedtip_test.go (94%) rename {wire => domainmessage}/msgtransactionnotfound.go (97%) rename {wire => domainmessage}/msgtx.go (97%) rename {wire => domainmessage}/msgtx_test.go (96%) rename {wire => domainmessage}/msgverack.go (97%) rename {wire => domainmessage}/msgverack_test.go (95%) rename {wire => domainmessage}/msgversion.go (96%) rename {wire => domainmessage}/msgversion_test.go (99%) rename {wire => domainmessage}/netaddress.go (98%) rename {wire => domainmessage}/netaddress_test.go (98%) rename {wire => domainmessage}/protocol.go (99%) rename {wire => domainmessage}/protocol_test.go (98%) rename {wire => domainmessage}/testdata/megatx.bin.bz2 (100%) delete mode 100644 wire/invvect.go delete mode 100644 wire/invvect_test.go diff --git a/addressmanager/addressmanager.go b/addressmanager/addressmanager.go index b1ec29108..ec93dd7ee 100644 --- a/addressmanager/addressmanager.go +++ b/addressmanager/addressmanager.go @@ -23,8 +23,8 @@ import ( "github.com/kaspanet/kaspad/util/subnetworkid" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) // AddressKey represents a "string" key in the form of ip:port for IPv4 addresses @@ -92,7 +92,7 @@ type PeersStateForSerialization struct { } type localAddress struct { - netAddress *wire.NetAddress + netAddress *domainmessage.NetAddress score AddressPriority } @@ -208,7 +208,7 @@ func New(cfg *config.Config, databaseContext *dbaccess.DatabaseContext) *Address // 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. -func (am *AddressManager) updateAddress(netAddress, sourceAddress *wire.NetAddress, subnetworkID *subnetworkid.SubnetworkID) { +func (am *AddressManager) updateAddress(netAddress, sourceAddress *domainmessage.NetAddress, subnetworkID *subnetworkid.SubnetworkID) { // Filter out non-routable addresses. Note that non-routable // also includes invalid and local addresses. if !am.IsRoutable(netAddress) { @@ -371,7 +371,7 @@ func (am *AddressManager) pickTried(subnetworkID *subnetworkid.SubnetworkID, buc return oldest, oldestIndex } -func (am *AddressManager) newAddressBucketIndex(netAddress, srcAddress *wire.NetAddress) int { +func (am *AddressManager) newAddressBucketIndex(netAddress, srcAddress *domainmessage.NetAddress) int { // doublesha256(key + sourcegroup + int64(doublesha256(key + group + sourcegroup))%bucket_per_source_group) % num_new_buckets data1 := []byte{} @@ -392,7 +392,7 @@ func (am *AddressManager) newAddressBucketIndex(netAddress, srcAddress *wire.Net return int(binary.LittleEndian.Uint64(hash2) % NewBucketCount) } -func (am *AddressManager) triedAddressBucketIndex(netAddress *wire.NetAddress) int { +func (am *AddressManager) triedAddressBucketIndex(netAddress *domainmessage.NetAddress) int { // doublesha256(key + group + truncate_to_64bits(doublesha256(key)) % buckets_per_group) % num_buckets data1 := []byte{} data1 = append(data1, am.key[:]...) @@ -705,8 +705,8 @@ func (am *AddressManager) deserializePeersState(serializedPeerState []byte) erro return nil } -// DeserializeNetAddress converts a given address string to a *wire.NetAddress -func (am *AddressManager) DeserializeNetAddress(addressKey AddressKey) (*wire.NetAddress, error) { +// DeserializeNetAddress converts a given address string to a *domainmessage.NetAddress +func (am *AddressManager) DeserializeNetAddress(addressKey AddressKey) (*domainmessage.NetAddress, error) { host, portString, err := net.SplitHostPort(string(addressKey)) if err != nil { return nil, err @@ -716,7 +716,7 @@ func (am *AddressManager) DeserializeNetAddress(addressKey AddressKey) (*wire.Ne return nil, err } - return am.HostToNetAddress(host, uint16(port), wire.SFNodeNetwork) + return am.HostToNetAddress(host, uint16(port), domainmessage.SFNodeNetwork) } // Start begins the core address handler which manages a pool of known @@ -758,7 +758,7 @@ func (am *AddressManager) Stop() error { // AddAddresses adds new addresses to the address manager. It enforces a max // number of addresses and silently ignores duplicate addresses. It is // safe for concurrent access. -func (am *AddressManager) AddAddresses(addresses []*wire.NetAddress, sourceAddress *wire.NetAddress, subnetworkID *subnetworkid.SubnetworkID) { +func (am *AddressManager) AddAddresses(addresses []*domainmessage.NetAddress, sourceAddress *domainmessage.NetAddress, subnetworkID *subnetworkid.SubnetworkID) { am.mutex.Lock() defer am.mutex.Unlock() @@ -770,7 +770,7 @@ func (am *AddressManager) AddAddresses(addresses []*wire.NetAddress, sourceAddre // AddAddress adds a new address to the address manager. It enforces a max // number of addresses and silently ignores duplicate addresses. It is // safe for concurrent access. -func (am *AddressManager) AddAddress(address, sourceAddress *wire.NetAddress, subnetworkID *subnetworkid.SubnetworkID) { +func (am *AddressManager) AddAddress(address, sourceAddress *domainmessage.NetAddress, subnetworkID *subnetworkid.SubnetworkID) { am.mutex.Lock() defer am.mutex.Unlock() @@ -778,14 +778,14 @@ func (am *AddressManager) AddAddress(address, sourceAddress *wire.NetAddress, su } // AddAddressByIP adds an address where we are given an ip:port and not a -// wire.NetAddress. +// domainmessage.NetAddress. func (am *AddressManager) AddAddressByIP(addressIP string, subnetworkID *subnetworkid.SubnetworkID) error { // Split IP and port ipString, portString, err := net.SplitHostPort(addressIP) if err != nil { return err } - // Put it in wire.Netaddress + // Put it in domainmessage.Netaddress ip := net.ParseIP(ipString) if ip == nil { return errors.Errorf("invalid ip %s", ipString) @@ -794,7 +794,7 @@ func (am *AddressManager) AddAddressByIP(addressIP string, subnetworkID *subnetw if err != nil { return errors.Errorf("invalid port %s: %s", portString, err) } - netAddress := wire.NewNetAddressIPPort(ip, uint16(port), 0) + netAddress := domainmessage.NewNetAddressIPPort(ip, uint16(port), 0) am.AddAddress(netAddress, netAddress, subnetworkID) // XXX use correct src address return nil } @@ -843,7 +843,7 @@ func (am *AddressManager) NeedMoreAddresses() bool { // 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). -func (am *AddressManager) AddressCache(includeAllSubnetworks bool, subnetworkID *subnetworkid.SubnetworkID) []*wire.NetAddress { +func (am *AddressManager) AddressCache(includeAllSubnetworks bool, subnetworkID *subnetworkid.SubnetworkID) []*domainmessage.NetAddress { am.mutex.Lock() defer am.mutex.Unlock() @@ -851,7 +851,7 @@ func (am *AddressManager) AddressCache(includeAllSubnetworks bool, subnetworkID return nil } - allAddresses := []*wire.NetAddress{} + allAddresses := []*domainmessage.NetAddress{} // Iteration order is undefined here, but we randomise it anyway. for _, v := range am.addressIndex { if includeAllSubnetworks || v.SubnetworkID().IsEqual(subnetworkID) { @@ -907,7 +907,7 @@ func (am *AddressManager) reset() { // HostToNetAddress returns a netaddress given a host address. If // the host is not an IP address it will be resolved. -func (am *AddressManager) HostToNetAddress(host string, port uint16, services wire.ServiceFlag) (*wire.NetAddress, error) { +func (am *AddressManager) HostToNetAddress(host string, port uint16, services domainmessage.ServiceFlag) (*domainmessage.NetAddress, error) { ip := net.ParseIP(host) if ip == nil { ips, err := am.lookupFunc(host) @@ -920,12 +920,12 @@ func (am *AddressManager) HostToNetAddress(host string, port uint16, services wi ip = ips[0] } - return wire.NewNetAddressIPPort(ip, port, services), nil + return domainmessage.NewNetAddressIPPort(ip, port, services), nil } // NetAddressKey returns a key in the form of ip:port for IPv4 addresses // or [ip]:port for IPv6 addresses for use as keys in maps. -func NetAddressKey(netAddress *wire.NetAddress) AddressKey { +func NetAddressKey(netAddress *domainmessage.NetAddress) AddressKey { port := strconv.FormatUint(uint64(netAddress.Port), 10) return AddressKey(net.JoinHostPort(netAddress.IP.String(), port)) @@ -1031,13 +1031,13 @@ func (tb *triedAddressBucketArray) name() string { return "tried" } -func (am *AddressManager) knownAddress(address *wire.NetAddress) *KnownAddress { +func (am *AddressManager) knownAddress(address *domainmessage.NetAddress) *KnownAddress { return am.addressIndex[NetAddressKey(address)] } // Attempt increases the given address' attempt counter and updates // the last attempt time. -func (am *AddressManager) Attempt(address *wire.NetAddress) { +func (am *AddressManager) Attempt(address *domainmessage.NetAddress) { am.mutex.Lock() defer am.mutex.Unlock() @@ -1055,7 +1055,7 @@ func (am *AddressManager) Attempt(address *wire.NetAddress) { // Connected Marks the given address as currently connected and working at the // current time. The address must already be known to AddressManager else it will // be ignored. -func (am *AddressManager) Connected(address *wire.NetAddress) { +func (am *AddressManager) Connected(address *domainmessage.NetAddress) { am.mutex.Lock() defer am.mutex.Unlock() @@ -1078,7 +1078,7 @@ func (am *AddressManager) Connected(address *wire.NetAddress) { // 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 // manager it will be ignored. -func (am *AddressManager) Good(address *wire.NetAddress, subnetworkID *subnetworkid.SubnetworkID) { +func (am *AddressManager) Good(address *domainmessage.NetAddress, subnetworkID *subnetworkid.SubnetworkID) { am.mutex.Lock() defer am.mutex.Unlock() @@ -1254,7 +1254,7 @@ func (am *AddressManager) incrementTriedAddressCount(subnetworkID *subnetworkid. // AddLocalAddress adds netAddress to the list of known local addresses to advertise // with the given priority. -func (am *AddressManager) AddLocalAddress(netAddress *wire.NetAddress, priority AddressPriority) error { +func (am *AddressManager) AddLocalAddress(netAddress *domainmessage.NetAddress, priority AddressPriority) error { if !am.IsRoutable(netAddress) { return errors.Errorf("address %s is not routable", netAddress.IP) } @@ -1279,7 +1279,7 @@ func (am *AddressManager) AddLocalAddress(netAddress *wire.NetAddress, priority // getReachabilityFrom returns the relative reachability of the provided local // address to the provided remote address. -func (am *AddressManager) getReachabilityFrom(localAddress, remoteAddress *wire.NetAddress) int { +func (am *AddressManager) getReachabilityFrom(localAddress, remoteAddress *domainmessage.NetAddress) int { const ( Unreachable = 0 Default = iota @@ -1346,13 +1346,13 @@ func (am *AddressManager) getReachabilityFrom(localAddress, remoteAddress *wire. // GetBestLocalAddress returns the most appropriate local address to use // for the given remote address. -func (am *AddressManager) GetBestLocalAddress(remoteAddress *wire.NetAddress) *wire.NetAddress { +func (am *AddressManager) GetBestLocalAddress(remoteAddress *domainmessage.NetAddress) *domainmessage.NetAddress { am.localAddressesLock.Lock() defer am.localAddressesLock.Unlock() bestReach := 0 var bestScore AddressPriority - var bestAddress *wire.NetAddress + var bestAddress *domainmessage.NetAddress for _, localAddress := range am.localAddresses { reach := am.getReachabilityFrom(localAddress.netAddress, remoteAddress) if reach > bestReach || @@ -1376,24 +1376,24 @@ func (am *AddressManager) GetBestLocalAddress(remoteAddress *wire.NetAddress) *w } else { ip = net.IPv4zero } - services := wire.SFNodeNetwork | wire.SFNodeBloom - bestAddress = wire.NewNetAddressIPPort(ip, 0, services) + services := domainmessage.SFNodeNetwork | domainmessage.SFNodeBloom + bestAddress = domainmessage.NewNetAddressIPPort(ip, 0, services) } return bestAddress } // Ban marks the given address as banned -func (am *AddressManager) Ban(address *wire.NetAddress) error { +func (am *AddressManager) Ban(address *domainmessage.NetAddress) error { return am.setBanned(address, true, mstime.Now()) } // Unban marks the given address as not banned -func (am *AddressManager) Unban(address *wire.NetAddress) error { +func (am *AddressManager) Unban(address *domainmessage.NetAddress) error { return am.setBanned(address, false, mstime.Time{}) } -func (am *AddressManager) setBanned(address *wire.NetAddress, isBanned bool, bannedTime mstime.Time) error { +func (am *AddressManager) setBanned(address *domainmessage.NetAddress, isBanned bool, bannedTime mstime.Time) error { am.localAddressesLock.Lock() defer am.localAddressesLock.Unlock() @@ -1408,7 +1408,7 @@ func (am *AddressManager) setBanned(address *wire.NetAddress, isBanned bool, ban } // IsBanned returns whether the given address is banned -func (am *AddressManager) IsBanned(address *wire.NetAddress) (bool, error) { +func (am *AddressManager) IsBanned(address *domainmessage.NetAddress) (bool, error) { am.localAddressesLock.Lock() defer am.localAddressesLock.Unlock() diff --git a/addressmanager/addressmanager_test.go b/addressmanager/addressmanager_test.go index 90a83787d..fec92c909 100644 --- a/addressmanager/addressmanager_test.go +++ b/addressmanager/addressmanager_test.go @@ -19,13 +19,13 @@ import ( "github.com/pkg/errors" - "github.com/kaspanet/kaspad/wire" + "github.com/kaspanet/kaspad/domainmessage" ) // naTest is used to describe a test to be performed against the NetAddressKey // method. type naTest struct { - in wire.NetAddress + in domainmessage.NetAddress want AddressKey } @@ -99,7 +99,7 @@ func addNaTests() { func addNaTest(ip string, port uint16, want AddressKey) { nip := net.ParseIP(ip) - na := *wire.NewNetAddressIPPort(nip, port, wire.SFNodeNetwork) + na := *domainmessage.NewNetAddressIPPort(nip, port, domainmessage.SFNodeNetwork) test := naTest{na, want} naTests = append(naTests, test) } @@ -194,37 +194,37 @@ func TestAddAddressByIP(t *testing.T) { func TestAddLocalAddress(t *testing.T) { var tests = []struct { - address wire.NetAddress + address domainmessage.NetAddress priority AddressPriority valid bool }{ { - wire.NetAddress{IP: net.ParseIP("192.168.0.100")}, + domainmessage.NetAddress{IP: net.ParseIP("192.168.0.100")}, InterfacePrio, false, }, { - wire.NetAddress{IP: net.ParseIP("204.124.1.1")}, + domainmessage.NetAddress{IP: net.ParseIP("204.124.1.1")}, InterfacePrio, true, }, { - wire.NetAddress{IP: net.ParseIP("204.124.1.1")}, + domainmessage.NetAddress{IP: net.ParseIP("204.124.1.1")}, BoundPrio, true, }, { - wire.NetAddress{IP: net.ParseIP("::1")}, + domainmessage.NetAddress{IP: net.ParseIP("::1")}, InterfacePrio, false, }, { - wire.NetAddress{IP: net.ParseIP("fe80::1")}, + domainmessage.NetAddress{IP: net.ParseIP("fe80::1")}, InterfacePrio, false, }, { - wire.NetAddress{IP: net.ParseIP("2620:100::1")}, + domainmessage.NetAddress{IP: net.ParseIP("2620:100::1")}, InterfacePrio, true, }, @@ -298,7 +298,7 @@ func TestNeedMoreAddresses(t *testing.T) { if !b { t.Errorf("Expected that we need more addresses") } - addrs := make([]*wire.NetAddress, addrsToAdd) + addrs := make([]*domainmessage.NetAddress, addrsToAdd) var err error for i := 0; i < addrsToAdd; i++ { @@ -309,7 +309,7 @@ func TestNeedMoreAddresses(t *testing.T) { } } - srcAddr := wire.NewNetAddressIPPort(net.IPv4(173, 144, 173, 111), 8333, 0) + srcAddr := domainmessage.NewNetAddressIPPort(net.IPv4(173, 144, 173, 111), 8333, 0) amgr.AddAddresses(addrs, srcAddr, nil) numAddrs := amgr.TotalNumAddresses() @@ -327,7 +327,7 @@ func TestGood(t *testing.T) { amgr, teardown := newAddrManagerForTest(t, "TestGood", nil) defer teardown() addrsToAdd := 64 * 64 - addrs := make([]*wire.NetAddress, addrsToAdd) + addrs := make([]*domainmessage.NetAddress, addrsToAdd) subnetworkCount := 32 subnetworkIDs := make([]*subnetworkid.SubnetworkID, subnetworkCount) @@ -344,7 +344,7 @@ func TestGood(t *testing.T) { subnetworkIDs[i] = &subnetworkid.SubnetworkID{0xff - byte(i)} } - srcAddr := wire.NewNetAddressIPPort(net.IPv4(173, 144, 173, 111), 8333, 0) + srcAddr := domainmessage.NewNetAddressIPPort(net.IPv4(173, 144, 173, 111), 8333, 0) amgr.AddAddresses(addrs, srcAddr, nil) for i, addr := range addrs { @@ -374,9 +374,9 @@ func TestGood(t *testing.T) { func TestGoodChangeSubnetworkID(t *testing.T) { amgr, teardown := newAddrManagerForTest(t, "TestGoodChangeSubnetworkID", nil) defer teardown() - addr := wire.NewNetAddressIPPort(net.IPv4(173, 144, 173, 111), 8333, 0) + addr := domainmessage.NewNetAddressIPPort(net.IPv4(173, 144, 173, 111), 8333, 0) addrKey := NetAddressKey(addr) - srcAddr := wire.NewNetAddressIPPort(net.IPv4(173, 144, 173, 111), 8333, 0) + srcAddr := domainmessage.NewNetAddressIPPort(net.IPv4(173, 144, 173, 111), 8333, 0) oldSubnetwork := subnetworkid.SubnetworkIDNative amgr.AddAddress(addr, srcAddr, oldSubnetwork) @@ -515,7 +515,7 @@ func TestGetAddress(t *testing.T) { } func TestGetBestLocalAddress(t *testing.T) { - localAddrs := []wire.NetAddress{ + localAddrs := []domainmessage.NetAddress{ {IP: net.ParseIP("192.168.0.100")}, {IP: net.ParseIP("::1")}, {IP: net.ParseIP("fe80::1")}, @@ -523,43 +523,43 @@ func TestGetBestLocalAddress(t *testing.T) { } var tests = []struct { - remoteAddr wire.NetAddress - want0 wire.NetAddress - want1 wire.NetAddress - want2 wire.NetAddress - want3 wire.NetAddress + remoteAddr domainmessage.NetAddress + want0 domainmessage.NetAddress + want1 domainmessage.NetAddress + want2 domainmessage.NetAddress + want3 domainmessage.NetAddress }{ { // Remote connection from public IPv4 - wire.NetAddress{IP: net.ParseIP("204.124.8.1")}, - wire.NetAddress{IP: net.IPv4zero}, - wire.NetAddress{IP: net.IPv4zero}, - wire.NetAddress{IP: net.ParseIP("204.124.8.100")}, - wire.NetAddress{IP: net.ParseIP("fd87:d87e:eb43:25::1")}, + domainmessage.NetAddress{IP: net.ParseIP("204.124.8.1")}, + domainmessage.NetAddress{IP: net.IPv4zero}, + domainmessage.NetAddress{IP: net.IPv4zero}, + domainmessage.NetAddress{IP: net.ParseIP("204.124.8.100")}, + domainmessage.NetAddress{IP: net.ParseIP("fd87:d87e:eb43:25::1")}, }, { // Remote connection from private IPv4 - wire.NetAddress{IP: net.ParseIP("172.16.0.254")}, - wire.NetAddress{IP: net.IPv4zero}, - wire.NetAddress{IP: net.IPv4zero}, - wire.NetAddress{IP: net.IPv4zero}, - wire.NetAddress{IP: net.IPv4zero}, + domainmessage.NetAddress{IP: net.ParseIP("172.16.0.254")}, + domainmessage.NetAddress{IP: net.IPv4zero}, + domainmessage.NetAddress{IP: net.IPv4zero}, + domainmessage.NetAddress{IP: net.IPv4zero}, + domainmessage.NetAddress{IP: net.IPv4zero}, }, { // Remote connection from public IPv6 - wire.NetAddress{IP: net.ParseIP("2602:100:abcd::102")}, - wire.NetAddress{IP: net.IPv6zero}, - wire.NetAddress{IP: net.ParseIP("2001:470::1")}, - wire.NetAddress{IP: net.ParseIP("2001:470::1")}, - wire.NetAddress{IP: net.ParseIP("2001:470::1")}, + domainmessage.NetAddress{IP: net.ParseIP("2602:100:abcd::102")}, + domainmessage.NetAddress{IP: net.IPv6zero}, + domainmessage.NetAddress{IP: net.ParseIP("2001:470::1")}, + domainmessage.NetAddress{IP: net.ParseIP("2001:470::1")}, + domainmessage.NetAddress{IP: net.ParseIP("2001:470::1")}, }, /* XXX { // Remote connection from Tor - wire.NetAddress{IP: net.ParseIP("fd87:d87e:eb43::100")}, - wire.NetAddress{IP: net.IPv4zero}, - wire.NetAddress{IP: net.ParseIP("204.124.8.100")}, - wire.NetAddress{IP: net.ParseIP("fd87:d87e:eb43:25::1")}, + domainmessage.NetAddress{IP: net.ParseIP("fd87:d87e:eb43::100")}, + domainmessage.NetAddress{IP: net.IPv4zero}, + domainmessage.NetAddress{IP: net.ParseIP("204.124.8.100")}, + domainmessage.NetAddress{IP: net.ParseIP("fd87:d87e:eb43:25::1")}, }, */ } @@ -592,7 +592,7 @@ func TestGetBestLocalAddress(t *testing.T) { } // Add a public IP to the list of local addresses. - localAddr := wire.NetAddress{IP: net.ParseIP("204.124.8.100")} + localAddr := domainmessage.NetAddress{IP: net.ParseIP("204.124.8.100")} amgr.AddLocalAddress(&localAddr, InterfacePrio) // Test against want2 @@ -606,7 +606,7 @@ func TestGetBestLocalAddress(t *testing.T) { } /* // Add a Tor generated IP address - localAddr = wire.NetAddress{IP: net.ParseIP("fd87:d87e:eb43:25::1")} + localAddr = domainmessage.NetAddress{IP: net.ParseIP("fd87:d87e:eb43:25::1")} amgr.AddLocalAddress(&localAddr, ManualPrio) // Test against want3 for x, test := range tests { diff --git a/addressmanager/internal_test.go b/addressmanager/internal_test.go index b89143a2c..9d3c32401 100644 --- a/addressmanager/internal_test.go +++ b/addressmanager/internal_test.go @@ -5,8 +5,8 @@ package addressmanager import ( + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util/mstime" - "github.com/kaspanet/kaspad/wire" ) func TstKnownAddressIsBad(ka *KnownAddress) bool { @@ -17,7 +17,7 @@ func TstKnownAddressChance(ka *KnownAddress) float64 { return ka.chance() } -func TstNewKnownAddress(na *wire.NetAddress, attempts int, +func TstNewKnownAddress(na *domainmessage.NetAddress, attempts int, lastattempt, lastsuccess mstime.Time, tried bool, refs int) *KnownAddress { return &KnownAddress{netAddress: na, attempts: attempts, lastAttempt: lastattempt, lastSuccess: lastsuccess, tried: tried, referenceCount: refs} diff --git a/addressmanager/knownaddress.go b/addressmanager/knownaddress.go index 38549ae09..ba01f3d0f 100644 --- a/addressmanager/knownaddress.go +++ b/addressmanager/knownaddress.go @@ -10,14 +10,14 @@ import ( "github.com/kaspanet/kaspad/util/subnetworkid" - "github.com/kaspanet/kaspad/wire" + "github.com/kaspanet/kaspad/domainmessage" ) // KnownAddress tracks information about a known network address that is used // to determine how viable an address is. type KnownAddress struct { - netAddress *wire.NetAddress - sourceAddress *wire.NetAddress + netAddress *domainmessage.NetAddress + sourceAddress *domainmessage.NetAddress attempts int lastAttempt mstime.Time lastSuccess mstime.Time @@ -28,9 +28,9 @@ type KnownAddress struct { bannedTime mstime.Time } -// NetAddress returns the underlying wire.NetAddress associated with the +// NetAddress returns the underlying domainmessage.NetAddress associated with the // known address. -func (ka *KnownAddress) NetAddress() *wire.NetAddress { +func (ka *KnownAddress) NetAddress() *domainmessage.NetAddress { return ka.netAddress } diff --git a/addressmanager/knownaddress_test.go b/addressmanager/knownaddress_test.go index 65bca6e26..c5f698eb0 100644 --- a/addressmanager/knownaddress_test.go +++ b/addressmanager/knownaddress_test.go @@ -11,7 +11,7 @@ import ( "time" "github.com/kaspanet/kaspad/addressmanager" - "github.com/kaspanet/kaspad/wire" + "github.com/kaspanet/kaspad/domainmessage" ) func TestChance(t *testing.T) { @@ -22,27 +22,27 @@ func TestChance(t *testing.T) { }{ { //Test normal case - addressmanager.TstNewKnownAddress(&wire.NetAddress{Timestamp: now.Add(-35 * time.Second)}, + addressmanager.TstNewKnownAddress(&domainmessage.NetAddress{Timestamp: now.Add(-35 * time.Second)}, 0, mstime.Now().Add(-30*time.Minute), mstime.Now(), false, 0), 1.0, }, { //Test case in which lastseen < 0 - addressmanager.TstNewKnownAddress(&wire.NetAddress{Timestamp: now.Add(20 * time.Second)}, + addressmanager.TstNewKnownAddress(&domainmessage.NetAddress{Timestamp: now.Add(20 * time.Second)}, 0, mstime.Now().Add(-30*time.Minute), mstime.Now(), false, 0), 1.0, }, { //Test case in which lastAttempt < 0 - addressmanager.TstNewKnownAddress(&wire.NetAddress{Timestamp: now.Add(-35 * time.Second)}, + addressmanager.TstNewKnownAddress(&domainmessage.NetAddress{Timestamp: now.Add(-35 * time.Second)}, 0, mstime.Now().Add(30*time.Minute), mstime.Now(), false, 0), 1.0 * .01, }, { //Test case in which lastAttempt < ten minutes - addressmanager.TstNewKnownAddress(&wire.NetAddress{Timestamp: now.Add(-35 * time.Second)}, + addressmanager.TstNewKnownAddress(&domainmessage.NetAddress{Timestamp: now.Add(-35 * time.Second)}, 0, mstime.Now().Add(-5*time.Minute), mstime.Now(), false, 0), 1.0 * .01, }, { //Test case with several failed attempts. - addressmanager.TstNewKnownAddress(&wire.NetAddress{Timestamp: now.Add(-35 * time.Second)}, + addressmanager.TstNewKnownAddress(&domainmessage.NetAddress{Timestamp: now.Add(-35 * time.Second)}, 2, mstime.Now().Add(-30*time.Minute), mstime.Now(), false, 0), 1 / 1.5 / 1.5, }, @@ -66,10 +66,10 @@ func TestIsBad(t *testing.T) { hoursOld := now.Add(-5 * time.Hour) zeroTime := mstime.Time{} - futureNa := &wire.NetAddress{Timestamp: future} - minutesOldNa := &wire.NetAddress{Timestamp: minutesOld} - monthOldNa := &wire.NetAddress{Timestamp: monthOld} - currentNa := &wire.NetAddress{Timestamp: secondsOld} + futureNa := &domainmessage.NetAddress{Timestamp: future} + minutesOldNa := &domainmessage.NetAddress{Timestamp: minutesOld} + monthOldNa := &domainmessage.NetAddress{Timestamp: monthOld} + currentNa := &domainmessage.NetAddress{Timestamp: secondsOld} //Test addresses that have been tried in the last minute. if addressmanager.TstKnownAddressIsBad(addressmanager.TstNewKnownAddress(futureNa, 3, secondsOld, zeroTime, false, 0)) { diff --git a/addressmanager/network.go b/addressmanager/network.go index 5766e12c2..294e252f9 100644 --- a/addressmanager/network.go +++ b/addressmanager/network.go @@ -7,7 +7,7 @@ package addressmanager import ( "net" - "github.com/kaspanet/kaspad/wire" + "github.com/kaspanet/kaspad/domainmessage" ) var ( @@ -86,19 +86,19 @@ func ipNet(ip string, ones, bits int) net.IPNet { } // IsIPv4 returns whether or not the given address is an IPv4 address. -func IsIPv4(na *wire.NetAddress) bool { +func IsIPv4(na *domainmessage.NetAddress) bool { return na.IP.To4() != nil } // IsLocal returns whether or not the given address is a local address. -func IsLocal(na *wire.NetAddress) bool { +func IsLocal(na *domainmessage.NetAddress) bool { return na.IP.IsLoopback() || zero4Net.Contains(na.IP) } // 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, // 172.16.0.0/12, or 192.168.0.0/16). -func IsRFC1918(na *wire.NetAddress) bool { +func IsRFC1918(na *domainmessage.NetAddress) bool { for _, rfc := range rfc1918Nets { if rfc.Contains(na.IP) { return true @@ -109,56 +109,56 @@ func IsRFC1918(na *wire.NetAddress) bool { // IsRFC2544 returns whether or not the passed address is part of the IPv4 // address space as defined by RFC2544 (198.18.0.0/15) -func IsRFC2544(na *wire.NetAddress) bool { +func IsRFC2544(na *domainmessage.NetAddress) bool { return rfc2544Net.Contains(na.IP) } // IsRFC3849 returns whether or not the passed address is part of the IPv6 // documentation range as defined by RFC3849 (2001:DB8::/32). -func IsRFC3849(na *wire.NetAddress) bool { +func IsRFC3849(na *domainmessage.NetAddress) bool { return rfc3849Net.Contains(na.IP) } // IsRFC3927 returns whether or not the passed address is part of the IPv4 // autoconfiguration range as defined by RFC3927 (169.254.0.0/16). -func IsRFC3927(na *wire.NetAddress) bool { +func IsRFC3927(na *domainmessage.NetAddress) bool { return rfc3927Net.Contains(na.IP) } // IsRFC3964 returns whether or not the passed address is part of the IPv6 to // IPv4 encapsulation range as defined by RFC3964 (2002::/16). -func IsRFC3964(na *wire.NetAddress) bool { +func IsRFC3964(na *domainmessage.NetAddress) bool { return rfc3964Net.Contains(na.IP) } // IsRFC4193 returns whether or not the passed address is part of the IPv6 // unique local range as defined by RFC4193 (FC00::/7). -func IsRFC4193(na *wire.NetAddress) bool { +func IsRFC4193(na *domainmessage.NetAddress) bool { return rfc4193Net.Contains(na.IP) } // IsRFC4380 returns whether or not the passed address is part of the IPv6 // teredo tunneling over UDP range as defined by RFC4380 (2001::/32). -func IsRFC4380(na *wire.NetAddress) bool { +func IsRFC4380(na *domainmessage.NetAddress) bool { return rfc4380Net.Contains(na.IP) } // IsRFC4843 returns whether or not the passed address is part of the IPv6 // ORCHID range as defined by RFC4843 (2001:10::/28). -func IsRFC4843(na *wire.NetAddress) bool { +func IsRFC4843(na *domainmessage.NetAddress) bool { return rfc4843Net.Contains(na.IP) } // IsRFC4862 returns whether or not the passed address is part of the IPv6 // stateless address autoconfiguration range as defined by RFC4862 (FE80::/64). -func IsRFC4862(na *wire.NetAddress) bool { +func IsRFC4862(na *domainmessage.NetAddress) bool { return rfc4862Net.Contains(na.IP) } // 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, // 198.51.100.0/24, 203.0.113.0/24) -func IsRFC5737(na *wire.NetAddress) bool { +func IsRFC5737(na *domainmessage.NetAddress) bool { for _, rfc := range rfc5737Net { if rfc.Contains(na.IP) { return true @@ -170,19 +170,19 @@ func IsRFC5737(na *wire.NetAddress) bool { // IsRFC6052 returns whether or not the passed address is part of the IPv6 // well-known prefix range as defined by RFC6052 (64:FF9B::/96). -func IsRFC6052(na *wire.NetAddress) bool { +func IsRFC6052(na *domainmessage.NetAddress) bool { return rfc6052Net.Contains(na.IP) } // 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). -func IsRFC6145(na *wire.NetAddress) bool { +func IsRFC6145(na *domainmessage.NetAddress) bool { return rfc6145Net.Contains(na.IP) } // IsRFC6598 returns whether or not the passed address is part of the IPv4 // shared address space specified by RFC6598 (100.64.0.0/10) -func IsRFC6598(na *wire.NetAddress) bool { +func IsRFC6598(na *domainmessage.NetAddress) bool { return rfc6598Net.Contains(na.IP) } @@ -190,7 +190,7 @@ func IsRFC6598(na *wire.NetAddress) bool { // considered invalid under the following circumstances: // IPv4: It is either a zero or all bits set address. // IPv6: It is either a zero or RFC3849 documentation address. -func IsValid(na *wire.NetAddress) bool { +func IsValid(na *domainmessage.NetAddress) bool { // IsUnspecified returns if address is 0, so only all bits set, and // RFC3849 need to be explicitly checked. return na.IP != nil && !(na.IP.IsUnspecified() || @@ -200,7 +200,7 @@ func IsValid(na *wire.NetAddress) bool { // 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 // in any reserved ranges. -func (am *AddressManager) IsRoutable(na *wire.NetAddress) bool { +func (am *AddressManager) IsRoutable(na *domainmessage.NetAddress) bool { if am.cfg.NetParams().AcceptUnroutable { return !IsLocal(na) } @@ -215,7 +215,7 @@ func (am *AddressManager) IsRoutable(na *wire.NetAddress) bool { // of. This is the /16 for IPv4, the /32 (/36 for he.net) for IPv6, the string // "local" for a local address, and the string "unroutable" for an unroutable // address. -func (am *AddressManager) GroupKey(na *wire.NetAddress) string { +func (am *AddressManager) GroupKey(na *domainmessage.NetAddress) string { if IsLocal(na) { return "local" } diff --git a/addressmanager/network_test.go b/addressmanager/network_test.go index 40cd92306..04efa3a24 100644 --- a/addressmanager/network_test.go +++ b/addressmanager/network_test.go @@ -8,7 +8,7 @@ import ( "net" "testing" - "github.com/kaspanet/kaspad/wire" + "github.com/kaspanet/kaspad/domainmessage" ) // TestIPTypes ensures the various functions which determine the type of an IP @@ -17,7 +17,7 @@ func TestIPTypes(t *testing.T) { amgr, teardown := newAddrManagerForTest(t, "TestAddAddressByIP", nil) defer teardown() type ipTest struct { - in wire.NetAddress + in domainmessage.NetAddress rfc1918 bool rfc2544 bool rfc3849 bool @@ -40,7 +40,7 @@ func TestIPTypes(t *testing.T) { rfc4193, rfc4380, rfc4843, rfc4862, rfc5737, rfc6052, rfc6145, rfc6598, local, valid, routable bool) ipTest { nip := net.ParseIP(ip) - na := *wire.NewNetAddressIPPort(nip, 16111, wire.SFNodeNetwork) + na := *domainmessage.NewNetAddressIPPort(nip, 16111, domainmessage.SFNodeNetwork) test := ipTest{na, rfc1918, rfc2544, rfc3849, rfc3927, rfc3964, rfc4193, rfc4380, rfc4843, rfc4862, rfc5737, rfc6052, rfc6145, rfc6598, local, valid, routable} return test @@ -196,7 +196,7 @@ func TestGroupKey(t *testing.T) { for i, test := range tests { nip := net.ParseIP(test.ip) - na := *wire.NewNetAddressIPPort(nip, 8333, wire.SFNodeNetwork) + na := *domainmessage.NewNetAddressIPPort(nip, 8333, domainmessage.SFNodeNetwork) if key := amgr.GroupKey(&na); key != test.expected { t.Errorf("TestGroupKey #%d (%s): unexpected group key "+ "- got '%s', want '%s'", i, test.name, diff --git a/app/app.go b/app/app.go index a0e26a8cd..5f8ebed2d 100644 --- a/app/app.go +++ b/app/app.go @@ -14,6 +14,7 @@ import ( "github.com/kaspanet/kaspad/connmanager" "github.com/kaspanet/kaspad/dbaccess" "github.com/kaspanet/kaspad/dnsseed" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/mempool" "github.com/kaspanet/kaspad/mining" "github.com/kaspanet/kaspad/netadapter" @@ -23,7 +24,6 @@ import ( "github.com/kaspanet/kaspad/txscript" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/panics" - "github.com/kaspanet/kaspad/wire" ) // App is a wrapper for all the kaspad services @@ -138,8 +138,8 @@ func New(cfg *config.Config, databaseContext *dbaccess.DatabaseContext, interrup func (a *App) maybeSeedFromDNS() { if !a.cfg.DisableDNSSeed { - dnsseed.SeedFromDNS(a.cfg.NetParams(), a.cfg.DNSSeed, wire.SFNodeNetwork, false, nil, - a.cfg.Lookup, func(addresses []*wire.NetAddress) { + dnsseed.SeedFromDNS(a.cfg.NetParams(), a.cfg.DNSSeed, domainmessage.SFNodeNetwork, false, nil, + a.cfg.Lookup, func(addresses []*domainmessage.NetAddress) { // Kaspad uses a lookup of the dns seeder here. Since seeder returns // IPs of nodes and not its own IP, we can not know real IP of // source. So we'll take first returned address as source. diff --git a/blockdag/blocknode.go b/blockdag/blocknode.go index 998297728..dcb157f67 100644 --- a/blockdag/blocknode.go +++ b/blockdag/blocknode.go @@ -12,8 +12,8 @@ import ( "github.com/kaspanet/kaspad/util/mstime" "github.com/pkg/errors" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) // blockStatus is a bit field representing the validation state of the block. @@ -106,7 +106,7 @@ type blockNode struct { // anticone of its selected parent (parent with highest blue score). // selectedParentAnticone is used to update reachability data we store for future reachability queries. // This function is NOT safe for concurrent access. -func (dag *BlockDAG) newBlockNode(blockHeader *wire.BlockHeader, parents blockSet) (node *blockNode, selectedParentAnticone []*blockNode) { +func (dag *BlockDAG) newBlockNode(blockHeader *domainmessage.BlockHeader, parents blockSet) (node *blockNode, selectedParentAnticone []*blockNode) { node = &blockNode{ parents: parents, children: make(blockSet), @@ -160,9 +160,9 @@ func (node *blockNode) less(other *blockNode) bool { // Header constructs a block header from the node and returns it. // // This function is safe for concurrent access. -func (node *blockNode) Header() *wire.BlockHeader { +func (node *blockNode) Header() *domainmessage.BlockHeader { // No lock is needed because all accessed fields are immutable. - return &wire.BlockHeader{ + return &domainmessage.BlockHeader{ Version: node.version, ParentHashes: node.ParentHashes(), HashMerkleRoot: node.hashMerkleRoot, diff --git a/blockdag/coinbase.go b/blockdag/coinbase.go index c8838a162..cc407e6ad 100644 --- a/blockdag/coinbase.go +++ b/blockdag/coinbase.go @@ -7,12 +7,12 @@ import ( "io" "github.com/kaspanet/kaspad/dbaccess" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/coinbasepayload" "github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/subnetworkid" "github.com/kaspanet/kaspad/util/txsort" - "github.com/kaspanet/kaspad/wire" "github.com/pkg/errors" ) @@ -124,8 +124,8 @@ func (node *blockNode) expectedCoinbaseTransaction(dag *BlockDAG, txsAcceptanceD return nil, err } - txIns := []*wire.TxIn{} - txOuts := []*wire.TxOut{} + txIns := []*domainmessage.TxIn{} + txOuts := []*domainmessage.TxOut{} for _, blue := range node.blues { txOut, err := coinbaseOutputForBlueBlock(dag, blue, txsAcceptanceData, bluesFeeData) @@ -140,7 +140,7 @@ func (node *blockNode) expectedCoinbaseTransaction(dag *BlockDAG, txsAcceptanceD if err != nil { return nil, err } - coinbaseTx := wire.NewSubnetworkMsgTx(wire.TxVersion, txIns, txOuts, subnetworkid.SubnetworkIDCoinbase, 0, payload) + coinbaseTx := domainmessage.NewSubnetworkMsgTx(domainmessage.TxVersion, txIns, txOuts, subnetworkid.SubnetworkIDCoinbase, 0, payload) sortedCoinbaseTx := txsort.Sort(coinbaseTx) return util.NewTx(sortedCoinbaseTx), nil } @@ -148,7 +148,7 @@ func (node *blockNode) expectedCoinbaseTransaction(dag *BlockDAG, txsAcceptanceD // coinbaseOutputForBlueBlock calculates the output that should go into the coinbase transaction of blueBlock // If blueBlock gets no fee - returns nil for txOut func coinbaseOutputForBlueBlock(dag *BlockDAG, blueBlock *blockNode, - txsAcceptanceData MultiBlockTxsAcceptanceData, feeData map[daghash.Hash]compactFeeData) (*wire.TxOut, error) { + txsAcceptanceData MultiBlockTxsAcceptanceData, feeData map[daghash.Hash]compactFeeData) (*domainmessage.TxOut, error) { blockTxsAcceptanceData, ok := txsAcceptanceData.FindAcceptanceData(blueBlock.hash) if !ok { @@ -190,7 +190,7 @@ func coinbaseOutputForBlueBlock(dag *BlockDAG, blueBlock *blockNode, return nil, err } - txOut := &wire.TxOut{ + txOut := &domainmessage.TxOut{ Value: totalReward, ScriptPubKey: scriptPubKey, } diff --git a/blockdag/common_test.go b/blockdag/common_test.go index 6180c9cf6..508b19844 100644 --- a/blockdag/common_test.go +++ b/blockdag/common_test.go @@ -18,9 +18,9 @@ import ( "github.com/pkg/errors" "github.com/kaspanet/kaspad/dagconfig" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) // loadUTXOSet returns a utxo view loaded from a file. @@ -78,7 +78,7 @@ func loadUTXOSet(filename string) (UTXOSet, error) { if err != nil { return nil, err } - utxoSet.utxoCollection[wire.Outpoint{TxID: txID, Index: index}] = entry + utxoSet.utxoCollection[domainmessage.Outpoint{TxID: txID, Index: index}] = entry } return utxoSet, nil @@ -120,7 +120,7 @@ func newTestDAG(params *dagconfig.Params) *BlockDAG { // provided fields populated and fake values for the other fields. func newTestNode(dag *BlockDAG, parents blockSet, blockVersion int32, bits uint32, timestamp mstime.Time) *blockNode { // Make up a header and create a block node from it. - header := &wire.BlockHeader{ + header := &domainmessage.BlockHeader{ Version: blockVersion, ParentHashes: parents.hashes(), Bits: bits, @@ -168,7 +168,7 @@ func checkRuleError(gotErr, wantErr error) error { return nil } -func prepareAndProcessBlockByParentMsgBlocks(t *testing.T, dag *BlockDAG, parents ...*wire.MsgBlock) *wire.MsgBlock { +func prepareAndProcessBlockByParentMsgBlocks(t *testing.T, dag *BlockDAG, parents ...*domainmessage.MsgBlock) *domainmessage.MsgBlock { parentHashes := make([]*daghash.Hash, len(parents)) for i, parent := range parents { parentHashes[i] = parent.BlockHash() @@ -176,7 +176,7 @@ func prepareAndProcessBlockByParentMsgBlocks(t *testing.T, dag *BlockDAG, parent return PrepareAndProcessBlockForTest(t, dag, parentHashes, nil) } -func nodeByMsgBlock(t *testing.T, dag *BlockDAG, block *wire.MsgBlock) *blockNode { +func nodeByMsgBlock(t *testing.T, dag *BlockDAG, block *domainmessage.MsgBlock) *blockNode { node, ok := dag.index.LookupNode(block.BlockHash()) if !ok { t.Fatalf("couldn't find block node with hash %s", block.BlockHash()) diff --git a/blockdag/dag.go b/blockdag/dag.go index 5a9430db5..9a2af8ae4 100644 --- a/blockdag/dag.go +++ b/blockdag/dag.go @@ -21,10 +21,10 @@ import ( "github.com/kaspanet/go-secp256k1" "github.com/kaspanet/kaspad/dagconfig" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/txscript" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) const ( @@ -513,14 +513,14 @@ func (dag *BlockDAG) calcSequenceLock(node *blockNode, utxoSet UTXOSet, tx *util // mask in order to obtain the time lock delta required before // this input can be spent. sequenceNum := txIn.Sequence - relativeLock := int64(sequenceNum & wire.SequenceLockTimeMask) + relativeLock := int64(sequenceNum & domainmessage.SequenceLockTimeMask) switch { // Relative time locks are disabled for this input, so we can // skip any further calculation. - case sequenceNum&wire.SequenceLockTimeDisabled == wire.SequenceLockTimeDisabled: + case sequenceNum&domainmessage.SequenceLockTimeDisabled == domainmessage.SequenceLockTimeDisabled: continue - case sequenceNum&wire.SequenceLockTimeIsSeconds == wire.SequenceLockTimeIsSeconds: + case sequenceNum&domainmessage.SequenceLockTimeIsSeconds == domainmessage.SequenceLockTimeIsSeconds: // This input requires a relative time lock expressed // in seconds before it can be spent. Therefore, we // need to query for the block prior to the one in @@ -534,11 +534,11 @@ func (dag *BlockDAG) calcSequenceLock(node *blockNode, utxoSet UTXOSet, tx *util medianTime := blockNode.PastMedianTime(dag) // Time based relative time-locks have a time granularity of - // wire.SequenceLockTimeGranularity, so we shift left by this + // domainmessage.SequenceLockTimeGranularity, so we shift left by this // amount to convert to the proper relative time-lock. We also // subtract one from the relative lock to maintain the original // lockTime semantics. - timeLockMilliseconds := (relativeLock << wire.SequenceLockTimeGranularity) - 1 + timeLockMilliseconds := (relativeLock << domainmessage.SequenceLockTimeGranularity) - 1 timeLock := medianTime.UnixMilliseconds() + timeLockMilliseconds if timeLock > sequenceLock.Milliseconds { sequenceLock.Milliseconds = timeLock @@ -572,8 +572,8 @@ func LockTimeToSequence(isMilliseconds bool, locktime uint64) uint64 { // shift the locktime over by 19 since the time granularity is in // 524288-millisecond intervals (2^19). This results in a max lock-time of // 34,359,214,080 seconds, or 1.1 years. - return wire.SequenceLockTimeIsSeconds | - locktime>>wire.SequenceLockTimeGranularity + return domainmessage.SequenceLockTimeIsSeconds | + locktime>>domainmessage.SequenceLockTimeGranularity } // addBlock handles adding the passed block to the DAG. @@ -755,7 +755,7 @@ func (node *blockNode) selectedParentMultiset(dag *BlockDAG) (*secp256k1.MultiSe return ms, nil } -func addTxToMultiset(ms *secp256k1.MultiSet, tx *wire.MsgTx, pastUTXO UTXOSet, blockBlueScore uint64) (*secp256k1.MultiSet, error) { +func addTxToMultiset(ms *secp256k1.MultiSet, tx *domainmessage.MsgTx, pastUTXO UTXOSet, blockBlueScore uint64) (*secp256k1.MultiSet, error) { for _, txIn := range tx.TxIn { entry, ok := pastUTXO.Get(txIn.PreviousOutpoint) if !ok { @@ -771,7 +771,7 @@ func addTxToMultiset(ms *secp256k1.MultiSet, tx *wire.MsgTx, pastUTXO UTXOSet, b isCoinbase := tx.IsCoinBase() for i, txOut := range tx.TxOut { - outpoint := *wire.NewOutpoint(tx.TxID(), uint32(i)) + outpoint := *domainmessage.NewOutpoint(tx.TxID(), uint32(i)) entry := NewUTXOEntry(txOut, isCoinbase, blockBlueScore) var err error @@ -1485,7 +1485,7 @@ func (dag *BlockDAG) selectedTip() *blockNode { // It will return nil if there is no tip. // // This function is safe for concurrent access. -func (dag *BlockDAG) SelectedTipHeader() *wire.BlockHeader { +func (dag *BlockDAG) SelectedTipHeader() *domainmessage.BlockHeader { selectedTip := dag.selectedTip() if selectedTip == nil { return nil @@ -1522,7 +1522,7 @@ func (dag *BlockDAG) CalcPastMedianTime() mstime.Time { // // This function is safe for concurrent access. However, the returned entry (if // any) is NOT. -func (dag *BlockDAG) GetUTXOEntry(outpoint wire.Outpoint) (*UTXOEntry, bool) { +func (dag *BlockDAG) GetUTXOEntry(outpoint domainmessage.Outpoint) (*UTXOEntry, bool) { return dag.virtual.utxoSet.get(outpoint) } @@ -1582,7 +1582,7 @@ func (dag *BlockDAG) BlockConfirmationsByHashNoLock(hash *daghash.Hash) (uint64, // in the DAG's UTXO set. // // This function is safe for concurrent access. -func (dag *BlockDAG) UTXOConfirmations(outpoint *wire.Outpoint) (uint64, bool) { +func (dag *BlockDAG) UTXOConfirmations(outpoint *domainmessage.Outpoint) (uint64, bool) { dag.dagLock.RLock() defer dag.dagLock.RUnlock() @@ -1784,11 +1784,11 @@ func (dag *BlockDAG) CurrentBits() uint32 { // HeaderByHash returns the block header identified by the given hash or an // error if it doesn't exist. -func (dag *BlockDAG) HeaderByHash(hash *daghash.Hash) (*wire.BlockHeader, error) { +func (dag *BlockDAG) HeaderByHash(hash *daghash.Hash) (*domainmessage.BlockHeader, error) { node, ok := dag.index.LookupNode(hash) if !ok { err := errors.Errorf("block %s is not known", hash) - return &wire.BlockHeader{}, err + return &domainmessage.BlockHeader{}, err } return node.Header(), nil @@ -1937,20 +1937,20 @@ func (dag *BlockDAG) AntiPastHashesBetween(lowHash, highHash *daghash.Hash, maxH // max number of block headers. // // This function MUST be called with the DAG state lock held (for reads). -func (dag *BlockDAG) antiPastHeadersBetween(lowHash, highHash *daghash.Hash, maxHeaders uint64) ([]*wire.BlockHeader, error) { +func (dag *BlockDAG) antiPastHeadersBetween(lowHash, highHash *daghash.Hash, maxHeaders uint64) ([]*domainmessage.BlockHeader, error) { nodes, err := dag.antiPastBetween(lowHash, highHash, maxHeaders) if err != nil { return nil, err } - headers := make([]*wire.BlockHeader, len(nodes)) + headers := make([]*domainmessage.BlockHeader, len(nodes)) for i, node := range nodes { headers[i] = node.Header() } return headers, nil } -// GetTopHeaders returns the top wire.MaxBlockHeadersPerMsg block headers ordered by blue score. -func (dag *BlockDAG) GetTopHeaders(highHash *daghash.Hash, maxHeaders uint64) ([]*wire.BlockHeader, error) { +// GetTopHeaders returns the top domainmessage.MaxBlockHeadersPerMsg block headers ordered by blue score. +func (dag *BlockDAG) GetTopHeaders(highHash *daghash.Hash, maxHeaders uint64) ([]*domainmessage.BlockHeader, error) { highNode := &dag.virtual.blockNode if highHash != nil { var ok bool @@ -1959,7 +1959,7 @@ func (dag *BlockDAG) GetTopHeaders(highHash *daghash.Hash, maxHeaders uint64) ([ return nil, errors.Errorf("Couldn't find the high hash %s in the dag", highHash) } } - headers := make([]*wire.BlockHeader, 0, highNode.blueScore) + headers := make([]*domainmessage.BlockHeader, 0, highNode.blueScore) queue := newDownHeap() queue.pushSet(highNode.parents) @@ -1997,10 +1997,10 @@ func (dag *BlockDAG) RUnlock() { // AntiPastHeadersBetween returns the headers of the blocks between the // lowHash's antiPast and highHash's antiPast, or up to -// wire.MaxBlockHeadersPerMsg block headers. +// domainmessage.MaxBlockHeadersPerMsg block headers. // // This function is safe for concurrent access. -func (dag *BlockDAG) AntiPastHeadersBetween(lowHash, highHash *daghash.Hash, maxHeaders uint64) ([]*wire.BlockHeader, error) { +func (dag *BlockDAG) AntiPastHeadersBetween(lowHash, highHash *daghash.Hash, maxHeaders uint64) ([]*domainmessage.BlockHeader, error) { dag.dagLock.RLock() defer dag.dagLock.RUnlock() headers, err := dag.antiPastHeadersBetween(lowHash, highHash, maxHeaders) diff --git a/blockdag/dag_test.go b/blockdag/dag_test.go index dbb9ac4d1..2e2c76e8c 100644 --- a/blockdag/dag_test.go +++ b/blockdag/dag_test.go @@ -18,11 +18,11 @@ import ( "github.com/pkg/errors" "github.com/kaspanet/kaspad/dagconfig" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/txscript" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/subnetworkid" - "github.com/kaspanet/kaspad/wire" ) func TestBlockCount(t *testing.T) { @@ -255,7 +255,7 @@ func TestCalcSequenceLock(t *testing.T) { // Create a utxo view with a fake utxo for the inputs used in the // transactions created below. This utxo is added such that it has an // age of 4 blocks. - msgTx := wire.NewNativeMsgTx(wire.TxVersion, nil, []*wire.TxOut{{ScriptPubKey: nil, Value: 10}}) + msgTx := domainmessage.NewNativeMsgTx(domainmessage.TxVersion, nil, []*domainmessage.TxOut{{ScriptPubKey: nil, Value: 10}}) targetTx := util.NewTx(msgTx) utxoSet := NewFullUTXOSet() blueScore := uint64(numBlocksToGenerate) - 4 @@ -270,7 +270,7 @@ func TestCalcSequenceLock(t *testing.T) { // that the sequence lock heights are always calculated from the same // point of view that they were originally calculated from for a given // utxo. That is to say, the height prior to it. - utxo := wire.Outpoint{ + utxo := domainmessage.Outpoint{ TxID: *targetTx.ID(), Index: 0, } @@ -290,8 +290,8 @@ func TestCalcSequenceLock(t *testing.T) { // Add an additional transaction which will serve as our unconfirmed // output. - unConfTx := wire.NewNativeMsgTx(wire.TxVersion, nil, []*wire.TxOut{{ScriptPubKey: nil, Value: 5}}) - unConfUtxo := wire.Outpoint{ + unConfTx := domainmessage.NewNativeMsgTx(domainmessage.TxVersion, nil, []*domainmessage.TxOut{{ScriptPubKey: nil, Value: 5}}) + unConfUtxo := domainmessage.Outpoint{ TxID: *unConfTx.TxID(), Index: 0, } @@ -303,7 +303,7 @@ func TestCalcSequenceLock(t *testing.T) { tests := []struct { name string - tx *wire.MsgTx + tx *domainmessage.MsgTx utxoSet UTXOSet mempool bool want *SequenceLock @@ -313,7 +313,7 @@ func TestCalcSequenceLock(t *testing.T) { // should be disabled. { name: "single input, max sequence number", - tx: wire.NewNativeMsgTx(1, []*wire.TxIn{{PreviousOutpoint: utxo, Sequence: wire.MaxTxInSequenceNum}}, nil), + tx: domainmessage.NewNativeMsgTx(1, []*domainmessage.TxIn{{PreviousOutpoint: utxo, Sequence: domainmessage.MaxTxInSequenceNum}}, nil), utxoSet: utxoSet, want: &SequenceLock{ Milliseconds: -1, @@ -328,7 +328,7 @@ func TestCalcSequenceLock(t *testing.T) { // the targeted block. { name: "single input, milliseconds lock time below time granularity", - tx: wire.NewNativeMsgTx(1, []*wire.TxIn{{PreviousOutpoint: utxo, Sequence: LockTimeToSequence(true, 2)}}, nil), + tx: domainmessage.NewNativeMsgTx(1, []*domainmessage.TxIn{{PreviousOutpoint: utxo, Sequence: LockTimeToSequence(true, 2)}}, nil), utxoSet: utxoSet, want: &SequenceLock{ Milliseconds: medianTime - 1, @@ -340,7 +340,7 @@ func TestCalcSequenceLock(t *testing.T) { // milliseconds after the median past time of the DAG. { name: "single input, 1048575 milliseconds after median time", - tx: wire.NewNativeMsgTx(1, []*wire.TxIn{{PreviousOutpoint: utxo, Sequence: LockTimeToSequence(true, 1048576)}}, nil), + tx: domainmessage.NewNativeMsgTx(1, []*domainmessage.TxIn{{PreviousOutpoint: utxo, Sequence: LockTimeToSequence(true, 1048576)}}, nil), utxoSet: utxoSet, want: &SequenceLock{ Milliseconds: medianTime + 1048575, @@ -355,8 +355,8 @@ func TestCalcSequenceLock(t *testing.T) { // latest lock that isn't disabled. { name: "multiple varied inputs", - tx: wire.NewNativeMsgTx(1, - []*wire.TxIn{{ + tx: domainmessage.NewNativeMsgTx(1, + []*domainmessage.TxIn{{ PreviousOutpoint: utxo, Sequence: LockTimeToSequence(true, 2621440), }, { @@ -365,12 +365,12 @@ func TestCalcSequenceLock(t *testing.T) { }, { PreviousOutpoint: utxo, Sequence: LockTimeToSequence(false, 5) | - wire.SequenceLockTimeDisabled, + domainmessage.SequenceLockTimeDisabled, }}, nil), utxoSet: utxoSet, want: &SequenceLock{ - Milliseconds: medianTime + (5 << wire.SequenceLockTimeGranularity) - 1, + Milliseconds: medianTime + (5 << domainmessage.SequenceLockTimeGranularity) - 1, BlockBlueScore: int64(prevUtxoBlueScore) + 3, }, }, @@ -380,7 +380,7 @@ func TestCalcSequenceLock(t *testing.T) { // height of 2 meaning it can be included at height 3. { name: "single input, lock-time in blocks", - tx: wire.NewNativeMsgTx(1, []*wire.TxIn{{PreviousOutpoint: utxo, Sequence: LockTimeToSequence(false, 3)}}, nil), + tx: domainmessage.NewNativeMsgTx(1, []*domainmessage.TxIn{{PreviousOutpoint: utxo, Sequence: LockTimeToSequence(false, 3)}}, nil), utxoSet: utxoSet, want: &SequenceLock{ Milliseconds: -1, @@ -392,7 +392,7 @@ func TestCalcSequenceLock(t *testing.T) { // be the time further in the future. { name: "two inputs, lock-times in seconds", - tx: wire.NewNativeMsgTx(1, []*wire.TxIn{{ + tx: domainmessage.NewNativeMsgTx(1, []*domainmessage.TxIn{{ PreviousOutpoint: utxo, Sequence: LockTimeToSequence(true, 5242880), }, { @@ -401,7 +401,7 @@ func TestCalcSequenceLock(t *testing.T) { }}, nil), utxoSet: utxoSet, want: &SequenceLock{ - Milliseconds: medianTime + (10 << wire.SequenceLockTimeGranularity) - 1, + Milliseconds: medianTime + (10 << domainmessage.SequenceLockTimeGranularity) - 1, BlockBlueScore: -1, }, }, @@ -411,8 +411,8 @@ func TestCalcSequenceLock(t *testing.T) { // indicating it can be included at height 11. { name: "two inputs, lock-times in blocks", - tx: wire.NewNativeMsgTx(1, - []*wire.TxIn{{ + tx: domainmessage.NewNativeMsgTx(1, + []*domainmessage.TxIn{{ PreviousOutpoint: utxo, Sequence: LockTimeToSequence(false, 1), }, { @@ -431,8 +431,8 @@ func TestCalcSequenceLock(t *testing.T) { // further into the future for both inputs should be chosen. { name: "four inputs, two lock-times in time, two lock-times in blocks", - tx: wire.NewNativeMsgTx(1, - []*wire.TxIn{{ + tx: domainmessage.NewNativeMsgTx(1, + []*domainmessage.TxIn{{ PreviousOutpoint: utxo, Sequence: LockTimeToSequence(true, 2621440), }, { @@ -448,7 +448,7 @@ func TestCalcSequenceLock(t *testing.T) { nil), utxoSet: utxoSet, want: &SequenceLock{ - Milliseconds: medianTime + (13 << wire.SequenceLockTimeGranularity) - 1, + Milliseconds: medianTime + (13 << domainmessage.SequenceLockTimeGranularity) - 1, BlockBlueScore: int64(prevUtxoBlueScore) + 8, }, }, @@ -460,7 +460,7 @@ func TestCalcSequenceLock(t *testing.T) { // after that. { name: "single input, unconfirmed, lock-time in blocks", - tx: wire.NewNativeMsgTx(1, []*wire.TxIn{{PreviousOutpoint: unConfUtxo, Sequence: LockTimeToSequence(false, 2)}}, nil), + tx: domainmessage.NewNativeMsgTx(1, []*domainmessage.TxIn{{PreviousOutpoint: unConfUtxo, Sequence: LockTimeToSequence(false, 2)}}, nil), utxoSet: utxoSet, mempool: true, want: &SequenceLock{ @@ -473,7 +473,7 @@ func TestCalcSequenceLock(t *testing.T) { // MTP of the *next* block. { name: "single input, unconfirmed, lock-time in milliseoncds", - tx: wire.NewNativeMsgTx(1, []*wire.TxIn{{PreviousOutpoint: unConfUtxo, Sequence: LockTimeToSequence(true, 1048576)}}, nil), + tx: domainmessage.NewNativeMsgTx(1, []*domainmessage.TxIn{{PreviousOutpoint: unConfUtxo, Sequence: LockTimeToSequence(true, 1048576)}}, nil), utxoSet: utxoSet, mempool: true, want: &SequenceLock{ @@ -701,7 +701,7 @@ func TestConfirmations(t *testing.T) { } // Add a chain of blocks - chainBlocks := make([]*wire.MsgBlock, 5) + chainBlocks := make([]*domainmessage.MsgBlock, 5) chainBlocks[0] = dag.Params.GenesisBlock for i := uint32(1); i < 5; i++ { chainBlocks[i] = prepareAndProcessBlockByParentMsgBlocks(t, dag, chainBlocks[i-1]) @@ -721,7 +721,7 @@ func TestConfirmations(t *testing.T) { } } - branchingBlocks := make([]*wire.MsgBlock, 2) + branchingBlocks := make([]*domainmessage.MsgBlock, 2) // Add two branching blocks branchingBlocks[0] = prepareAndProcessBlockByParentMsgBlocks(t, dag, chainBlocks[1]) branchingBlocks[1] = prepareAndProcessBlockByParentMsgBlocks(t, dag, branchingBlocks[0]) @@ -794,7 +794,7 @@ func TestAcceptingBlock(t *testing.T) { defer teardownFunc() dag.TestSetCoinbaseMaturity(0) - acceptingBlockByMsgBlock := func(block *wire.MsgBlock) (*blockNode, error) { + acceptingBlockByMsgBlock := func(block *domainmessage.MsgBlock) (*blockNode, error) { node := nodeByMsgBlock(t, dag, block) return dag.acceptingBlock(node) } @@ -810,7 +810,7 @@ func TestAcceptingBlock(t *testing.T) { } numChainBlocks := uint32(10) - chainBlocks := make([]*wire.MsgBlock, numChainBlocks) + chainBlocks := make([]*domainmessage.MsgBlock, numChainBlocks) chainBlocks[0] = dag.Params.GenesisBlock for i := uint32(1); i <= numChainBlocks-1; i++ { chainBlocks[i] = prepareAndProcessBlockByParentMsgBlocks(t, dag, chainBlocks[i-1]) @@ -1030,11 +1030,11 @@ func TestDAGIndexFailedStatus(t *testing.T) { } defer teardownFunc() - invalidCbTx := wire.NewSubnetworkMsgTx(wire.TxVersion, []*wire.TxIn{}, []*wire.TxOut{}, subnetworkid.SubnetworkIDCoinbase, 0, []byte{}) + invalidCbTx := domainmessage.NewSubnetworkMsgTx(domainmessage.TxVersion, []*domainmessage.TxIn{}, []*domainmessage.TxOut{}, subnetworkid.SubnetworkIDCoinbase, 0, []byte{}) txs := []*util.Tx{util.NewTx(invalidCbTx)} hashMerkleRoot := BuildHashMerkleTreeStore(txs).Root() - invalidMsgBlock := wire.NewMsgBlock( - wire.NewBlockHeader( + invalidMsgBlock := domainmessage.NewMsgBlock( + domainmessage.NewBlockHeader( 1, []*daghash.Hash{params.GenesisHash}, hashMerkleRoot, &daghash.Hash{}, @@ -1066,8 +1066,8 @@ func TestDAGIndexFailedStatus(t *testing.T) { t.Fatalf("invalidBlockNode status to have %b flags raised (got: %b)", statusValidateFailed, invalidBlockNode.status) } - invalidMsgBlockChild := wire.NewMsgBlock( - wire.NewBlockHeader(1, []*daghash.Hash{ + invalidMsgBlockChild := domainmessage.NewMsgBlock( + domainmessage.NewBlockHeader(1, []*daghash.Hash{ invalidBlock.Hash(), }, hashMerkleRoot, &daghash.Hash{}, &daghash.Hash{}, dag.genesis.bits, 0), ) @@ -1095,8 +1095,8 @@ func TestDAGIndexFailedStatus(t *testing.T) { t.Fatalf("invalidBlockNode status to have %b flags raised (got %b)", statusInvalidAncestor, invalidBlockChildNode.status) } - invalidMsgBlockGrandChild := wire.NewMsgBlock( - wire.NewBlockHeader(1, []*daghash.Hash{ + invalidMsgBlockGrandChild := domainmessage.NewMsgBlock( + domainmessage.NewBlockHeader(1, []*daghash.Hash{ invalidBlockChild.Hash(), }, hashMerkleRoot, &daghash.Hash{}, &daghash.Hash{}, dag.genesis.bits, 0), ) @@ -1139,7 +1139,7 @@ func TestIsDAGCurrentMaxDiff(t *testing.T) { } } -func testProcessBlockRuleError(t *testing.T, dag *BlockDAG, block *wire.MsgBlock, expectedRuleErr error) { +func testProcessBlockRuleError(t *testing.T, dag *BlockDAG, block *domainmessage.MsgBlock, expectedRuleErr error) { isOrphan, isDelayed, err := dag.ProcessBlock(util.NewBlock(block), BFNoPoWCheck) err = checkRuleError(err, expectedRuleErr) @@ -1175,24 +1175,24 @@ func TestDoubleSpends(t *testing.T) { if err != nil { t.Fatalf("Failed to build signature script: %s", err) } - txIn := &wire.TxIn{ - PreviousOutpoint: wire.Outpoint{TxID: *cbTx.TxID(), Index: 0}, + txIn := &domainmessage.TxIn{ + PreviousOutpoint: domainmessage.Outpoint{TxID: *cbTx.TxID(), Index: 0}, SignatureScript: signatureScript, - Sequence: wire.MaxTxInSequenceNum, + Sequence: domainmessage.MaxTxInSequenceNum, } - txOut := &wire.TxOut{ + txOut := &domainmessage.TxOut{ ScriptPubKey: OpTrueScript, Value: uint64(1), } - tx1 := wire.NewNativeMsgTx(wire.TxVersion, []*wire.TxIn{txIn}, []*wire.TxOut{txOut}) + tx1 := domainmessage.NewNativeMsgTx(domainmessage.TxVersion, []*domainmessage.TxIn{txIn}, []*domainmessage.TxOut{txOut}) - doubleSpendTxOut := &wire.TxOut{ + doubleSpendTxOut := &domainmessage.TxOut{ ScriptPubKey: OpTrueScript, Value: uint64(2), } - doubleSpendTx1 := wire.NewNativeMsgTx(wire.TxVersion, []*wire.TxIn{txIn}, []*wire.TxOut{doubleSpendTxOut}) + doubleSpendTx1 := domainmessage.NewNativeMsgTx(domainmessage.TxVersion, []*domainmessage.TxIn{txIn}, []*domainmessage.TxOut{doubleSpendTxOut}) - blockWithTx1 := PrepareAndProcessBlockForTest(t, dag, []*daghash.Hash{fundingBlock.BlockHash()}, []*wire.MsgTx{tx1}) + blockWithTx1 := PrepareAndProcessBlockForTest(t, dag, []*daghash.Hash{fundingBlock.BlockHash()}, []*domainmessage.MsgTx{tx1}) // Check that a block will be rejected if it has a transaction that already exists in its past. anotherBlockWithTx1, err := PrepareBlockForTest(dag, []*daghash.Hash{blockWithTx1.BlockHash()}, nil) @@ -1227,7 +1227,7 @@ func TestDoubleSpends(t *testing.T) { testProcessBlockRuleError(t, dag, blockWithDoubleSpendForTx1, ruleError(ErrMissingTxOut, "")) - blockInAnticoneOfBlockWithTx1, err := PrepareBlockForTest(dag, []*daghash.Hash{fundingBlock.BlockHash()}, []*wire.MsgTx{doubleSpendTx1}) + blockInAnticoneOfBlockWithTx1, err := PrepareBlockForTest(dag, []*daghash.Hash{fundingBlock.BlockHash()}, []*domainmessage.MsgTx{doubleSpendTx1}) if err != nil { t.Fatalf("PrepareBlockForTest: %v", err) } @@ -1282,7 +1282,7 @@ func TestUTXOCommitment(t *testing.T) { resetExtraNonceForTest() - createTx := func(txToSpend *wire.MsgTx) *wire.MsgTx { + createTx := func(txToSpend *domainmessage.MsgTx) *domainmessage.MsgTx { scriptPubKey, err := txscript.PayToScriptHashScript(OpTrueScript) if err != nil { t.Fatalf("TestUTXOCommitment: failed to build script pub key: %s", err) @@ -1291,16 +1291,16 @@ func TestUTXOCommitment(t *testing.T) { if err != nil { t.Fatalf("TestUTXOCommitment: failed to build signature script: %s", err) } - txIn := &wire.TxIn{ - PreviousOutpoint: wire.Outpoint{TxID: *txToSpend.TxID(), Index: 0}, + txIn := &domainmessage.TxIn{ + PreviousOutpoint: domainmessage.Outpoint{TxID: *txToSpend.TxID(), Index: 0}, SignatureScript: signatureScript, - Sequence: wire.MaxTxInSequenceNum, + Sequence: domainmessage.MaxTxInSequenceNum, } - txOut := &wire.TxOut{ + txOut := &domainmessage.TxOut{ ScriptPubKey: scriptPubKey, Value: uint64(1), } - return wire.NewNativeMsgTx(wire.TxVersion, []*wire.TxIn{txIn}, []*wire.TxOut{txOut}) + return domainmessage.NewNativeMsgTx(domainmessage.TxVersion, []*domainmessage.TxIn{txIn}, []*domainmessage.TxOut{txOut}) } // Build the following DAG: @@ -1316,12 +1316,12 @@ func TestUTXOCommitment(t *testing.T) { // Block C: txSpendBlockACoinbase := createTx(blockA.Transactions[0]) - blockCTxs := []*wire.MsgTx{txSpendBlockACoinbase} + blockCTxs := []*domainmessage.MsgTx{txSpendBlockACoinbase} blockC := PrepareAndProcessBlockForTest(t, dag, []*daghash.Hash{blockA.BlockHash()}, blockCTxs) // Block D: txSpendTxInBlockC := createTx(txSpendBlockACoinbase) - blockDTxs := []*wire.MsgTx{txSpendTxInBlockC} + blockDTxs := []*domainmessage.MsgTx{txSpendTxInBlockC} blockD := PrepareAndProcessBlockForTest(t, dag, []*daghash.Hash{blockB.BlockHash(), blockC.BlockHash()}, blockDTxs) // Get the pastUTXO of blockD diff --git a/blockdag/dagio.go b/blockdag/dagio.go index 391904e05..9825a3c5c 100644 --- a/blockdag/dagio.go +++ b/blockdag/dagio.go @@ -15,11 +15,11 @@ import ( "github.com/kaspanet/kaspad/dbaccess" "github.com/pkg/errors" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/binaryserializer" "github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/subnetworkid" - "github.com/kaspanet/kaspad/wire" ) var ( @@ -49,7 +49,7 @@ func IsNotInDAGErr(err error) bool { // keys will be iterated in an ascending order by the outpoint index. var outpointIndexByteOrder = binary.BigEndian -func serializeOutpoint(w io.Writer, outpoint *wire.Outpoint) error { +func serializeOutpoint(w io.Writer, outpoint *domainmessage.Outpoint) error { _, err := w.Write(outpoint.TxID[:]) if err != nil { return err @@ -61,10 +61,10 @@ func serializeOutpoint(w io.Writer, outpoint *wire.Outpoint) error { var outpointSerializeSize = daghash.TxIDSize + 4 // deserializeOutpoint decodes an outpoint from the passed serialized byte -// slice into a new wire.Outpoint using a format that is suitable for long- +// slice into a new domainmessage.Outpoint using a format that is suitable for long- // term storage. This format is described in detail above. -func deserializeOutpoint(r io.Reader) (*wire.Outpoint, error) { - outpoint := &wire.Outpoint{} +func deserializeOutpoint(r io.Reader) (*domainmessage.Outpoint, error) { + outpoint := &domainmessage.Outpoint{} _, err := r.Read(outpoint.TxID[:]) if err != nil { return nil, err @@ -410,7 +410,7 @@ func (dag *BlockDAG) processUnprocessedBlockNodes(unprocessedBlockNodes []*block func (dag *BlockDAG) deserializeBlockNode(blockRow []byte) (*blockNode, error) { buffer := bytes.NewReader(blockRow) - var header wire.BlockHeader + var header domainmessage.BlockHeader err := header.Deserialize(buffer) if err != nil { return nil, err @@ -464,7 +464,7 @@ func (dag *BlockDAG) deserializeBlockNode(blockRow []byte) (*blockNode, error) { return nil, err } - bluesCount, err := wire.ReadVarInt(buffer) + bluesCount, err := domainmessage.ReadVarInt(buffer) if err != nil { return nil, err } @@ -483,7 +483,7 @@ func (dag *BlockDAG) deserializeBlockNode(blockRow []byte) (*blockNode, error) { } } - bluesAnticoneSizesLen, err := wire.ReadVarInt(buffer) + bluesAnticoneSizesLen, err := domainmessage.ReadVarInt(buffer) if err != nil { return nil, err } @@ -527,7 +527,7 @@ func storeBlock(dbContext *dbaccess.TxContext, block *util.Block) error { } func serializeBlockNode(node *blockNode) ([]byte, error) { - w := bytes.NewBuffer(make([]byte, 0, wire.MaxBlockHeaderPayload+1)) + w := bytes.NewBuffer(make([]byte, 0, domainmessage.MaxBlockHeaderPayload+1)) header := node.Header() err := header.Serialize(w) if err != nil { @@ -554,7 +554,7 @@ func serializeBlockNode(node *blockNode) ([]byte, error) { return nil, err } - err = wire.WriteVarInt(w, uint64(len(node.blues))) + err = domainmessage.WriteVarInt(w, uint64(len(node.blues))) if err != nil { return nil, err } @@ -566,7 +566,7 @@ func serializeBlockNode(node *blockNode) ([]byte, error) { } } - err = wire.WriteVarInt(w, uint64(len(node.bluesAnticoneSizes))) + err = domainmessage.WriteVarInt(w, uint64(len(node.bluesAnticoneSizes))) if err != nil { return nil, err } diff --git a/blockdag/external_dag_test.go b/blockdag/external_dag_test.go index 8f4eb65c5..311075691 100644 --- a/blockdag/external_dag_test.go +++ b/blockdag/external_dag_test.go @@ -15,10 +15,10 @@ import ( "github.com/kaspanet/kaspad/blockdag" "github.com/kaspanet/kaspad/dagconfig" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/mining" "github.com/kaspanet/kaspad/txscript" "github.com/kaspanet/kaspad/util" - "github.com/kaspanet/kaspad/wire" ) // TestFinality checks that the finality mechanism works as expected. @@ -125,7 +125,7 @@ func TestFinality(t *testing.T) { t.Errorf("NextBlockCoinbaseTransaction: %s", err) } merkleRoot := blockdag.BuildHashMerkleTreeStore([]*util.Tx{fakeCoinbaseTx}).Root() - beforeFinalityBlock := wire.NewMsgBlock(&wire.BlockHeader{ + beforeFinalityBlock := domainmessage.NewMsgBlock(&domainmessage.BlockHeader{ Version: 0x10000000, ParentHashes: []*daghash.Hash{genesis.Hash()}, HashMerkleRoot: merkleRoot, @@ -164,7 +164,7 @@ func TestFinality(t *testing.T) { } // TestFinalityInterval tests that the finality interval is -// smaller then wire.MaxInvPerMsg, so when a peer receives +// smaller then domainmessage.MaxInvPerMsg, so when a peer receives // a getblocks message it should always be able to send // all the necessary invs. func TestFinalityInterval(t *testing.T) { @@ -185,8 +185,8 @@ func TestFinalityInterval(t *testing.T) { } defer teardownFunc() - if dag.FinalityInterval() > wire.MaxInvPerMsg { - t.Errorf("FinalityInterval in %s should be lower or equal to wire.MaxInvPerMsg", params.Name) + if dag.FinalityInterval() > domainmessage.MaxInvPerMsg { + t.Errorf("FinalityInterval in %s should be lower or equal to domainmessage.MaxInvPerMsg", params.Name) } }() } @@ -253,34 +253,34 @@ func TestChainedTransactions(t *testing.T) { if err != nil { t.Fatalf("Failed to build signature script: %s", err) } - txIn := &wire.TxIn{ - PreviousOutpoint: wire.Outpoint{TxID: *cbTx.TxID(), Index: 0}, + txIn := &domainmessage.TxIn{ + PreviousOutpoint: domainmessage.Outpoint{TxID: *cbTx.TxID(), Index: 0}, SignatureScript: signatureScript, - Sequence: wire.MaxTxInSequenceNum, + Sequence: domainmessage.MaxTxInSequenceNum, } - txOut := &wire.TxOut{ + txOut := &domainmessage.TxOut{ ScriptPubKey: blockdag.OpTrueScript, Value: uint64(1), } - tx := wire.NewNativeMsgTx(wire.TxVersion, []*wire.TxIn{txIn}, []*wire.TxOut{txOut}) + tx := domainmessage.NewNativeMsgTx(domainmessage.TxVersion, []*domainmessage.TxIn{txIn}, []*domainmessage.TxOut{txOut}) - chainedTxIn := &wire.TxIn{ - PreviousOutpoint: wire.Outpoint{TxID: *tx.TxID(), Index: 0}, + chainedTxIn := &domainmessage.TxIn{ + PreviousOutpoint: domainmessage.Outpoint{TxID: *tx.TxID(), Index: 0}, SignatureScript: signatureScript, - Sequence: wire.MaxTxInSequenceNum, + Sequence: domainmessage.MaxTxInSequenceNum, } scriptPubKey, err := txscript.PayToScriptHashScript(blockdag.OpTrueScript) if err != nil { t.Fatalf("Failed to build public key script: %s", err) } - chainedTxOut := &wire.TxOut{ + chainedTxOut := &domainmessage.TxOut{ ScriptPubKey: scriptPubKey, Value: uint64(1), } - chainedTx := wire.NewNativeMsgTx(wire.TxVersion, []*wire.TxIn{chainedTxIn}, []*wire.TxOut{chainedTxOut}) + chainedTx := domainmessage.NewNativeMsgTx(domainmessage.TxVersion, []*domainmessage.TxIn{chainedTxIn}, []*domainmessage.TxOut{chainedTxOut}) - block2, err := mining.PrepareBlockForTest(dag, []*daghash.Hash{block1.BlockHash()}, []*wire.MsgTx{tx}, false) + block2, err := mining.PrepareBlockForTest(dag, []*daghash.Hash{block1.BlockHash()}, []*domainmessage.MsgTx{tx}, false) if err != nil { t.Fatalf("PrepareBlockForTest: %v", err) } @@ -315,18 +315,18 @@ func TestChainedTransactions(t *testing.T) { t.Errorf("ProcessBlock: block2 got unexpectedly orphaned") } - nonChainedTxIn := &wire.TxIn{ - PreviousOutpoint: wire.Outpoint{TxID: *cbTx.TxID(), Index: 0}, + nonChainedTxIn := &domainmessage.TxIn{ + PreviousOutpoint: domainmessage.Outpoint{TxID: *cbTx.TxID(), Index: 0}, SignatureScript: signatureScript, - Sequence: wire.MaxTxInSequenceNum, + Sequence: domainmessage.MaxTxInSequenceNum, } - nonChainedTxOut := &wire.TxOut{ + nonChainedTxOut := &domainmessage.TxOut{ ScriptPubKey: scriptPubKey, Value: uint64(1), } - nonChainedTx := wire.NewNativeMsgTx(wire.TxVersion, []*wire.TxIn{nonChainedTxIn}, []*wire.TxOut{nonChainedTxOut}) + nonChainedTx := domainmessage.NewNativeMsgTx(domainmessage.TxVersion, []*domainmessage.TxIn{nonChainedTxIn}, []*domainmessage.TxOut{nonChainedTxOut}) - block3, err := mining.PrepareBlockForTest(dag, []*daghash.Hash{block1.BlockHash()}, []*wire.MsgTx{nonChainedTx}, false) + block3, err := mining.PrepareBlockForTest(dag, []*daghash.Hash{block1.BlockHash()}, []*domainmessage.MsgTx{nonChainedTx}, false) if err != nil { t.Fatalf("PrepareBlockForTest: %v", err) } @@ -363,23 +363,23 @@ func TestOrderInDiffFromAcceptanceData(t *testing.T) { createBlock := func(previousBlock *util.Block) *util.Block { // Prepare a transaction that spends the previous block's coinbase transaction - var txs []*wire.MsgTx + var txs []*domainmessage.MsgTx if !previousBlock.IsGenesis() { previousCoinbaseTx := previousBlock.MsgBlock().Transactions[0] signatureScript, err := txscript.PayToScriptHashSignatureScript(blockdag.OpTrueScript, nil) if err != nil { t.Fatalf("TestOrderInDiffFromAcceptanceData: Failed to build signature script: %s", err) } - txIn := &wire.TxIn{ - PreviousOutpoint: wire.Outpoint{TxID: *previousCoinbaseTx.TxID(), Index: 0}, + txIn := &domainmessage.TxIn{ + PreviousOutpoint: domainmessage.Outpoint{TxID: *previousCoinbaseTx.TxID(), Index: 0}, SignatureScript: signatureScript, - Sequence: wire.MaxTxInSequenceNum, + Sequence: domainmessage.MaxTxInSequenceNum, } - txOut := &wire.TxOut{ + txOut := &domainmessage.TxOut{ ScriptPubKey: blockdag.OpTrueScript, Value: uint64(1), } - txs = append(txs, wire.NewNativeMsgTx(wire.TxVersion, []*wire.TxIn{txIn}, []*wire.TxOut{txOut})) + txs = append(txs, domainmessage.NewNativeMsgTx(domainmessage.TxVersion, []*domainmessage.TxIn{txIn}, []*domainmessage.TxOut{txOut})) } // Create the block @@ -438,7 +438,7 @@ func TestGasLimit(t *testing.T) { t.Fatalf("could not register network: %s", err) } - cbTxs := []*wire.MsgTx{} + cbTxs := []*domainmessage.MsgTx{} for i := 0; i < 4; i++ { fundsBlock, err := mining.PrepareBlockForTest(dag, dag.TipHashes(), nil, false) if err != nil { @@ -469,30 +469,30 @@ func TestGasLimit(t *testing.T) { t.Fatalf("Failed to build public key script: %s", err) } - tx1In := &wire.TxIn{ - PreviousOutpoint: *wire.NewOutpoint(cbTxs[0].TxID(), 0), - Sequence: wire.MaxTxInSequenceNum, + tx1In := &domainmessage.TxIn{ + PreviousOutpoint: *domainmessage.NewOutpoint(cbTxs[0].TxID(), 0), + Sequence: domainmessage.MaxTxInSequenceNum, SignatureScript: signatureScript, } - tx1Out := &wire.TxOut{ + tx1Out := &domainmessage.TxOut{ Value: cbTxs[0].TxOut[0].Value, ScriptPubKey: scriptPubKey, } - tx1 := wire.NewSubnetworkMsgTx(wire.TxVersion, []*wire.TxIn{tx1In}, []*wire.TxOut{tx1Out}, subnetworkID, 10000, []byte{}) + tx1 := domainmessage.NewSubnetworkMsgTx(domainmessage.TxVersion, []*domainmessage.TxIn{tx1In}, []*domainmessage.TxOut{tx1Out}, subnetworkID, 10000, []byte{}) - tx2In := &wire.TxIn{ - PreviousOutpoint: *wire.NewOutpoint(cbTxs[1].TxID(), 0), - Sequence: wire.MaxTxInSequenceNum, + tx2In := &domainmessage.TxIn{ + PreviousOutpoint: *domainmessage.NewOutpoint(cbTxs[1].TxID(), 0), + Sequence: domainmessage.MaxTxInSequenceNum, SignatureScript: signatureScript, } - tx2Out := &wire.TxOut{ + tx2Out := &domainmessage.TxOut{ Value: cbTxs[1].TxOut[0].Value, ScriptPubKey: scriptPubKey, } - tx2 := wire.NewSubnetworkMsgTx(wire.TxVersion, []*wire.TxIn{tx2In}, []*wire.TxOut{tx2Out}, subnetworkID, 10000, []byte{}) + tx2 := domainmessage.NewSubnetworkMsgTx(domainmessage.TxVersion, []*domainmessage.TxIn{tx2In}, []*domainmessage.TxOut{tx2Out}, subnetworkID, 10000, []byte{}) // Here we check that we can't process a block that has transactions that exceed the gas limit - overLimitBlock, err := mining.PrepareBlockForTest(dag, dag.TipHashes(), []*wire.MsgTx{tx1, tx2}, true) + overLimitBlock, err := mining.PrepareBlockForTest(dag, dag.TipHashes(), []*domainmessage.MsgTx{tx1, tx2}, true) if err != nil { t.Fatalf("PrepareBlockForTest: %v", err) } @@ -514,20 +514,20 @@ func TestGasLimit(t *testing.T) { t.Fatalf("ProcessBlock: overLimitBlock got unexpectedly orphan") } - overflowGasTxIn := &wire.TxIn{ - PreviousOutpoint: *wire.NewOutpoint(cbTxs[2].TxID(), 0), - Sequence: wire.MaxTxInSequenceNum, + overflowGasTxIn := &domainmessage.TxIn{ + PreviousOutpoint: *domainmessage.NewOutpoint(cbTxs[2].TxID(), 0), + Sequence: domainmessage.MaxTxInSequenceNum, SignatureScript: signatureScript, } - overflowGasTxOut := &wire.TxOut{ + overflowGasTxOut := &domainmessage.TxOut{ Value: cbTxs[2].TxOut[0].Value, ScriptPubKey: scriptPubKey, } - overflowGasTx := wire.NewSubnetworkMsgTx(wire.TxVersion, []*wire.TxIn{overflowGasTxIn}, []*wire.TxOut{overflowGasTxOut}, + overflowGasTx := domainmessage.NewSubnetworkMsgTx(domainmessage.TxVersion, []*domainmessage.TxIn{overflowGasTxIn}, []*domainmessage.TxOut{overflowGasTxOut}, subnetworkID, math.MaxUint64, []byte{}) // Here we check that we can't process a block that its transactions' gas overflows uint64 - overflowGasBlock, err := mining.PrepareBlockForTest(dag, dag.TipHashes(), []*wire.MsgTx{tx1, overflowGasTx}, true) + overflowGasBlock, err := mining.PrepareBlockForTest(dag, dag.TipHashes(), []*domainmessage.MsgTx{tx1, overflowGasTx}, true) if err != nil { t.Fatalf("PrepareBlockForTest: %v", err) } @@ -549,19 +549,19 @@ func TestGasLimit(t *testing.T) { } nonExistentSubnetwork := &subnetworkid.SubnetworkID{123} - nonExistentSubnetworkTxIn := &wire.TxIn{ - PreviousOutpoint: *wire.NewOutpoint(cbTxs[3].TxID(), 0), - Sequence: wire.MaxTxInSequenceNum, + nonExistentSubnetworkTxIn := &domainmessage.TxIn{ + PreviousOutpoint: *domainmessage.NewOutpoint(cbTxs[3].TxID(), 0), + Sequence: domainmessage.MaxTxInSequenceNum, SignatureScript: signatureScript, } - nonExistentSubnetworkTxOut := &wire.TxOut{ + nonExistentSubnetworkTxOut := &domainmessage.TxOut{ Value: cbTxs[3].TxOut[0].Value, ScriptPubKey: scriptPubKey, } - nonExistentSubnetworkTx := wire.NewSubnetworkMsgTx(wire.TxVersion, []*wire.TxIn{nonExistentSubnetworkTxIn}, - []*wire.TxOut{nonExistentSubnetworkTxOut}, nonExistentSubnetwork, 1, []byte{}) + nonExistentSubnetworkTx := domainmessage.NewSubnetworkMsgTx(domainmessage.TxVersion, []*domainmessage.TxIn{nonExistentSubnetworkTxIn}, + []*domainmessage.TxOut{nonExistentSubnetworkTxOut}, nonExistentSubnetwork, 1, []byte{}) - nonExistentSubnetworkBlock, err := mining.PrepareBlockForTest(dag, dag.TipHashes(), []*wire.MsgTx{nonExistentSubnetworkTx, overflowGasTx}, true) + nonExistentSubnetworkBlock, err := mining.PrepareBlockForTest(dag, dag.TipHashes(), []*domainmessage.MsgTx{nonExistentSubnetworkTx, overflowGasTx}, true) if err != nil { t.Fatalf("PrepareBlockForTest: %v", err) } @@ -582,7 +582,7 @@ func TestGasLimit(t *testing.T) { } // Here we check that we can process a block with a transaction that doesn't exceed the gas limit - validBlock, err := mining.PrepareBlockForTest(dag, dag.TipHashes(), []*wire.MsgTx{tx1}, true) + validBlock, err := mining.PrepareBlockForTest(dag, dag.TipHashes(), []*domainmessage.MsgTx{tx1}, true) if err != nil { t.Fatalf("PrepareBlockForTest: %v", err) } diff --git a/blockdag/indexers/acceptanceindex.go b/blockdag/indexers/acceptanceindex.go index 9b64b23c7..a6494add5 100644 --- a/blockdag/indexers/acceptanceindex.go +++ b/blockdag/indexers/acceptanceindex.go @@ -6,9 +6,9 @@ import ( "github.com/kaspanet/kaspad/blockdag" "github.com/kaspanet/kaspad/dbaccess" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) // AcceptanceIndex implements a txAcceptanceData by block hash index. That is to say, @@ -113,7 +113,7 @@ func (idx *AcceptanceIndex) TxsAcceptanceData(blockHash *daghash.Hash) (blockdag } type serializableTxAcceptanceData struct { - MsgTx wire.MsgTx + MsgTx domainmessage.MsgTx IsAccepted bool } diff --git a/blockdag/indexers/acceptanceindex_test.go b/blockdag/indexers/acceptanceindex_test.go index a695d9d43..cf6fe3b7f 100644 --- a/blockdag/indexers/acceptanceindex_test.go +++ b/blockdag/indexers/acceptanceindex_test.go @@ -12,28 +12,28 @@ import ( "github.com/kaspanet/kaspad/blockdag" "github.com/kaspanet/kaspad/dagconfig" "github.com/kaspanet/kaspad/dbaccess" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" "github.com/pkg/errors" ) func TestAcceptanceIndexSerializationAndDeserialization(t *testing.T) { // Create test data hash, _ := daghash.NewHashFromStr("1111111111111111111111111111111111111111111111111111111111111111") - txIn1 := &wire.TxIn{SignatureScript: []byte{1}, PreviousOutpoint: wire.Outpoint{Index: 1}, Sequence: 0} - txIn2 := &wire.TxIn{SignatureScript: []byte{2}, PreviousOutpoint: wire.Outpoint{Index: 2}, Sequence: 0} - txOut1 := &wire.TxOut{ScriptPubKey: []byte{1}, Value: 10} - txOut2 := &wire.TxOut{ScriptPubKey: []byte{2}, Value: 20} + txIn1 := &domainmessage.TxIn{SignatureScript: []byte{1}, PreviousOutpoint: domainmessage.Outpoint{Index: 1}, Sequence: 0} + txIn2 := &domainmessage.TxIn{SignatureScript: []byte{2}, PreviousOutpoint: domainmessage.Outpoint{Index: 2}, Sequence: 0} + txOut1 := &domainmessage.TxOut{ScriptPubKey: []byte{1}, Value: 10} + txOut2 := &domainmessage.TxOut{ScriptPubKey: []byte{2}, Value: 20} blockTxsAcceptanceData := blockdag.BlockTxsAcceptanceData{ BlockHash: *hash, TxAcceptanceData: []blockdag.TxAcceptanceData{ { - Tx: util.NewTx(wire.NewNativeMsgTx(wire.TxVersion, []*wire.TxIn{txIn1}, []*wire.TxOut{txOut1})), + Tx: util.NewTx(domainmessage.NewNativeMsgTx(domainmessage.TxVersion, []*domainmessage.TxIn{txIn1}, []*domainmessage.TxOut{txOut1})), IsAccepted: true, }, { - Tx: util.NewTx(wire.NewNativeMsgTx(wire.TxVersion, []*wire.TxIn{txIn2}, []*wire.TxOut{txOut2})), + Tx: util.NewTx(domainmessage.NewNativeMsgTx(domainmessage.TxVersion, []*domainmessage.TxIn{txIn2}, []*domainmessage.TxOut{txOut2})), IsAccepted: false, }, }, diff --git a/blockdag/mining.go b/blockdag/mining.go index e0793f013..5879ac6e5 100644 --- a/blockdag/mining.go +++ b/blockdag/mining.go @@ -6,11 +6,11 @@ import ( "time" "github.com/kaspanet/go-secp256k1" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/txscript" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/mstime" - "github.com/kaspanet/kaspad/wire" ) // BlockForMining returns a block with the given transactions @@ -18,7 +18,7 @@ import ( // all aspects except proof of work. // // This function MUST be called with the DAG state lock held (for reads). -func (dag *BlockDAG) BlockForMining(transactions []*util.Tx) (*wire.MsgBlock, error) { +func (dag *BlockDAG) BlockForMining(transactions []*util.Tx) (*domainmessage.MsgBlock, error) { blockTimestamp := dag.NextBlockTime() requiredDifficulty := dag.NextRequiredDifficulty(blockTimestamp) @@ -35,7 +35,7 @@ func (dag *BlockDAG) BlockForMining(transactions []*util.Tx) (*wire.MsgBlock, er if err != nil { return nil, err } - var msgBlock wire.MsgBlock + var msgBlock domainmessage.MsgBlock for _, tx := range transactions { msgBlock.AddTransaction(tx.MsgTx()) } @@ -45,7 +45,7 @@ func (dag *BlockDAG) BlockForMining(transactions []*util.Tx) (*wire.MsgBlock, er return nil, err } - msgBlock.Header = wire.BlockHeader{ + msgBlock.Header = domainmessage.BlockHeader{ Version: nextBlockVersion, ParentHashes: dag.TipHashes(), HashMerkleRoot: hashMerkleTree.Root(), diff --git a/blockdag/reachabilitystore.go b/blockdag/reachabilitystore.go index 064e82d6b..ce6ae7c36 100644 --- a/blockdag/reachabilitystore.go +++ b/blockdag/reachabilitystore.go @@ -4,8 +4,8 @@ import ( "bytes" "github.com/kaspanet/kaspad/database" "github.com/kaspanet/kaspad/dbaccess" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" "github.com/pkg/errors" "io" ) @@ -225,20 +225,20 @@ func (store *reachabilityStore) serializeTreeNode(w io.Writer, treeNode *reachab if treeNode.parent != nil { parentHash = treeNode.parent.blockNode.hash } - err = wire.WriteElement(w, parentHash) + err = domainmessage.WriteElement(w, parentHash) if err != nil { return err } // Serialize the amount of children - err = wire.WriteVarInt(w, uint64(len(treeNode.children))) + err = domainmessage.WriteVarInt(w, uint64(len(treeNode.children))) if err != nil { return err } // Serialize the children for _, child := range treeNode.children { - err = wire.WriteElement(w, child.blockNode.hash) + err = domainmessage.WriteElement(w, child.blockNode.hash) if err != nil { return err } @@ -249,13 +249,13 @@ func (store *reachabilityStore) serializeTreeNode(w io.Writer, treeNode *reachab func (store *reachabilityStore) serializeReachabilityInterval(w io.Writer, interval *reachabilityInterval) error { // Serialize start - err := wire.WriteElement(w, interval.start) + err := domainmessage.WriteElement(w, interval.start) if err != nil { return err } // Serialize end - err = wire.WriteElement(w, interval.end) + err = domainmessage.WriteElement(w, interval.end) if err != nil { return err } @@ -265,14 +265,14 @@ func (store *reachabilityStore) serializeReachabilityInterval(w io.Writer, inter func (store *reachabilityStore) serializeFutureCoveringSet(w io.Writer, futureCoveringSet futureCoveringTreeNodeSet) error { // Serialize the set size - err := wire.WriteVarInt(w, uint64(len(futureCoveringSet))) + err := domainmessage.WriteVarInt(w, uint64(len(futureCoveringSet))) if err != nil { return err } // Serialize each node in the set for _, node := range futureCoveringSet { - err = wire.WriteElement(w, node.blockNode.hash) + err = domainmessage.WriteElement(w, node.blockNode.hash) if err != nil { return err } @@ -312,7 +312,7 @@ func (store *reachabilityStore) deserializeTreeNode(r io.Reader, destination *re // Deserialize the parent // If this is the zero hash, this node is the genesis and as such doesn't have a parent parentHash := &daghash.Hash{} - err = wire.ReadElement(r, parentHash) + err = domainmessage.ReadElement(r, parentHash) if err != nil { return err } @@ -325,7 +325,7 @@ func (store *reachabilityStore) deserializeTreeNode(r io.Reader, destination *re } // Deserialize the amount of children - childCount, err := wire.ReadVarInt(r) + childCount, err := domainmessage.ReadVarInt(r) if err != nil { return err } @@ -334,7 +334,7 @@ func (store *reachabilityStore) deserializeTreeNode(r io.Reader, destination *re children := make([]*reachabilityTreeNode, childCount) for i := uint64(0); i < childCount; i++ { childHash := &daghash.Hash{} - err = wire.ReadElement(r, childHash) + err = domainmessage.ReadElement(r, childHash) if err != nil { return err } @@ -354,7 +354,7 @@ func (store *reachabilityStore) deserializeReachabilityInterval(r io.Reader) (*r // Deserialize start start := uint64(0) - err := wire.ReadElement(r, &start) + err := domainmessage.ReadElement(r, &start) if err != nil { return nil, err } @@ -362,7 +362,7 @@ func (store *reachabilityStore) deserializeReachabilityInterval(r io.Reader) (*r // Deserialize end end := uint64(0) - err = wire.ReadElement(r, &end) + err = domainmessage.ReadElement(r, &end) if err != nil { return nil, err } @@ -373,7 +373,7 @@ func (store *reachabilityStore) deserializeReachabilityInterval(r io.Reader) (*r func (store *reachabilityStore) deserializeFutureCoveringSet(r io.Reader, destination *reachabilityData) error { // Deserialize the set size - setSize, err := wire.ReadVarInt(r) + setSize, err := domainmessage.ReadVarInt(r) if err != nil { return err } @@ -382,7 +382,7 @@ func (store *reachabilityStore) deserializeFutureCoveringSet(r io.Reader, destin futureCoveringSet := make(futureCoveringTreeNodeSet, setSize) for i := uint64(0); i < setSize; i++ { blockHash := &daghash.Hash{} - err = wire.ReadElement(r, blockHash) + err = domainmessage.ReadElement(r, blockHash) if err != nil { return err } diff --git a/blockdag/scriptval.go b/blockdag/scriptval.go index 2673d878f..7a5b2ae9f 100644 --- a/blockdag/scriptval.go +++ b/blockdag/scriptval.go @@ -9,15 +9,15 @@ import ( "runtime" "time" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/txscript" "github.com/kaspanet/kaspad/util" - "github.com/kaspanet/kaspad/wire" ) // txValidateItem holds a transaction along with which input to validate. type txValidateItem struct { txInIndex int - txIn *wire.TxIn + txIn *domainmessage.TxIn tx *util.Tx } diff --git a/blockdag/subnetworks.go b/blockdag/subnetworks.go index 7a1912834..b74ee8526 100644 --- a/blockdag/subnetworks.go +++ b/blockdag/subnetworks.go @@ -10,8 +10,8 @@ import ( "github.com/kaspanet/kaspad/util" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util/subnetworkid" - "github.com/kaspanet/kaspad/wire" ) // registerSubnetworks scans a list of transactions, singles out @@ -19,7 +19,7 @@ import ( // subnetwork based on it. // This function returns an error if one or more transactions are invalid func registerSubnetworks(dbContext dbaccess.Context, txs []*util.Tx) error { - subnetworkRegistryTxs := make([]*wire.MsgTx, 0) + subnetworkRegistryTxs := make([]*domainmessage.MsgTx, 0) for _, tx := range txs { msgTx := tx.MsgTx() @@ -60,7 +60,7 @@ func registerSubnetworks(dbContext dbaccess.Context, txs []*util.Tx) error { // validateSubnetworkRegistryTransaction makes sure that a given subnetwork registry // transaction is valid. Such a transaction is valid iff: // - Its entire payload is a uint64 (8 bytes) -func validateSubnetworkRegistryTransaction(tx *wire.MsgTx) error { +func validateSubnetworkRegistryTransaction(tx *domainmessage.MsgTx) error { if len(tx.Payload) != 8 { return ruleError(ErrSubnetworkRegistry, fmt.Sprintf("validation failed: subnetwork registry"+ "tx '%s' has an invalid payload", tx.TxHash())) @@ -70,7 +70,7 @@ func validateSubnetworkRegistryTransaction(tx *wire.MsgTx) error { } // TxToSubnetworkID creates a subnetwork ID from a subnetwork registry transaction -func TxToSubnetworkID(tx *wire.MsgTx) (*subnetworkid.SubnetworkID, error) { +func TxToSubnetworkID(tx *domainmessage.MsgTx) (*subnetworkid.SubnetworkID, error) { txHash := tx.TxHash() return subnetworkid.New(util.Hash160(txHash[:])) } @@ -114,14 +114,14 @@ type subnetwork struct { gasLimit uint64 } -func newSubnetwork(tx *wire.MsgTx) *subnetwork { +func newSubnetwork(tx *domainmessage.MsgTx) *subnetwork { return &subnetwork{ gasLimit: ExtractGasLimit(tx), } } // ExtractGasLimit extracts the gas limit from the transaction payload -func ExtractGasLimit(tx *wire.MsgTx) uint64 { +func ExtractGasLimit(tx *domainmessage.MsgTx) uint64 { return binary.LittleEndian.Uint64(tx.Payload[:8]) } diff --git a/blockdag/test_utils.go b/blockdag/test_utils.go index 9108379dd..28edd0ba1 100644 --- a/blockdag/test_utils.go +++ b/blockdag/test_utils.go @@ -22,9 +22,9 @@ import ( "github.com/kaspanet/kaspad/util/subnetworkid" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/txscript" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) // FileExists returns whether or not the named file or directory exists. @@ -121,30 +121,30 @@ type txSubnetworkData struct { Payload []byte } -func createTxForTest(numInputs uint32, numOutputs uint32, outputValue uint64, subnetworkData *txSubnetworkData) *wire.MsgTx { - txIns := []*wire.TxIn{} - txOuts := []*wire.TxOut{} +func createTxForTest(numInputs uint32, numOutputs uint32, outputValue uint64, subnetworkData *txSubnetworkData) *domainmessage.MsgTx { + txIns := []*domainmessage.TxIn{} + txOuts := []*domainmessage.TxOut{} for i := uint32(0); i < numInputs; i++ { - txIns = append(txIns, &wire.TxIn{ - PreviousOutpoint: *wire.NewOutpoint(&daghash.TxID{}, i), + txIns = append(txIns, &domainmessage.TxIn{ + PreviousOutpoint: *domainmessage.NewOutpoint(&daghash.TxID{}, i), SignatureScript: []byte{}, - Sequence: wire.MaxTxInSequenceNum, + Sequence: domainmessage.MaxTxInSequenceNum, }) } for i := uint32(0); i < numOutputs; i++ { - txOuts = append(txOuts, &wire.TxOut{ + txOuts = append(txOuts, &domainmessage.TxOut{ ScriptPubKey: OpTrueScript, Value: outputValue, }) } if subnetworkData != nil { - return wire.NewSubnetworkMsgTx(wire.TxVersion, txIns, txOuts, subnetworkData.subnetworkID, subnetworkData.Gas, subnetworkData.Payload) + return domainmessage.NewSubnetworkMsgTx(domainmessage.TxVersion, txIns, txOuts, subnetworkData.subnetworkID, subnetworkData.Gas, subnetworkData.Payload) } - return wire.NewNativeMsgTx(wire.TxVersion, txIns, txOuts) + return domainmessage.NewNativeMsgTx(domainmessage.TxVersion, txIns, txOuts) } // VirtualForTest is an exported version for virtualBlock, so that it can be returned by exported test_util methods @@ -186,7 +186,7 @@ func GetVirtualFromParentsForTest(dag *BlockDAG, parentHashes []*daghash.Hash) ( // LoadBlocks reads files containing kaspa gzipped block data from disk // and returns them as an array of util.Block. func LoadBlocks(filename string) (blocks []*util.Block, err error) { - var network = wire.Mainnet + var network = domainmessage.Mainnet var dr io.Reader var fi io.ReadCloser @@ -244,7 +244,7 @@ func opTrueAddress(prefix util.Bech32Prefix) (util.Address, error) { } // PrepareBlockForTest generates a block with the proper merkle roots, coinbase transaction etc. This function is used for test purposes only -func PrepareBlockForTest(dag *BlockDAG, parentHashes []*daghash.Hash, transactions []*wire.MsgTx) (*wire.MsgBlock, error) { +func PrepareBlockForTest(dag *BlockDAG, parentHashes []*daghash.Hash, transactions []*domainmessage.MsgTx) (*domainmessage.MsgBlock, error) { newVirtual, err := GetVirtualFromParentsForTest(dag, parentHashes) if err != nil { return nil, err @@ -297,7 +297,7 @@ func PrepareBlockForTest(dag *BlockDAG, parentHashes []*daghash.Hash, transactio // PrepareAndProcessBlockForTest prepares a block that points to the given parent // hashes and process it. -func PrepareAndProcessBlockForTest(t *testing.T, dag *BlockDAG, parentHashes []*daghash.Hash, transactions []*wire.MsgTx) *wire.MsgBlock { +func PrepareAndProcessBlockForTest(t *testing.T, dag *BlockDAG, parentHashes []*daghash.Hash, transactions []*domainmessage.MsgTx) *domainmessage.MsgBlock { daghash.Sort(parentHashes) block, err := PrepareBlockForTest(dag, parentHashes, transactions) if err != nil { diff --git a/blockdag/utxo_ecmh.go b/blockdag/utxo_ecmh.go index 12ddd9f50..26794ab8a 100644 --- a/blockdag/utxo_ecmh.go +++ b/blockdag/utxo_ecmh.go @@ -3,10 +3,10 @@ package blockdag import ( "bytes" "github.com/kaspanet/go-secp256k1" - "github.com/kaspanet/kaspad/wire" + "github.com/kaspanet/kaspad/domainmessage" ) -func addUTXOToMultiset(ms *secp256k1.MultiSet, entry *UTXOEntry, outpoint *wire.Outpoint) (*secp256k1.MultiSet, error) { +func addUTXOToMultiset(ms *secp256k1.MultiSet, entry *UTXOEntry, outpoint *domainmessage.Outpoint) (*secp256k1.MultiSet, error) { w := &bytes.Buffer{} err := serializeUTXO(w, entry, outpoint) if err != nil { @@ -16,7 +16,7 @@ func addUTXOToMultiset(ms *secp256k1.MultiSet, entry *UTXOEntry, outpoint *wire. return ms, nil } -func removeUTXOFromMultiset(ms *secp256k1.MultiSet, entry *UTXOEntry, outpoint *wire.Outpoint) (*secp256k1.MultiSet, error) { +func removeUTXOFromMultiset(ms *secp256k1.MultiSet, entry *UTXOEntry, outpoint *domainmessage.Outpoint) (*secp256k1.MultiSet, error) { w := &bytes.Buffer{} err := serializeUTXO(w, entry, outpoint) if err != nil { diff --git a/blockdag/utxodiffstore_test.go b/blockdag/utxodiffstore_test.go index 3beedc611..347939328 100644 --- a/blockdag/utxodiffstore_test.go +++ b/blockdag/utxodiffstore_test.go @@ -6,8 +6,8 @@ import ( "github.com/kaspanet/kaspad/dagconfig" "github.com/kaspanet/kaspad/dbaccess" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) func TestUTXODiffStore(t *testing.T) { @@ -42,8 +42,8 @@ func TestUTXODiffStore(t *testing.T) { // Add node's diff data to the utxoDiffStore and check if it's checked correctly. node := createNode() diff := NewUTXODiff() - diff.toAdd.add(wire.Outpoint{TxID: daghash.TxID{0x01}, Index: 0}, &UTXOEntry{amount: 1, scriptPubKey: []byte{0x01}}) - diff.toRemove.add(wire.Outpoint{TxID: daghash.TxID{0x02}, Index: 0}, &UTXOEntry{amount: 2, scriptPubKey: []byte{0x02}}) + diff.toAdd.add(domainmessage.Outpoint{TxID: daghash.TxID{0x01}, Index: 0}, &UTXOEntry{amount: 1, scriptPubKey: []byte{0x01}}) + diff.toRemove.add(domainmessage.Outpoint{TxID: daghash.TxID{0x02}, Index: 0}, &UTXOEntry{amount: 2, scriptPubKey: []byte{0x02}}) if err := dag.utxoDiffStore.setBlockDiff(node, diff); err != nil { t.Fatalf("setBlockDiff: unexpected error: %s", err) } diff --git a/blockdag/utxoio.go b/blockdag/utxoio.go index c7bb474c9..583d075b6 100644 --- a/blockdag/utxoio.go +++ b/blockdag/utxoio.go @@ -2,9 +2,9 @@ package blockdag import ( "bytes" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util/binaryserializer" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" "github.com/pkg/errors" "io" ) @@ -17,12 +17,12 @@ import ( // diff | UTXODiff | The diff data's diff func serializeBlockUTXODiffData(w io.Writer, diffData *blockUTXODiffData) error { hasDiffChild := diffData.diffChild != nil - err := wire.WriteElement(w, hasDiffChild) + err := domainmessage.WriteElement(w, hasDiffChild) if err != nil { return err } if hasDiffChild { - err := wire.WriteElement(w, diffData.diffChild.hash) + err := domainmessage.WriteElement(w, diffData.diffChild.hash) if err != nil { return err } @@ -41,14 +41,14 @@ func (diffStore *utxoDiffStore) deserializeBlockUTXODiffData(serializedDiffData r := bytes.NewBuffer(serializedDiffData) var hasDiffChild bool - err := wire.ReadElement(r, &hasDiffChild) + err := domainmessage.ReadElement(r, &hasDiffChild) if err != nil { return nil, err } if hasDiffChild { hash := &daghash.Hash{} - err := wire.ReadElement(r, hash) + err := domainmessage.ReadElement(r, hash) if err != nil { return nil, err } @@ -86,7 +86,7 @@ func deserializeUTXODiff(r io.Reader) (*UTXODiff, error) { } func deserializeUTXOCollection(r io.Reader) (utxoCollection, error) { - count, err := wire.ReadVarInt(r) + count, err := domainmessage.ReadVarInt(r) if err != nil { return nil, err } @@ -101,7 +101,7 @@ func deserializeUTXOCollection(r io.Reader) (utxoCollection, error) { return collection, nil } -func deserializeUTXO(r io.Reader) (*UTXOEntry, *wire.Outpoint, error) { +func deserializeUTXO(r io.Reader) (*UTXOEntry, *domainmessage.Outpoint, error) { outpoint, err := deserializeOutpoint(r) if err != nil { return nil, nil, err @@ -134,7 +134,7 @@ func serializeUTXODiff(w io.Writer, diff *UTXODiff) error { // the utxo entries and serializing them and their corresponding outpoint // prefixed by a varint that indicates their size. func serializeUTXOCollection(w io.Writer, collection utxoCollection) error { - err := wire.WriteVarInt(w, uint64(len(collection))) + err := domainmessage.WriteVarInt(w, uint64(len(collection))) if err != nil { return err } @@ -148,7 +148,7 @@ func serializeUTXOCollection(w io.Writer, collection utxoCollection) error { } // serializeUTXO serializes a utxo entry-outpoint pair -func serializeUTXO(w io.Writer, entry *UTXOEntry, outpoint *wire.Outpoint) error { +func serializeUTXO(w io.Writer, entry *UTXOEntry, outpoint *domainmessage.Outpoint) error { err := serializeOutpoint(w, outpoint) if err != nil { return err @@ -163,7 +163,7 @@ func serializeUTXO(w io.Writer, entry *UTXOEntry, outpoint *wire.Outpoint) error // p2pkhUTXOEntrySerializeSize is the serialized size for a P2PKH UTXO entry. // 8 bytes (header code) + 8 bytes (amount) + varint for script pub key length of 25 (for P2PKH) + 25 bytes for P2PKH script. -var p2pkhUTXOEntrySerializeSize = 8 + 8 + wire.VarIntSerializeSize(25) + 25 +var p2pkhUTXOEntrySerializeSize = 8 + 8 + domainmessage.VarIntSerializeSize(25) + 25 // serializeUTXOEntry encodes the entry to the given io.Writer and use compression if useCompression is true. // The compression format is described in detail above. @@ -185,7 +185,7 @@ func serializeUTXOEntry(w io.Writer, entry *UTXOEntry) error { return err } - err = wire.WriteVarInt(w, uint64(len(entry.ScriptPubKey()))) + err = domainmessage.WriteVarInt(w, uint64(len(entry.ScriptPubKey()))) if err != nil { return err } @@ -225,7 +225,7 @@ func deserializeUTXOEntry(r io.Reader) (*UTXOEntry, error) { return nil, err } - scriptPubKeyLen, err := wire.ReadVarInt(r) + scriptPubKeyLen, err := domainmessage.ReadVarInt(r) if err != nil { return nil, err } diff --git a/blockdag/utxoset.go b/blockdag/utxoset.go index 40a32c269..b96cc7d87 100644 --- a/blockdag/utxoset.go +++ b/blockdag/utxoset.go @@ -9,7 +9,7 @@ import ( "github.com/pkg/errors" "github.com/kaspanet/go-secp256k1" - "github.com/kaspanet/kaspad/wire" + "github.com/kaspanet/kaspad/domainmessage" ) const ( @@ -78,7 +78,7 @@ const ( ) // NewUTXOEntry creates a new utxoEntry representing the given txOut -func NewUTXOEntry(txOut *wire.TxOut, isCoinbase bool, blockBlueScore uint64) *UTXOEntry { +func NewUTXOEntry(txOut *domainmessage.TxOut, isCoinbase bool, blockBlueScore uint64) *UTXOEntry { entry := &UTXOEntry{ amount: txOut.Value, scriptPubKey: txOut.ScriptPubKey, @@ -93,7 +93,7 @@ func NewUTXOEntry(txOut *wire.TxOut, isCoinbase bool, blockBlueScore uint64) *UT } // utxoCollection represents a set of UTXOs indexed by their outpoints -type utxoCollection map[wire.Outpoint]*UTXOEntry +type utxoCollection map[domainmessage.Outpoint]*UTXOEntry func (uc utxoCollection) String() string { utxoStrings := make([]string, len(uc)) @@ -112,31 +112,31 @@ func (uc utxoCollection) String() string { } // add adds a new UTXO entry to this collection -func (uc utxoCollection) add(outpoint wire.Outpoint, entry *UTXOEntry) { +func (uc utxoCollection) add(outpoint domainmessage.Outpoint, entry *UTXOEntry) { uc[outpoint] = entry } // remove removes a UTXO entry from this collection if it exists -func (uc utxoCollection) remove(outpoint wire.Outpoint) { +func (uc utxoCollection) remove(outpoint domainmessage.Outpoint) { delete(uc, outpoint) } // get returns the UTXOEntry represented by provided outpoint, // and a boolean value indicating if said UTXOEntry is in the set or not -func (uc utxoCollection) get(outpoint wire.Outpoint) (*UTXOEntry, bool) { +func (uc utxoCollection) get(outpoint domainmessage.Outpoint) (*UTXOEntry, bool) { entry, ok := uc[outpoint] return entry, ok } // contains returns a boolean value indicating whether a UTXO entry is in the set -func (uc utxoCollection) contains(outpoint wire.Outpoint) bool { +func (uc utxoCollection) contains(outpoint domainmessage.Outpoint) bool { _, ok := uc[outpoint] return ok } // containsWithBlueScore returns a boolean value indicating whether a UTXOEntry // is in the set and its blue score is equal to the given blue score. -func (uc utxoCollection) containsWithBlueScore(outpoint wire.Outpoint, blueScore uint64) bool { +func (uc utxoCollection) containsWithBlueScore(outpoint domainmessage.Outpoint, blueScore uint64) bool { entry, ok := uc.get(outpoint) return ok && entry.blockBlueScore == blueScore } @@ -353,7 +353,7 @@ func (d *UTXODiff) clone() *UTXODiff { // // If d.useMultiset is true, this function MUST be // called with the DAG lock held. -func (d *UTXODiff) AddEntry(outpoint wire.Outpoint, entry *UTXOEntry) error { +func (d *UTXODiff) AddEntry(outpoint domainmessage.Outpoint, entry *UTXOEntry) error { if d.toRemove.containsWithBlueScore(outpoint, entry.blockBlueScore) { d.toRemove.remove(outpoint) } else if _, exists := d.toAdd[outpoint]; exists { @@ -368,7 +368,7 @@ func (d *UTXODiff) AddEntry(outpoint wire.Outpoint, entry *UTXOEntry) error { // // If d.useMultiset is true, this function MUST be // called with the DAG lock held. -func (d *UTXODiff) RemoveEntry(outpoint wire.Outpoint, entry *UTXOEntry) error { +func (d *UTXODiff) RemoveEntry(outpoint domainmessage.Outpoint, entry *UTXOEntry) error { if d.toAdd.containsWithBlueScore(outpoint, entry.blockBlueScore) { d.toAdd.remove(outpoint) } else if _, exists := d.toRemove[outpoint]; exists { @@ -399,9 +399,9 @@ type UTXOSet interface { fmt.Stringer diffFrom(other UTXOSet) (*UTXODiff, error) WithDiff(utxoDiff *UTXODiff) (UTXOSet, error) - AddTx(tx *wire.MsgTx, blockBlueScore uint64) (ok bool, err error) + AddTx(tx *domainmessage.MsgTx, blockBlueScore uint64) (ok bool, err error) clone() UTXOSet - Get(outpoint wire.Outpoint) (*UTXOEntry, bool) + Get(outpoint domainmessage.Outpoint) (*UTXOEntry, bool) } // FullUTXOSet represents a full list of transaction outputs and their values @@ -456,7 +456,7 @@ func (fus *FullUTXOSet) WithDiff(other *UTXODiff) (UTXOSet, error) { // necessarily means there's an error). // // This function MUST be called with the DAG lock held. -func (fus *FullUTXOSet) AddTx(tx *wire.MsgTx, blueScore uint64) (isAccepted bool, err error) { +func (fus *FullUTXOSet) AddTx(tx *domainmessage.MsgTx, blueScore uint64) (isAccepted bool, err error) { if !fus.containsInputs(tx) { return false, nil } @@ -467,7 +467,7 @@ func (fus *FullUTXOSet) AddTx(tx *wire.MsgTx, blueScore uint64) (isAccepted bool isCoinbase := tx.IsCoinBase() for i, txOut := range tx.TxOut { - outpoint := *wire.NewOutpoint(tx.TxID(), uint32(i)) + outpoint := *domainmessage.NewOutpoint(tx.TxID(), uint32(i)) entry := NewUTXOEntry(txOut, isCoinbase, blueScore) fus.add(outpoint, entry) } @@ -475,9 +475,9 @@ func (fus *FullUTXOSet) AddTx(tx *wire.MsgTx, blueScore uint64) (isAccepted bool return true, nil } -func (fus *FullUTXOSet) containsInputs(tx *wire.MsgTx) bool { +func (fus *FullUTXOSet) containsInputs(tx *domainmessage.MsgTx) bool { for _, txIn := range tx.TxIn { - outpoint := *wire.NewOutpoint(&txIn.PreviousOutpoint.TxID, txIn.PreviousOutpoint.Index) + outpoint := *domainmessage.NewOutpoint(&txIn.PreviousOutpoint.TxID, txIn.PreviousOutpoint.Index) if !fus.contains(outpoint) { return false } @@ -492,7 +492,7 @@ func (fus *FullUTXOSet) clone() UTXOSet { } // Get returns the UTXOEntry associated with the given Outpoint, and a boolean indicating if such entry was found -func (fus *FullUTXOSet) Get(outpoint wire.Outpoint) (*UTXOEntry, bool) { +func (fus *FullUTXOSet) Get(outpoint domainmessage.Outpoint) (*UTXOEntry, bool) { utxoEntry, ok := fus.utxoCollection[outpoint] return utxoEntry, ok } @@ -540,7 +540,7 @@ func (dus *DiffUTXOSet) WithDiff(other *UTXODiff) (UTXOSet, error) { // // If dus.UTXODiff.useMultiset is true, this function MUST be // called with the DAG lock held. -func (dus *DiffUTXOSet) AddTx(tx *wire.MsgTx, blockBlueScore uint64) (bool, error) { +func (dus *DiffUTXOSet) AddTx(tx *domainmessage.MsgTx, blockBlueScore uint64) (bool, error) { if !dus.containsInputs(tx) { return false, nil } @@ -553,7 +553,7 @@ func (dus *DiffUTXOSet) AddTx(tx *wire.MsgTx, blockBlueScore uint64) (bool, erro return true, nil } -func (dus *DiffUTXOSet) appendTx(tx *wire.MsgTx, blockBlueScore uint64) error { +func (dus *DiffUTXOSet) appendTx(tx *domainmessage.MsgTx, blockBlueScore uint64) error { for _, txIn := range tx.TxIn { entry, ok := dus.Get(txIn.PreviousOutpoint) if !ok { @@ -567,7 +567,7 @@ func (dus *DiffUTXOSet) appendTx(tx *wire.MsgTx, blockBlueScore uint64) error { isCoinbase := tx.IsCoinBase() for i, txOut := range tx.TxOut { - outpoint := *wire.NewOutpoint(tx.TxID(), uint32(i)) + outpoint := *domainmessage.NewOutpoint(tx.TxID(), uint32(i)) entry := NewUTXOEntry(txOut, isCoinbase, blockBlueScore) err := dus.UTXODiff.AddEntry(outpoint, entry) @@ -578,9 +578,9 @@ func (dus *DiffUTXOSet) appendTx(tx *wire.MsgTx, blockBlueScore uint64) error { return nil } -func (dus *DiffUTXOSet) containsInputs(tx *wire.MsgTx) bool { +func (dus *DiffUTXOSet) containsInputs(tx *domainmessage.MsgTx) bool { for _, txIn := range tx.TxIn { - outpoint := *wire.NewOutpoint(&txIn.PreviousOutpoint.TxID, txIn.PreviousOutpoint.Index) + outpoint := *domainmessage.NewOutpoint(&txIn.PreviousOutpoint.TxID, txIn.PreviousOutpoint.Index) isInBase := dus.base.contains(outpoint) isInDiffToAdd := dus.UTXODiff.toAdd.contains(outpoint) isInDiffToRemove := dus.UTXODiff.toRemove.contains(outpoint) @@ -626,7 +626,7 @@ func (dus *DiffUTXOSet) cloneWithoutBase() UTXOSet { // Get returns the UTXOEntry associated with provided outpoint in this UTXOSet. // Returns false in second output if this UTXOEntry was not found -func (dus *DiffUTXOSet) Get(outpoint wire.Outpoint) (*UTXOEntry, bool) { +func (dus *DiffUTXOSet) Get(outpoint domainmessage.Outpoint) (*UTXOEntry, bool) { if toRemoveEntry, ok := dus.UTXODiff.toRemove.get(outpoint); ok { // An exception is made for entries with unequal blue scores // These are just "updates" to accepted blue score diff --git a/blockdag/utxoset_test.go b/blockdag/utxoset_test.go index c18e464fd..30878ddfc 100644 --- a/blockdag/utxoset_test.go +++ b/blockdag/utxoset_test.go @@ -6,18 +6,18 @@ import ( "github.com/kaspanet/kaspad/util/subnetworkid" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) // TestUTXOCollection makes sure that utxoCollection cloning and string representations work as expected. func TestUTXOCollection(t *testing.T) { txID0, _ := daghash.NewTxIDFromStr("0000000000000000000000000000000000000000000000000000000000000000") txID1, _ := daghash.NewTxIDFromStr("1111111111111111111111111111111111111111111111111111111111111111") - outpoint0 := *wire.NewOutpoint(txID0, 0) - outpoint1 := *wire.NewOutpoint(txID1, 0) - utxoEntry0 := NewUTXOEntry(&wire.TxOut{ScriptPubKey: []byte{}, Value: 10}, true, 0) - utxoEntry1 := NewUTXOEntry(&wire.TxOut{ScriptPubKey: []byte{}, Value: 20}, false, 1) + outpoint0 := *domainmessage.NewOutpoint(txID0, 0) + outpoint1 := *domainmessage.NewOutpoint(txID1, 0) + utxoEntry0 := NewUTXOEntry(&domainmessage.TxOut{ScriptPubKey: []byte{}, Value: 10}, true, 0) + utxoEntry1 := NewUTXOEntry(&domainmessage.TxOut{ScriptPubKey: []byte{}, Value: 20}, false, 1) // For each of the following test cases, we will: // .String() the given collection and compare it to expectedStringWithMultiset @@ -73,10 +73,10 @@ func TestUTXOCollection(t *testing.T) { func TestUTXODiff(t *testing.T) { txID0, _ := daghash.NewTxIDFromStr("0000000000000000000000000000000000000000000000000000000000000000") txID1, _ := daghash.NewTxIDFromStr("1111111111111111111111111111111111111111111111111111111111111111") - outpoint0 := *wire.NewOutpoint(txID0, 0) - outpoint1 := *wire.NewOutpoint(txID1, 0) - utxoEntry0 := NewUTXOEntry(&wire.TxOut{ScriptPubKey: []byte{}, Value: 10}, true, 0) - utxoEntry1 := NewUTXOEntry(&wire.TxOut{ScriptPubKey: []byte{}, Value: 20}, false, 1) + outpoint0 := *domainmessage.NewOutpoint(txID0, 0) + outpoint1 := *domainmessage.NewOutpoint(txID1, 0) + utxoEntry0 := NewUTXOEntry(&domainmessage.TxOut{ScriptPubKey: []byte{}, Value: 10}, true, 0) + utxoEntry1 := NewUTXOEntry(&domainmessage.TxOut{ScriptPubKey: []byte{}, Value: 20}, false, 1) // Test utxoDiff creation @@ -119,9 +119,9 @@ func TestUTXODiff(t *testing.T) { // Each test case represents a cell in the two tables outlined in the documentation for utxoDiff. func TestUTXODiffRules(t *testing.T) { txID0, _ := daghash.NewTxIDFromStr("0000000000000000000000000000000000000000000000000000000000000000") - outpoint0 := *wire.NewOutpoint(txID0, 0) - utxoEntry1 := NewUTXOEntry(&wire.TxOut{ScriptPubKey: []byte{}, Value: 10}, true, 10) - utxoEntry2 := NewUTXOEntry(&wire.TxOut{ScriptPubKey: []byte{}, Value: 10}, true, 20) + outpoint0 := *domainmessage.NewOutpoint(txID0, 0) + utxoEntry1 := NewUTXOEntry(&domainmessage.TxOut{ScriptPubKey: []byte{}, Value: 10}, true, 10) + utxoEntry2 := NewUTXOEntry(&domainmessage.TxOut{ScriptPubKey: []byte{}, Value: 10}, true, 20) // For each of the following test cases, we will: // this.diffFrom(other) and compare it to expectedDiffFromResult @@ -630,10 +630,10 @@ func (dus *DiffUTXOSet) equal(other *DiffUTXOSet) bool { func TestFullUTXOSet(t *testing.T) { txID0, _ := daghash.NewTxIDFromStr("0000000000000000000000000000000000000000000000000000000000000000") txID1, _ := daghash.NewTxIDFromStr("1111111111111111111111111111111111111111111111111111111111111111") - outpoint0 := *wire.NewOutpoint(txID0, 0) - outpoint1 := *wire.NewOutpoint(txID1, 0) - txOut0 := &wire.TxOut{ScriptPubKey: []byte{}, Value: 10} - txOut1 := &wire.TxOut{ScriptPubKey: []byte{}, Value: 20} + outpoint0 := *domainmessage.NewOutpoint(txID0, 0) + outpoint1 := *domainmessage.NewOutpoint(txID1, 0) + txOut0 := &domainmessage.TxOut{ScriptPubKey: []byte{}, Value: 10} + txOut1 := &domainmessage.TxOut{ScriptPubKey: []byte{}, Value: 20} utxoEntry0 := NewUTXOEntry(txOut0, true, 0) utxoEntry1 := NewUTXOEntry(txOut1, false, 1) diff := &UTXODiff{ @@ -661,8 +661,8 @@ func TestFullUTXOSet(t *testing.T) { } // Test fullUTXOSet addTx - txIn0 := &wire.TxIn{SignatureScript: []byte{}, PreviousOutpoint: wire.Outpoint{TxID: *txID0, Index: 0}, Sequence: 0} - transaction0 := wire.NewNativeMsgTx(1, []*wire.TxIn{txIn0}, []*wire.TxOut{txOut0}) + txIn0 := &domainmessage.TxIn{SignatureScript: []byte{}, PreviousOutpoint: domainmessage.Outpoint{TxID: *txID0, Index: 0}, Sequence: 0} + transaction0 := domainmessage.NewNativeMsgTx(1, []*domainmessage.TxIn{txIn0}, []*domainmessage.TxOut{txOut0}) if isAccepted, err := emptySet.AddTx(transaction0, 0); err != nil { t.Errorf("AddTx unexpectedly failed: %s", err) } else if isAccepted { @@ -694,10 +694,10 @@ func TestFullUTXOSet(t *testing.T) { func TestDiffUTXOSet(t *testing.T) { txID0, _ := daghash.NewTxIDFromStr("0000000000000000000000000000000000000000000000000000000000000000") txID1, _ := daghash.NewTxIDFromStr("1111111111111111111111111111111111111111111111111111111111111111") - outpoint0 := *wire.NewOutpoint(txID0, 0) - outpoint1 := *wire.NewOutpoint(txID1, 0) - txOut0 := &wire.TxOut{ScriptPubKey: []byte{}, Value: 10} - txOut1 := &wire.TxOut{ScriptPubKey: []byte{}, Value: 20} + outpoint0 := *domainmessage.NewOutpoint(txID0, 0) + outpoint1 := *domainmessage.NewOutpoint(txID1, 0) + txOut0 := &domainmessage.TxOut{ScriptPubKey: []byte{}, Value: 10} + txOut1 := &domainmessage.TxOut{ScriptPubKey: []byte{}, Value: 20} utxoEntry0 := NewUTXOEntry(txOut0, true, 0) utxoEntry1 := NewUTXOEntry(txOut1, false, 1) diff := &UTXODiff{ @@ -946,29 +946,29 @@ func TestUTXOSetDiffRules(t *testing.T) { // TestDiffUTXOSet_addTx makes sure that diffUTXOSet addTx works as expected func TestDiffUTXOSet_addTx(t *testing.T) { - txOut0 := &wire.TxOut{ScriptPubKey: []byte{0}, Value: 10} + txOut0 := &domainmessage.TxOut{ScriptPubKey: []byte{0}, Value: 10} utxoEntry0 := NewUTXOEntry(txOut0, true, 0) - coinbaseTX := wire.NewSubnetworkMsgTx(1, []*wire.TxIn{}, []*wire.TxOut{txOut0}, subnetworkid.SubnetworkIDCoinbase, 0, nil) + coinbaseTX := domainmessage.NewSubnetworkMsgTx(1, []*domainmessage.TxIn{}, []*domainmessage.TxOut{txOut0}, subnetworkid.SubnetworkIDCoinbase, 0, nil) // transaction1 spends coinbaseTX id1 := coinbaseTX.TxID() - outpoint1 := *wire.NewOutpoint(id1, 0) - txIn1 := &wire.TxIn{SignatureScript: []byte{}, PreviousOutpoint: outpoint1, Sequence: 0} - txOut1 := &wire.TxOut{ScriptPubKey: []byte{1}, Value: 20} + outpoint1 := *domainmessage.NewOutpoint(id1, 0) + txIn1 := &domainmessage.TxIn{SignatureScript: []byte{}, PreviousOutpoint: outpoint1, Sequence: 0} + txOut1 := &domainmessage.TxOut{ScriptPubKey: []byte{1}, Value: 20} utxoEntry1 := NewUTXOEntry(txOut1, false, 1) - transaction1 := wire.NewNativeMsgTx(1, []*wire.TxIn{txIn1}, []*wire.TxOut{txOut1}) + transaction1 := domainmessage.NewNativeMsgTx(1, []*domainmessage.TxIn{txIn1}, []*domainmessage.TxOut{txOut1}) // transaction2 spends transaction1 id2 := transaction1.TxID() - outpoint2 := *wire.NewOutpoint(id2, 0) - txIn2 := &wire.TxIn{SignatureScript: []byte{}, PreviousOutpoint: outpoint2, Sequence: 0} - txOut2 := &wire.TxOut{ScriptPubKey: []byte{2}, Value: 30} + outpoint2 := *domainmessage.NewOutpoint(id2, 0) + txIn2 := &domainmessage.TxIn{SignatureScript: []byte{}, PreviousOutpoint: outpoint2, Sequence: 0} + txOut2 := &domainmessage.TxOut{ScriptPubKey: []byte{2}, Value: 30} utxoEntry2 := NewUTXOEntry(txOut2, false, 2) - transaction2 := wire.NewNativeMsgTx(1, []*wire.TxIn{txIn2}, []*wire.TxOut{txOut2}) + transaction2 := domainmessage.NewNativeMsgTx(1, []*domainmessage.TxIn{txIn2}, []*domainmessage.TxOut{txOut2}) // outpoint3 is the outpoint for transaction2 id3 := transaction2.TxID() - outpoint3 := *wire.NewOutpoint(id3, 0) + outpoint3 := *domainmessage.NewOutpoint(id3, 0) // For each of the following test cases, we will: // 1. startSet.addTx() all the transactions in toAdd, in order, with the initial block height startHeight @@ -977,14 +977,14 @@ func TestDiffUTXOSet_addTx(t *testing.T) { name string startSet *DiffUTXOSet startHeight uint64 - toAdd []*wire.MsgTx + toAdd []*domainmessage.MsgTx expectedSet *DiffUTXOSet }{ { name: "add coinbase transaction to empty set", startSet: NewDiffUTXOSet(NewFullUTXOSet(), NewUTXODiff()), startHeight: 0, - toAdd: []*wire.MsgTx{coinbaseTX}, + toAdd: []*domainmessage.MsgTx{coinbaseTX}, expectedSet: &DiffUTXOSet{ base: &FullUTXOSet{utxoCollection: utxoCollection{}}, UTXODiff: &UTXODiff{ @@ -997,7 +997,7 @@ func TestDiffUTXOSet_addTx(t *testing.T) { name: "add regular transaction to empty set", startSet: NewDiffUTXOSet(NewFullUTXOSet(), NewUTXODiff()), startHeight: 0, - toAdd: []*wire.MsgTx{transaction1}, + toAdd: []*domainmessage.MsgTx{transaction1}, expectedSet: &DiffUTXOSet{ base: &FullUTXOSet{utxoCollection: utxoCollection{}}, UTXODiff: &UTXODiff{ @@ -1016,7 +1016,7 @@ func TestDiffUTXOSet_addTx(t *testing.T) { }, }, startHeight: 1, - toAdd: []*wire.MsgTx{transaction1}, + toAdd: []*domainmessage.MsgTx{transaction1}, expectedSet: &DiffUTXOSet{ base: &FullUTXOSet{utxoCollection: utxoCollection{outpoint1: utxoEntry0}}, UTXODiff: &UTXODiff{ @@ -1035,7 +1035,7 @@ func TestDiffUTXOSet_addTx(t *testing.T) { }, }, startHeight: 1, - toAdd: []*wire.MsgTx{transaction1}, + toAdd: []*domainmessage.MsgTx{transaction1}, expectedSet: &DiffUTXOSet{ base: NewFullUTXOSet(), UTXODiff: &UTXODiff{ @@ -1054,7 +1054,7 @@ func TestDiffUTXOSet_addTx(t *testing.T) { }, }, startHeight: 1, - toAdd: []*wire.MsgTx{transaction1}, + toAdd: []*domainmessage.MsgTx{transaction1}, expectedSet: &DiffUTXOSet{ base: NewFullUTXOSet(), UTXODiff: &UTXODiff{ @@ -1073,7 +1073,7 @@ func TestDiffUTXOSet_addTx(t *testing.T) { }, }, startHeight: 1, - toAdd: []*wire.MsgTx{transaction1, transaction2}, + toAdd: []*domainmessage.MsgTx{transaction1, transaction2}, expectedSet: &DiffUTXOSet{ base: &FullUTXOSet{utxoCollection: utxoCollection{outpoint1: utxoEntry0}}, UTXODiff: &UTXODiff{ @@ -1125,16 +1125,16 @@ func (dus *DiffUTXOSet) collection() (utxoCollection, error) { func TestUTXOSetAddEntry(t *testing.T) { txID0, _ := daghash.NewTxIDFromStr("0000000000000000000000000000000000000000000000000000000000000000") txID1, _ := daghash.NewTxIDFromStr("1111111111111111111111111111111111111111111111111111111111111111") - outpoint0 := wire.NewOutpoint(txID0, 0) - outpoint1 := wire.NewOutpoint(txID1, 0) - utxoEntry0 := NewUTXOEntry(&wire.TxOut{ScriptPubKey: []byte{}, Value: 10}, true, 0) - utxoEntry1 := NewUTXOEntry(&wire.TxOut{ScriptPubKey: []byte{}, Value: 20}, false, 1) + outpoint0 := domainmessage.NewOutpoint(txID0, 0) + outpoint1 := domainmessage.NewOutpoint(txID1, 0) + utxoEntry0 := NewUTXOEntry(&domainmessage.TxOut{ScriptPubKey: []byte{}, Value: 10}, true, 0) + utxoEntry1 := NewUTXOEntry(&domainmessage.TxOut{ScriptPubKey: []byte{}, Value: 20}, false, 1) utxoDiff := NewUTXODiff() tests := []struct { name string - outpointToAdd *wire.Outpoint + outpointToAdd *domainmessage.Outpoint utxoEntryToAdd *UTXOEntry expectedUTXODiff *UTXODiff expectedError string diff --git a/blockdag/validate.go b/blockdag/validate.go index 22f19f730..bef8b29d8 100644 --- a/blockdag/validate.go +++ b/blockdag/validate.go @@ -14,11 +14,11 @@ import ( "github.com/pkg/errors" "github.com/kaspanet/kaspad/dagconfig" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/txscript" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/subnetworkid" - "github.com/kaspanet/kaspad/wire" ) const ( @@ -46,7 +46,7 @@ const ( // isNullOutpoint determines whether or not a previous transaction outpoint // is set. -func isNullOutpoint(outpoint *wire.Outpoint) bool { +func isNullOutpoint(outpoint *domainmessage.Outpoint) bool { if outpoint.Index == math.MaxUint32 && outpoint.TxID == daghash.ZeroTxID { return true } @@ -171,7 +171,7 @@ func CheckTransactionSanity(tx *util.Tx, subnetworkID *subnetworkid.SubnetworkID } // Check for duplicate transaction inputs. - existingTxOut := make(map[wire.Outpoint]struct{}) + existingTxOut := make(map[domainmessage.Outpoint]struct{}) for _, txIn := range msgTx.TxIn { if _, exists := existingTxOut[txIn.PreviousOutpoint]; exists { return ruleError(ErrDuplicateTxInputs, "transaction "+ @@ -255,7 +255,7 @@ func CheckTransactionSanity(tx *util.Tx, subnetworkID *subnetworkid.SubnetworkID // The flags modify the behavior of this function as follows: // - BFNoPoWCheck: The check to ensure the block hash is less than the target // difficulty is not performed. -func (dag *BlockDAG) checkProofOfWork(header *wire.BlockHeader, flags BehaviorFlags) error { +func (dag *BlockDAG) checkProofOfWork(header *domainmessage.BlockHeader, flags BehaviorFlags) error { // The target difficulty must be larger than zero. target := util.CompactToBig(header.Bits) if target.Sign() <= 0 { @@ -295,9 +295,9 @@ func ValidateTxMass(tx *util.Tx, utxoSet UTXOSet) error { if err != nil { return err } - if txMass > wire.MaxMassPerBlock { + if txMass > domainmessage.MaxMassPerBlock { str := fmt.Sprintf("tx %s has mass %d, which is above the "+ - "allowed limit of %d", tx.ID(), txMass, wire.MaxMassPerBlock) + "allowed limit of %d", tx.ID(), txMass, domainmessage.MaxMassPerBlock) return ruleError(ErrTxMassTooHigh, str) } return nil @@ -321,9 +321,9 @@ func CalcBlockMass(pastUTXO UTXOSet, transactions []*util.Tx) (uint64, error) { // We could potentially overflow the accumulator so check for // overflow as well. - if totalMass < txMass || totalMass > wire.MaxMassPerBlock { + if totalMass < txMass || totalMass > domainmessage.MaxMassPerBlock { str := fmt.Sprintf("block has total mass %d, which is "+ - "above the allowed limit of %d", totalMass, wire.MaxMassPerBlock) + "above the allowed limit of %d", totalMass, domainmessage.MaxMassPerBlock) return 0, ruleError(ErrBlockMassTooHigh, str) } } @@ -426,7 +426,7 @@ func (dag *BlockDAG) checkBlockHeaderSanity(block *util.Block, flags BehaviorFla } //checkBlockParentsOrder ensures that the block's parents are ordered by hash -func checkBlockParentsOrder(header *wire.BlockHeader) error { +func checkBlockParentsOrder(header *domainmessage.BlockHeader) error { sortedHashes := make([]*daghash.Hash, header.NumParentBlocks()) for i, hash := range header.ParentHashes { sortedHashes[i] = hash @@ -512,9 +512,9 @@ func (dag *BlockDAG) checkBlockContainsLessThanMaxBlockMassTransactions(block *u // else it is certainly over the block mass limit. transactions := block.Transactions() numTx := len(transactions) - if numTx > wire.MaxMassPerBlock { + if numTx > domainmessage.MaxMassPerBlock { str := fmt.Sprintf("block contains too many transactions - "+ - "got %d, max %d", numTx, wire.MaxMassPerBlock) + "got %d, max %d", numTx, domainmessage.MaxMassPerBlock) return ruleError(ErrBlockMassTooHigh, str) } return nil @@ -608,7 +608,7 @@ func (dag *BlockDAG) checkBlockDuplicateTransactions(block *util.Block) error { } func (dag *BlockDAG) checkBlockDoubleSpends(block *util.Block) error { - usedOutpoints := make(map[wire.Outpoint]*daghash.TxID) + usedOutpoints := make(map[domainmessage.Outpoint]*daghash.TxID) transactions := block.Transactions() for _, tx := range transactions { for _, txIn := range tx.MsgTx().TxIn { @@ -631,7 +631,7 @@ func (dag *BlockDAG) checkBlockDoubleSpends(block *util.Block) error { // - BFFastAdd: No checks are performed. // // This function MUST be called with the dag state lock held (for writes). -func (dag *BlockDAG) checkBlockHeaderContext(header *wire.BlockHeader, bluestParent *blockNode, fastAdd bool) error { +func (dag *BlockDAG) checkBlockHeaderContext(header *domainmessage.BlockHeader, bluestParent *blockNode, fastAdd bool) error { if !fastAdd { if err := dag.validateDifficulty(header, bluestParent); err != nil { return err @@ -644,7 +644,7 @@ func (dag *BlockDAG) checkBlockHeaderContext(header *wire.BlockHeader, bluestPar return nil } -func validateMedianTime(dag *BlockDAG, header *wire.BlockHeader, bluestParent *blockNode) error { +func validateMedianTime(dag *BlockDAG, header *domainmessage.BlockHeader, bluestParent *blockNode) error { if !header.IsGenesis() { // Ensure the timestamp for the block header is not before the // median time of the last several blocks (medianTimeBlocks). @@ -658,7 +658,7 @@ func validateMedianTime(dag *BlockDAG, header *wire.BlockHeader, bluestParent *b return nil } -func (dag *BlockDAG) validateDifficulty(header *wire.BlockHeader, bluestParent *blockNode) error { +func (dag *BlockDAG) validateDifficulty(header *domainmessage.BlockHeader, bluestParent *blockNode) error { // Ensure the difficulty specified in the block header matches // the calculated difficulty based on the previous block and // difficulty retarget rules. @@ -674,7 +674,7 @@ func (dag *BlockDAG) validateDifficulty(header *wire.BlockHeader, bluestParent * } // validateParents validates that no parent is an ancestor of another parent, and no parent is finalized -func (dag *BlockDAG) validateParents(blockHeader *wire.BlockHeader, parents blockSet) error { +func (dag *BlockDAG) validateParents(blockHeader *domainmessage.BlockHeader, parents blockSet) error { for parentA := range parents { // isFinalized might be false-negative because node finality status is // updated in a separate goroutine. This is why later the block is @@ -765,9 +765,9 @@ func (dag *BlockDAG) validateAllTxsFinalized(block *util.Block, node *blockNode, func ensureNoDuplicateTx(utxoSet UTXOSet, transactions []*util.Tx) error { // Fetch utxos for all of the transaction ouputs in this block. // Typically, there will not be any utxos for any of the outputs. - fetchSet := make(map[wire.Outpoint]struct{}) + fetchSet := make(map[domainmessage.Outpoint]struct{}) for _, tx := range transactions { - prevOut := wire.Outpoint{TxID: *tx.ID()} + prevOut := domainmessage.Outpoint{TxID: *tx.ID()} for txOutIdx := range tx.MsgTx().TxOut { prevOut.Index = uint32(txOutIdx) fetchSet[prevOut] = struct{}{} @@ -874,7 +874,7 @@ func CheckTransactionInputsAndCalulateFee(tx *util.Tx, txBlueScore uint64, utxoS return txFeeInSompi, nil } -func validateCoinbaseMaturity(dagParams *dagconfig.Params, entry *UTXOEntry, txBlueScore uint64, txIn *wire.TxIn) error { +func validateCoinbaseMaturity(dagParams *dagconfig.Params, entry *UTXOEntry, txBlueScore uint64, txIn *domainmessage.TxIn) error { // Ensure the transaction is not spending coins which have not // yet reached the required coinbase maturity. if entry.IsCoinbase() { diff --git a/blockdag/validate_test.go b/blockdag/validate_test.go index 13f160e57..7ce962fb5 100644 --- a/blockdag/validate_test.go +++ b/blockdag/validate_test.go @@ -15,10 +15,10 @@ import ( "github.com/pkg/errors" "github.com/kaspanet/kaspad/dagconfig" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/subnetworkid" - "github.com/kaspanet/kaspad/wire" ) // TestSequenceLocksActive tests the SequenceLockActive function to ensure it @@ -196,8 +196,8 @@ func TestCheckBlockSanity(t *testing.T) { t.Errorf("CheckBlockSanity: unexpected return %s delay", delay) } - var invalidParentsOrderBlock = wire.MsgBlock{ - Header: wire.BlockHeader{ + var invalidParentsOrderBlock = domainmessage.MsgBlock{ + Header: domainmessage.BlockHeader{ Version: 0x10000000, ParentHashes: []*daghash.Hash{ { @@ -235,12 +235,12 @@ func TestCheckBlockSanity(t *testing.T) { Bits: 0x207fffff, Nonce: 0x1, }, - Transactions: []*wire.MsgTx{ + Transactions: []*domainmessage.MsgTx{ { Version: 1, - TxIn: []*wire.TxIn{ + TxIn: []*domainmessage.TxIn{ { - PreviousOutpoint: wire.Outpoint{ + PreviousOutpoint: domainmessage.Outpoint{ TxID: daghash.TxID{}, Index: 0xffffffff, }, @@ -252,7 +252,7 @@ func TestCheckBlockSanity(t *testing.T) { Sequence: math.MaxUint64, }, }, - TxOut: []*wire.TxOut{ + TxOut: []*domainmessage.TxOut{ { Value: 0x12a05f200, // 5000000000 ScriptPubKey: []byte{ @@ -265,9 +265,9 @@ func TestCheckBlockSanity(t *testing.T) { }, { Version: 1, - TxIn: []*wire.TxIn{ + TxIn: []*domainmessage.TxIn{ { - PreviousOutpoint: wire.Outpoint{ + PreviousOutpoint: domainmessage.Outpoint{ TxID: daghash.TxID([32]byte{ 0x03, 0x2e, 0x38, 0xe9, 0xc0, 0xa8, 0x4c, 0x60, 0x46, 0xd6, 0x87, 0xd1, 0x05, 0x56, 0xdc, 0xac, @@ -302,7 +302,7 @@ func TestCheckBlockSanity(t *testing.T) { Sequence: math.MaxUint64, }, }, - TxOut: []*wire.TxOut{ + TxOut: []*domainmessage.TxOut{ { Value: 0x2123e300, // 556000000 ScriptPubKey: []byte{ @@ -335,9 +335,9 @@ func TestCheckBlockSanity(t *testing.T) { }, { Version: 1, - TxIn: []*wire.TxIn{ + TxIn: []*domainmessage.TxIn{ { - PreviousOutpoint: wire.Outpoint{ + PreviousOutpoint: domainmessage.Outpoint{ TxID: daghash.TxID([32]byte{ 0xc3, 0x3e, 0xbf, 0xf2, 0xa7, 0x09, 0xf1, 0x3d, 0x9f, 0x9a, 0x75, 0x69, 0xab, 0x16, 0xa3, 0x27, @@ -371,7 +371,7 @@ func TestCheckBlockSanity(t *testing.T) { Sequence: math.MaxUint64, }, }, - TxOut: []*wire.TxOut{ + TxOut: []*domainmessage.TxOut{ { Value: 0xf4240, // 1000000 ScriptPubKey: []byte{ @@ -404,9 +404,9 @@ func TestCheckBlockSanity(t *testing.T) { }, { Version: 1, - TxIn: []*wire.TxIn{ + TxIn: []*domainmessage.TxIn{ { - PreviousOutpoint: wire.Outpoint{ + PreviousOutpoint: domainmessage.Outpoint{ TxID: daghash.TxID([32]byte{ 0x0b, 0x60, 0x72, 0xb3, 0x86, 0xd4, 0xa7, 0x73, 0x23, 0x52, 0x37, 0xf6, 0x4c, 0x11, 0x26, 0xac, @@ -441,7 +441,7 @@ func TestCheckBlockSanity(t *testing.T) { Sequence: math.MaxUint64, }, }, - TxOut: []*wire.TxOut{ + TxOut: []*domainmessage.TxOut{ { Value: 0xf4240, // 1000000 ScriptPubKey: []byte{ @@ -563,7 +563,7 @@ func TestValidateParents(t *testing.T) { bNode := nodeByMsgBlock(t, dag, b) cNode := nodeByMsgBlock(t, dag, c) - fakeBlockHeader := &wire.BlockHeader{ + fakeBlockHeader := &domainmessage.BlockHeader{ HashMerkleRoot: &daghash.ZeroHash, AcceptedIDMerkleRoot: &daghash.ZeroHash, UTXOCommitment: &daghash.ZeroHash, @@ -596,7 +596,7 @@ func TestCheckTransactionSanity(t *testing.T) { outputValue uint64 nodeSubnetworkID subnetworkid.SubnetworkID txSubnetworkData *txSubnetworkData - extraModificationsFunc func(*wire.MsgTx) + extraModificationsFunc func(*domainmessage.MsgTx) expectedErr error }{ {"good one", 1, 1, 1, *subnetworkid.SubnetworkIDNative, nil, nil, nil}, @@ -615,7 +615,7 @@ func TestCheckTransactionSanity(t *testing.T) { {"duplicate inputs", 2, 1, 1, *subnetworkid.SubnetworkIDNative, nil, - func(tx *wire.MsgTx) { tx.TxIn[1].PreviousOutpoint.Index = 0 }, + func(tx *domainmessage.MsgTx) { tx.TxIn[1].PreviousOutpoint.Index = 0 }, ruleError(ErrDuplicateTxInputs, "")}, {"1 input coinbase", 1, @@ -669,14 +669,14 @@ func TestCheckTransactionSanity(t *testing.T) { {"invalid payload hash", 1, 1, 0, subnetworkid.SubnetworkID{123}, &txSubnetworkData{&subnetworkid.SubnetworkID{123}, 0, []byte{1}}, - func(tx *wire.MsgTx) { + func(tx *domainmessage.MsgTx) { tx.PayloadHash = &daghash.Hash{} }, ruleError(ErrInvalidPayloadHash, "")}, {"invalid payload hash in native subnetwork", 1, 1, 0, *subnetworkid.SubnetworkIDNative, nil, - func(tx *wire.MsgTx) { + func(tx *domainmessage.MsgTx) { tx.PayloadHash = daghash.DoubleHashP(tx.Payload) }, ruleError(ErrInvalidPayloadHash, "")}, @@ -699,8 +699,8 @@ func TestCheckTransactionSanity(t *testing.T) { // Block100000 defines block 100,000 of the block DAG. It is used to // test Block operations. -var Block100000 = wire.MsgBlock{ - Header: wire.BlockHeader{ +var Block100000 = domainmessage.MsgBlock{ + Header: domainmessage.BlockHeader{ Version: 0x10000000, ParentHashes: []*daghash.Hash{ { @@ -733,12 +733,12 @@ var Block100000 = wire.MsgBlock{ Bits: 0x207fffff, Nonce: 1, }, - Transactions: []*wire.MsgTx{ + Transactions: []*domainmessage.MsgTx{ { Version: 1, - TxIn: []*wire.TxIn{ + TxIn: []*domainmessage.TxIn{ { - PreviousOutpoint: wire.Outpoint{ + PreviousOutpoint: domainmessage.Outpoint{ TxID: daghash.TxID{ 0x9b, 0x22, 0x59, 0x44, 0x66, 0xf0, 0xbe, 0x50, 0x7c, 0x1c, 0x8a, 0xf6, 0x06, 0x27, 0xe6, 0x33, @@ -751,7 +751,7 @@ var Block100000 = wire.MsgBlock{ Sequence: math.MaxUint64, }, }, - TxOut: []*wire.TxOut{ + TxOut: []*domainmessage.TxOut{ { Value: 0x12a05f200, // 5000000000 ScriptPubKey: []byte{ @@ -773,9 +773,9 @@ var Block100000 = wire.MsgBlock{ }, { Version: 1, - TxIn: []*wire.TxIn{ + TxIn: []*domainmessage.TxIn{ { - PreviousOutpoint: wire.Outpoint{ + PreviousOutpoint: domainmessage.Outpoint{ TxID: daghash.TxID{ 0x16, 0x5e, 0x38, 0xe8, 0xb3, 0x91, 0x45, 0x95, 0xd9, 0xc6, 0x41, 0xf3, 0xb8, 0xee, 0xc2, 0xf3, @@ -787,7 +787,7 @@ var Block100000 = wire.MsgBlock{ Sequence: math.MaxUint64, }, { - PreviousOutpoint: wire.Outpoint{ + PreviousOutpoint: domainmessage.Outpoint{ TxID: daghash.TxID{ 0x4b, 0xb0, 0x75, 0x35, 0xdf, 0xd5, 0x8e, 0x0b, 0x3c, 0xd6, 0x4f, 0xd7, 0x15, 0x52, 0x80, 0x87, @@ -803,9 +803,9 @@ var Block100000 = wire.MsgBlock{ }, { Version: 1, - TxIn: []*wire.TxIn{ + TxIn: []*domainmessage.TxIn{ { - PreviousOutpoint: wire.Outpoint{ + PreviousOutpoint: domainmessage.Outpoint{ TxID: daghash.TxID([32]byte{ 0x03, 0x2e, 0x38, 0xe9, 0xc0, 0xa8, 0x4c, 0x60, 0x46, 0xd6, 0x87, 0xd1, 0x05, 0x56, 0xdc, 0xac, @@ -840,7 +840,7 @@ var Block100000 = wire.MsgBlock{ Sequence: math.MaxUint64, }, }, - TxOut: []*wire.TxOut{ + TxOut: []*domainmessage.TxOut{ { Value: 0x2123e300, // 556000000 ScriptPubKey: []byte{ @@ -873,9 +873,9 @@ var Block100000 = wire.MsgBlock{ }, { Version: 1, - TxIn: []*wire.TxIn{ + TxIn: []*domainmessage.TxIn{ { - PreviousOutpoint: wire.Outpoint{ + PreviousOutpoint: domainmessage.Outpoint{ TxID: daghash.TxID([32]byte{ 0xc3, 0x3e, 0xbf, 0xf2, 0xa7, 0x09, 0xf1, 0x3d, 0x9f, 0x9a, 0x75, 0x69, 0xab, 0x16, 0xa3, 0x27, @@ -909,7 +909,7 @@ var Block100000 = wire.MsgBlock{ Sequence: math.MaxUint64, }, }, - TxOut: []*wire.TxOut{ + TxOut: []*domainmessage.TxOut{ { Value: 0xf4240, // 1000000 ScriptPubKey: []byte{ @@ -942,9 +942,9 @@ var Block100000 = wire.MsgBlock{ }, { Version: 1, - TxIn: []*wire.TxIn{ + TxIn: []*domainmessage.TxIn{ { - PreviousOutpoint: wire.Outpoint{ + PreviousOutpoint: domainmessage.Outpoint{ TxID: daghash.TxID([32]byte{ 0x0b, 0x60, 0x72, 0xb3, 0x86, 0xd4, 0xa7, 0x73, 0x23, 0x52, 0x37, 0xf6, 0x4c, 0x11, 0x26, 0xac, @@ -979,7 +979,7 @@ var Block100000 = wire.MsgBlock{ Sequence: math.MaxUint64, }, }, - TxOut: []*wire.TxOut{ + TxOut: []*domainmessage.TxOut{ { Value: 0xf4240, // 1000000 ScriptPubKey: []byte{ @@ -1001,8 +1001,8 @@ var Block100000 = wire.MsgBlock{ } // BlockWithWrongTxOrder defines invalid block 100,000 of the block DAG. -var BlockWithWrongTxOrder = wire.MsgBlock{ - Header: wire.BlockHeader{ +var BlockWithWrongTxOrder = domainmessage.MsgBlock{ + Header: domainmessage.BlockHeader{ Version: 1, ParentHashes: []*daghash.Hash{ { @@ -1040,12 +1040,12 @@ var BlockWithWrongTxOrder = wire.MsgBlock{ Bits: 0x207fffff, Nonce: 1, }, - Transactions: []*wire.MsgTx{ + Transactions: []*domainmessage.MsgTx{ { Version: 1, - TxIn: []*wire.TxIn{ + TxIn: []*domainmessage.TxIn{ { - PreviousOutpoint: wire.Outpoint{ + PreviousOutpoint: domainmessage.Outpoint{ TxID: daghash.TxID{ 0x9b, 0x22, 0x59, 0x44, 0x66, 0xf0, 0xbe, 0x50, 0x7c, 0x1c, 0x8a, 0xf6, 0x06, 0x27, 0xe6, 0x33, @@ -1058,7 +1058,7 @@ var BlockWithWrongTxOrder = wire.MsgBlock{ Sequence: math.MaxUint64, }, }, - TxOut: []*wire.TxOut{ + TxOut: []*domainmessage.TxOut{ { Value: 0x12a05f200, // 5000000000 ScriptPubKey: []byte{ @@ -1080,9 +1080,9 @@ var BlockWithWrongTxOrder = wire.MsgBlock{ }, { Version: 1, - TxIn: []*wire.TxIn{ + TxIn: []*domainmessage.TxIn{ { - PreviousOutpoint: wire.Outpoint{ + PreviousOutpoint: domainmessage.Outpoint{ TxID: daghash.TxID{ 0x16, 0x5e, 0x38, 0xe8, 0xb3, 0x91, 0x45, 0x95, 0xd9, 0xc6, 0x41, 0xf3, 0xb8, 0xee, 0xc2, 0xf3, @@ -1094,7 +1094,7 @@ var BlockWithWrongTxOrder = wire.MsgBlock{ Sequence: math.MaxUint64, }, { - PreviousOutpoint: wire.Outpoint{ + PreviousOutpoint: domainmessage.Outpoint{ TxID: daghash.TxID{ 0x4b, 0xb0, 0x75, 0x35, 0xdf, 0xd5, 0x8e, 0x0b, 0x3c, 0xd6, 0x4f, 0xd7, 0x15, 0x52, 0x80, 0x87, @@ -1110,9 +1110,9 @@ var BlockWithWrongTxOrder = wire.MsgBlock{ }, { Version: 1, - TxIn: []*wire.TxIn{ + TxIn: []*domainmessage.TxIn{ { - PreviousOutpoint: wire.Outpoint{ + PreviousOutpoint: domainmessage.Outpoint{ TxID: daghash.TxID([32]byte{ 0x03, 0x2e, 0x38, 0xe9, 0xc0, 0xa8, 0x4c, 0x60, 0x46, 0xd6, 0x87, 0xd1, 0x05, 0x56, 0xdc, 0xac, @@ -1147,7 +1147,7 @@ var BlockWithWrongTxOrder = wire.MsgBlock{ Sequence: math.MaxUint64, }, }, - TxOut: []*wire.TxOut{ + TxOut: []*domainmessage.TxOut{ { Value: 0x2123e300, // 556000000 ScriptPubKey: []byte{ @@ -1182,9 +1182,9 @@ var BlockWithWrongTxOrder = wire.MsgBlock{ }, { Version: 1, - TxIn: []*wire.TxIn{ + TxIn: []*domainmessage.TxIn{ { - PreviousOutpoint: wire.Outpoint{ + PreviousOutpoint: domainmessage.Outpoint{ TxID: daghash.TxID([32]byte{ 0xc3, 0x3e, 0xbf, 0xf2, 0xa7, 0x09, 0xf1, 0x3d, 0x9f, 0x9a, 0x75, 0x69, 0xab, 0x16, 0xa3, 0x27, @@ -1218,7 +1218,7 @@ var BlockWithWrongTxOrder = wire.MsgBlock{ Sequence: math.MaxUint64, }, }, - TxOut: []*wire.TxOut{ + TxOut: []*domainmessage.TxOut{ { Value: 0xf4240, // 1000000 ScriptPubKey: []byte{ @@ -1251,9 +1251,9 @@ var BlockWithWrongTxOrder = wire.MsgBlock{ }, { Version: 1, - TxIn: []*wire.TxIn{ + TxIn: []*domainmessage.TxIn{ { - PreviousOutpoint: wire.Outpoint{ + PreviousOutpoint: domainmessage.Outpoint{ TxID: daghash.TxID([32]byte{ 0x0b, 0x60, 0x72, 0xb3, 0x86, 0xd4, 0xa7, 0x73, 0x23, 0x52, 0x37, 0xf6, 0x4c, 0x11, 0x26, 0xac, @@ -1288,7 +1288,7 @@ var BlockWithWrongTxOrder = wire.MsgBlock{ Sequence: math.MaxUint64, }, }, - TxOut: []*wire.TxOut{ + TxOut: []*domainmessage.TxOut{ { Value: 0xf4240, // 1000000 ScriptPubKey: []byte{ diff --git a/cmd/addblock/import.go b/cmd/addblock/import.go index e465b7311..1290e9319 100644 --- a/cmd/addblock/import.go +++ b/cmd/addblock/import.go @@ -14,8 +14,8 @@ import ( "time" "github.com/kaspanet/kaspad/blockdag" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util" - "github.com/kaspanet/kaspad/wire" ) // importResults houses the stats and result as an import operation. @@ -68,10 +68,10 @@ func (bi *blockImporter) readBlock() ([]byte, error) { if err := binary.Read(bi.r, binary.LittleEndian, &blockLen); err != nil { return nil, err } - if blockLen > wire.MaxMessagePayload { + if blockLen > domainmessage.MaxMessagePayload { return nil, errors.Errorf("block payload of %d bytes is larger "+ "than the max allowed %d bytes", blockLen, - wire.MaxMessagePayload) + domainmessage.MaxMessagePayload) } serializedBlock := make([]byte, blockLen) diff --git a/cmd/kaspaminer/client.go b/cmd/kaspaminer/client.go index 8b03bfe2d..2b89e1a28 100644 --- a/cmd/kaspaminer/client.go +++ b/cmd/kaspaminer/client.go @@ -1,9 +1,9 @@ package main import ( + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/rpc/client" "github.com/kaspanet/kaspad/util" - "github.com/kaspanet/kaspad/wire" "github.com/pkg/errors" "io/ioutil" "time" @@ -19,7 +19,7 @@ func newMinerClient(connCfg *client.ConnConfig) (*minerClient, error) { onBlockAdded: make(chan struct{}, 1), } notificationHandlers := &client.NotificationHandlers{ - OnFilteredBlockAdded: func(_ uint64, header *wire.BlockHeader, + OnFilteredBlockAdded: func(_ uint64, header *domainmessage.BlockHeader, txs []*util.Tx) { minerClient.onBlockAdded <- struct{}{} }, diff --git a/cmd/txsigner/txsigner.go b/cmd/txsigner/txsigner.go index 9c1f4dd11..085ce4a98 100644 --- a/cmd/txsigner/txsigner.go +++ b/cmd/txsigner/txsigner.go @@ -5,9 +5,9 @@ import ( "encoding/hex" "fmt" "github.com/kaspanet/go-secp256k1" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/txscript" "github.com/kaspanet/kaspad/util" - "github.com/kaspanet/kaspad/wire" "github.com/pkg/errors" "os" ) @@ -58,12 +58,12 @@ func parsePrivateKey(privateKeyHex string) (*secp256k1.PrivateKey, error) { return secp256k1.DeserializePrivateKeyFromSlice(privateKeyBytes) } -func parseTransaction(transactionHex string) (*wire.MsgTx, error) { +func parseTransaction(transactionHex string) (*domainmessage.MsgTx, error) { serializedTx, err := hex.DecodeString(transactionHex) if err != nil { return nil, errors.Wrap(err, "couldn't decode transaction hex") } - var transaction wire.MsgTx + var transaction domainmessage.MsgTx err = transaction.Deserialize(bytes.NewReader(serializedTx)) return &transaction, err } @@ -81,7 +81,7 @@ func createScriptPubKey(publicKey *secp256k1.SchnorrPublicKey) ([]byte, error) { return scriptPubKey, err } -func signTransaction(transaction *wire.MsgTx, privateKey *secp256k1.PrivateKey, scriptPubKey []byte) error { +func signTransaction(transaction *domainmessage.MsgTx, privateKey *secp256k1.PrivateKey, scriptPubKey []byte) error { for i, transactionInput := range transaction.TxIn { signatureScript, err := txscript.SignatureScript(transaction, i, scriptPubKey, txscript.SigHashAll, privateKey, true) if err != nil { @@ -92,7 +92,7 @@ func signTransaction(transaction *wire.MsgTx, privateKey *secp256k1.PrivateKey, return nil } -func serializeTransaction(transaction *wire.MsgTx) (string, error) { +func serializeTransaction(transaction *domainmessage.MsgTx) (string, error) { buf := bytes.NewBuffer(make([]byte, 0, transaction.SerializeSize())) err := transaction.Serialize(buf) serializedTransaction := hex.EncodeToString(buf.Bytes()) diff --git a/dagconfig/genesis.go b/dagconfig/genesis.go index 0a266095c..4a283637d 100644 --- a/dagconfig/genesis.go +++ b/dagconfig/genesis.go @@ -5,13 +5,13 @@ package dagconfig import ( + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/mstime" "github.com/kaspanet/kaspad/util/subnetworkid" - "github.com/kaspanet/kaspad/wire" ) -var genesisTxOuts = []*wire.TxOut{} +var genesisTxOuts = []*domainmessage.TxOut{} var genesisTxPayload = []byte{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Blue score @@ -23,7 +23,7 @@ var genesisTxPayload = []byte{ // genesisCoinbaseTx is the coinbase transaction for the genesis blocks for // the main network. -var genesisCoinbaseTx = wire.NewSubnetworkMsgTx(1, []*wire.TxIn{}, genesisTxOuts, subnetworkid.SubnetworkIDCoinbase, 0, genesisTxPayload) +var genesisCoinbaseTx = domainmessage.NewSubnetworkMsgTx(1, []*domainmessage.TxIn{}, genesisTxOuts, subnetworkid.SubnetworkIDCoinbase, 0, genesisTxPayload) // genesisHash is the hash of the first block in the block DAG for the main // network (genesis block). @@ -45,8 +45,8 @@ var genesisMerkleRoot = daghash.Hash{ // genesisBlock defines the genesis block of the block DAG which serves as the // public transaction ledger for the main network. -var genesisBlock = wire.MsgBlock{ - Header: wire.BlockHeader{ +var genesisBlock = domainmessage.MsgBlock{ + Header: domainmessage.BlockHeader{ Version: 0x10000000, ParentHashes: []*daghash.Hash{}, HashMerkleRoot: &genesisMerkleRoot, @@ -56,10 +56,10 @@ var genesisBlock = wire.MsgBlock{ Bits: 0x207fffff, Nonce: 0x1, }, - Transactions: []*wire.MsgTx{genesisCoinbaseTx}, + Transactions: []*domainmessage.MsgTx{genesisCoinbaseTx}, } -var devnetGenesisTxOuts = []*wire.TxOut{} +var devnetGenesisTxOuts = []*domainmessage.TxOut{} var devnetGenesisTxPayload = []byte{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Blue score @@ -72,7 +72,7 @@ var devnetGenesisTxPayload = []byte{ // devnetGenesisCoinbaseTx is the coinbase transaction for the genesis blocks for // the development network. -var devnetGenesisCoinbaseTx = wire.NewSubnetworkMsgTx(1, []*wire.TxIn{}, devnetGenesisTxOuts, subnetworkid.SubnetworkIDCoinbase, 0, devnetGenesisTxPayload) +var devnetGenesisCoinbaseTx = domainmessage.NewSubnetworkMsgTx(1, []*domainmessage.TxIn{}, devnetGenesisTxOuts, subnetworkid.SubnetworkIDCoinbase, 0, devnetGenesisTxPayload) // devGenesisHash is the hash of the first block in the block DAG for the development // network (genesis block). @@ -94,8 +94,8 @@ var devnetGenesisMerkleRoot = daghash.Hash{ // devnetGenesisBlock defines the genesis block of the block DAG which serves as the // public transaction ledger for the development network. -var devnetGenesisBlock = wire.MsgBlock{ - Header: wire.BlockHeader{ +var devnetGenesisBlock = domainmessage.MsgBlock{ + Header: domainmessage.BlockHeader{ Version: 0x10000000, ParentHashes: []*daghash.Hash{}, HashMerkleRoot: &devnetGenesisMerkleRoot, @@ -105,10 +105,10 @@ var devnetGenesisBlock = wire.MsgBlock{ Bits: 0x1e7fffff, Nonce: 0x10bb, }, - Transactions: []*wire.MsgTx{devnetGenesisCoinbaseTx}, + Transactions: []*domainmessage.MsgTx{devnetGenesisCoinbaseTx}, } -var regtestGenesisTxOuts = []*wire.TxOut{} +var regtestGenesisTxOuts = []*domainmessage.TxOut{} var regtestGenesisTxPayload = []byte{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Blue score @@ -121,7 +121,7 @@ var regtestGenesisTxPayload = []byte{ // regtestGenesisCoinbaseTx is the coinbase transaction for // the genesis blocks for the regtest network. -var regtestGenesisCoinbaseTx = wire.NewSubnetworkMsgTx(1, []*wire.TxIn{}, regtestGenesisTxOuts, subnetworkid.SubnetworkIDCoinbase, 0, regtestGenesisTxPayload) +var regtestGenesisCoinbaseTx = domainmessage.NewSubnetworkMsgTx(1, []*domainmessage.TxIn{}, regtestGenesisTxOuts, subnetworkid.SubnetworkIDCoinbase, 0, regtestGenesisTxPayload) // devGenesisHash is the hash of the first block in the block DAG for the development // network (genesis block). @@ -143,8 +143,8 @@ var regtestGenesisMerkleRoot = daghash.Hash{ // regtestGenesisBlock defines the genesis block of the block DAG which serves as the // public transaction ledger for the development network. -var regtestGenesisBlock = wire.MsgBlock{ - Header: wire.BlockHeader{ +var regtestGenesisBlock = domainmessage.MsgBlock{ + Header: domainmessage.BlockHeader{ Version: 0x10000000, ParentHashes: []*daghash.Hash{}, HashMerkleRoot: ®testGenesisMerkleRoot, @@ -154,10 +154,10 @@ var regtestGenesisBlock = wire.MsgBlock{ Bits: 0x207fffff, Nonce: 0x0, }, - Transactions: []*wire.MsgTx{regtestGenesisCoinbaseTx}, + Transactions: []*domainmessage.MsgTx{regtestGenesisCoinbaseTx}, } -var simnetGenesisTxOuts = []*wire.TxOut{} +var simnetGenesisTxOuts = []*domainmessage.TxOut{} var simnetGenesisTxPayload = []byte{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Blue score @@ -169,7 +169,7 @@ var simnetGenesisTxPayload = []byte{ } // simnetGenesisCoinbaseTx is the coinbase transaction for the simnet genesis block. -var simnetGenesisCoinbaseTx = wire.NewSubnetworkMsgTx(1, []*wire.TxIn{}, simnetGenesisTxOuts, subnetworkid.SubnetworkIDCoinbase, 0, simnetGenesisTxPayload) +var simnetGenesisCoinbaseTx = domainmessage.NewSubnetworkMsgTx(1, []*domainmessage.TxIn{}, simnetGenesisTxOuts, subnetworkid.SubnetworkIDCoinbase, 0, simnetGenesisTxPayload) // simnetGenesisHash is the hash of the first block in the block DAG for // the simnet (genesis block). @@ -191,8 +191,8 @@ var simnetGenesisMerkleRoot = daghash.Hash{ // simnetGenesisBlock defines the genesis block of the block DAG which serves as the // public transaction ledger for the development network. -var simnetGenesisBlock = wire.MsgBlock{ - Header: wire.BlockHeader{ +var simnetGenesisBlock = domainmessage.MsgBlock{ + Header: domainmessage.BlockHeader{ Version: 0x10000000, ParentHashes: []*daghash.Hash{}, HashMerkleRoot: &simnetGenesisMerkleRoot, @@ -202,10 +202,10 @@ var simnetGenesisBlock = wire.MsgBlock{ Bits: 0x207fffff, Nonce: 0x0, }, - Transactions: []*wire.MsgTx{simnetGenesisCoinbaseTx}, + Transactions: []*domainmessage.MsgTx{simnetGenesisCoinbaseTx}, } -var testnetGenesisTxOuts = []*wire.TxOut{} +var testnetGenesisTxOuts = []*domainmessage.TxOut{} var testnetGenesisTxPayload = []byte{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Blue score @@ -215,7 +215,7 @@ var testnetGenesisTxPayload = []byte{ } // testnetGenesisCoinbaseTx is the coinbase transaction for the testnet genesis block. -var testnetGenesisCoinbaseTx = wire.NewSubnetworkMsgTx(1, []*wire.TxIn{}, testnetGenesisTxOuts, subnetworkid.SubnetworkIDCoinbase, 0, testnetGenesisTxPayload) +var testnetGenesisCoinbaseTx = domainmessage.NewSubnetworkMsgTx(1, []*domainmessage.TxIn{}, testnetGenesisTxOuts, subnetworkid.SubnetworkIDCoinbase, 0, testnetGenesisTxPayload) // testnetGenesisHash is the hash of the first block in the block DAG for the test // network (genesis block). @@ -237,8 +237,8 @@ var testnetGenesisMerkleRoot = daghash.Hash{ // testnetGenesisBlock defines the genesis block of the block DAG which serves as the // public transaction ledger for testnet. -var testnetGenesisBlock = wire.MsgBlock{ - Header: wire.BlockHeader{ +var testnetGenesisBlock = domainmessage.MsgBlock{ + Header: domainmessage.BlockHeader{ Version: 0x10000000, ParentHashes: []*daghash.Hash{}, HashMerkleRoot: &testnetGenesisMerkleRoot, @@ -248,5 +248,5 @@ var testnetGenesisBlock = wire.MsgBlock{ Bits: 0x1e7fffff, Nonce: 0x162ca, }, - Transactions: []*wire.MsgTx{testnetGenesisCoinbaseTx}, + Transactions: []*domainmessage.MsgTx{testnetGenesisCoinbaseTx}, } diff --git a/dagconfig/genesis_test.go b/dagconfig/genesis_test.go index 367c1a062..85324cf8d 100644 --- a/dagconfig/genesis_test.go +++ b/dagconfig/genesis_test.go @@ -145,7 +145,7 @@ func TestDevnetGenesisBlock(t *testing.T) { } } -// genesisBlockBytes are the wire encoded bytes for the genesis block of the +// genesisBlockBytes are the encoded bytes for the genesis block of the // main network as of protocol version 1. var genesisBlockBytes = []byte{ 0x00, 0x00, 0x00, 0x10, 0x00, 0xca, 0x85, 0x56, 0x27, 0xc7, 0x6a, 0xb5, 0x7a, 0x26, 0x1d, 0x63, @@ -165,7 +165,7 @@ var genesisBlockBytes = []byte{ 0x30, 0xcd, 0x5a, 0x4b, 0x87, } -// regtestGenesisBlockBytes are the wire encoded bytes for the genesis block of +// regtestGenesisBlockBytes are the encoded bytes for the genesis block of // the regression test network as of protocol version 1. var regtestGenesisBlockBytes = []byte{ 0x00, 0x00, 0x00, 0x10, 0x00, 0x1e, 0x08, 0xae, 0x1f, 0x43, 0xf5, 0xfc, 0x24, 0xe6, 0xec, 0x54, @@ -186,7 +186,7 @@ var regtestGenesisBlockBytes = []byte{ 0x73, 0x74, } -// testnetGenesisBlockBytes are the wire encoded bytes for the genesis block of +// testnetGenesisBlockBytes are the encoded bytes for the genesis block of // the test network as of protocol version 1. var testnetGenesisBlockBytes = []byte{ 0x00, 0x00, 0x00, 0x10, 0x00, 0xa0, 0xa1, 0x3d, 0xfd, 0x86, 0x41, 0x35, 0xc8, 0xbd, 0xbb, 0xe6, @@ -205,7 +205,7 @@ var testnetGenesisBlockBytes = []byte{ 0x61, 0x73, 0x70, 0x61, 0x2d, 0x74, 0x65, 0x73, 0x74, 0x6e, 0x65, 0x74, } -// simnetGenesisBlockBytes are the wire encoded bytes for the genesis block of +// simnetGenesisBlockBytes are the encoded bytes for the genesis block of // the simulation test network as of protocol version 1. var simnetGenesisBlockBytes = []byte{ 0x00, 0x00, 0x00, 0x10, 0x00, 0x47, 0x52, 0xc7, 0x23, 0x70, 0x4d, 0x89, 0x17, 0xbd, 0x44, 0x26, @@ -226,7 +226,7 @@ var simnetGenesisBlockBytes = []byte{ 0x74, } -// devnetGenesisBlockBytes are the wire encoded bytes for the genesis block of +// devnetGenesisBlockBytes are the encoded bytes for the genesis block of // the development network as of protocol version 1. var devnetGenesisBlockBytes = []byte{ 0x00, 0x00, 0x00, 0x10, 0x00, 0x68, 0x60, 0xe7, 0x77, 0x47, 0x74, 0x7f, 0xd5, 0x55, 0x58, 0x8a, diff --git a/dagconfig/params.go b/dagconfig/params.go index fd105bb0d..fc0875bd6 100644 --- a/dagconfig/params.go +++ b/dagconfig/params.go @@ -14,8 +14,8 @@ import ( "github.com/kaspanet/kaspad/util" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) // These variables are the DAG proof-of-work limit parameters for each default @@ -101,7 +101,7 @@ type Params struct { Name string // Net defines the magic bytes used to identify the network. - Net wire.KaspaNet + Net domainmessage.KaspaNet // RPCPort defines the rpc server port RPCPort string @@ -114,7 +114,7 @@ type Params struct { DNSSeeds []string // GenesisBlock defines the first block of the DAG. - GenesisBlock *wire.MsgBlock + GenesisBlock *domainmessage.MsgBlock // GenesisHash is the starting block hash. GenesisHash *daghash.Hash @@ -190,7 +190,7 @@ func (p *Params) NormalizeRPCServerAddress(addr string) (string, error) { var MainnetParams = Params{ K: ghostdagK, Name: "mainnet", - Net: wire.Mainnet, + Net: domainmessage.Mainnet, RPCPort: "16110", DefaultPort: "16111", DNSSeeds: []string{"dnsseed.kas.pa"}, @@ -243,7 +243,7 @@ var MainnetParams = Params{ var RegressionNetParams = Params{ K: ghostdagK, Name: "regtest", - Net: wire.Regtest, + Net: domainmessage.Regtest, RPCPort: "16210", DefaultPort: "16211", DNSSeeds: []string{}, @@ -294,7 +294,7 @@ var RegressionNetParams = Params{ var TestnetParams = Params{ K: ghostdagK, Name: "testnet", - Net: wire.Testnet, + Net: domainmessage.Testnet, RPCPort: "16210", DefaultPort: "16211", DNSSeeds: []string{"testnet-dnsseed.kas.pa"}, @@ -351,7 +351,7 @@ var TestnetParams = Params{ var SimnetParams = Params{ K: ghostdagK, Name: "simnet", - Net: wire.Simnet, + Net: domainmessage.Simnet, RPCPort: "16510", DefaultPort: "16511", DNSSeeds: []string{}, // NOTE: There must NOT be any seeds. @@ -400,7 +400,7 @@ var SimnetParams = Params{ var DevnetParams = Params{ K: ghostdagK, Name: "devnet", - Net: wire.Devnet, + Net: domainmessage.Devnet, RPCPort: "16610", DefaultPort: "16611", DNSSeeds: []string{}, // NOTE: There must NOT be any seeds. @@ -455,7 +455,7 @@ var ( ) var ( - registeredNets = make(map[wire.KaspaNet]struct{}) + registeredNets = make(map[domainmessage.KaspaNet]struct{}) ) // Register registers the network parameters for a Kaspa network. This may diff --git a/dnsseed/seed.go b/dnsseed/seed.go index 5cfbd3e8a..b0fa15343 100644 --- a/dnsseed/seed.go +++ b/dnsseed/seed.go @@ -16,7 +16,7 @@ import ( "github.com/kaspanet/kaspad/util/subnetworkid" "github.com/kaspanet/kaspad/dagconfig" - "github.com/kaspanet/kaspad/wire" + "github.com/kaspanet/kaspad/domainmessage" ) const ( @@ -34,13 +34,13 @@ const ( // OnSeed is the signature of the callback function which is invoked when DNS // seeding is successful. -type OnSeed func(addrs []*wire.NetAddress) +type OnSeed func(addrs []*domainmessage.NetAddress) // LookupFunc is the signature of the DNS lookup function. type LookupFunc func(string) ([]net.IP, error) // SeedFromDNS uses DNS seeding to populate the address manager with peers. -func SeedFromDNS(dagParams *dagconfig.Params, customSeed string, reqServices wire.ServiceFlag, includeAllSubnetworks bool, +func SeedFromDNS(dagParams *dagconfig.Params, customSeed string, reqServices domainmessage.ServiceFlag, includeAllSubnetworks bool, subnetworkID *subnetworkid.SubnetworkID, lookupFn LookupFunc, seedFn OnSeed) { var dnsSeeds []string @@ -52,7 +52,7 @@ func SeedFromDNS(dagParams *dagconfig.Params, customSeed string, reqServices wir for _, dnsseed := range dnsSeeds { var host string - if reqServices == wire.SFNodeNetwork { + if reqServices == domainmessage.SFNodeNetwork { host = dnsseed } else { host = fmt.Sprintf("%c%x.%s", ServiceFlagPrefixChar, uint64(reqServices), dnsseed) @@ -81,11 +81,11 @@ func SeedFromDNS(dagParams *dagconfig.Params, customSeed string, reqServices wir if numPeers == 0 { return } - addresses := make([]*wire.NetAddress, len(seedPeers)) + addresses := make([]*domainmessage.NetAddress, len(seedPeers)) // if this errors then we have *real* problems intPort, _ := strconv.Atoi(dagParams.DefaultPort) for i, peer := range seedPeers { - addresses[i] = wire.NewNetAddressTimestamp( + addresses[i] = domainmessage.NewNetAddressTimestamp( // seed with addresses from a time randomly selected // between 3 and 7 days ago. mstime.Now().Add(-1*time.Second*time.Duration(secondsIn3Days+ diff --git a/wire/README.md b/domainmessage/README.md similarity index 97% rename from wire/README.md rename to domainmessage/README.md index 2ef65cb85..373d6993c 100644 --- a/wire/README.md +++ b/domainmessage/README.md @@ -36,7 +36,7 @@ to a remote node running a kaspa peer. Example syntax is: // Reads and validates the next kaspa message from conn using the // protocol version pver and the kaspa network kaspanet. The returns - // are a wire.Message, a []byte which contains the unmarshalled + // are a domainmessage.Message, a []byte which contains the unmarshalled // raw payload, and a possible error. msg, rawPayload, err := wire.ReadMessage(conn, pver, kaspanet) if err != nil { diff --git a/wire/bench_test.go b/domainmessage/bench_test.go similarity index 99% rename from wire/bench_test.go rename to domainmessage/bench_test.go index aa29719f7..636f130ab 100644 --- a/wire/bench_test.go +++ b/domainmessage/bench_test.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "bytes" diff --git a/wire/blockheader.go b/domainmessage/blockheader.go similarity index 94% rename from wire/blockheader.go rename to domainmessage/blockheader.go index 023a05507..e20369322 100644 --- a/wire/blockheader.go +++ b/domainmessage/blockheader.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "bytes" @@ -82,7 +82,7 @@ func (h *BlockHeader) IsGenesis() bool { // KaspaDecode decodes r using the kaspa protocol encoding into the receiver. // This is part of the Message interface implementation. // See Deserialize for decoding block headers stored to disk, such as in a -// database, as opposed to decoding block headers from the wire. +// database, as opposed to decoding block headers from the domainmessage. func (h *BlockHeader) KaspaDecode(r io.Reader, pver uint32) error { return readBlockHeader(r, pver, h) } @@ -90,7 +90,7 @@ func (h *BlockHeader) KaspaDecode(r io.Reader, pver uint32) error { // KaspaEncode encodes the receiver to w using the kaspa protocol encoding. // This is part of the Message interface implementation. // See Serialize for encoding block headers to be stored to disk, such as in a -// database, as opposed to encoding block headers for the wire. +// database, as opposed to encoding block headers for the domainmessage. func (h *BlockHeader) KaspaEncode(w io.Writer, pver uint32) error { return writeBlockHeader(w, pver, h) } @@ -99,7 +99,7 @@ func (h *BlockHeader) KaspaEncode(w io.Writer, pver uint32) error { // that is suitable for long-term storage such as a database while respecting // the Version field. func (h *BlockHeader) Deserialize(r io.Reader) error { - // At the current time, there is no difference between the wire encoding + // At the current time, there is no difference between the domainmessage encoding // at protocol version 0 and the stable long-term storage format. As // a result, make use of readBlockHeader. return readBlockHeader(r, 0, h) @@ -109,7 +109,7 @@ func (h *BlockHeader) Deserialize(r io.Reader) error { // that is suitable for long-term storage such as a database while respecting // the Version field. func (h *BlockHeader) Serialize(w io.Writer) error { - // At the current time, there is no difference between the wire encoding + // At the current time, there is no difference between the domainmessage encoding // at protocol version 0 and the stable long-term storage format. As // a result, make use of writeBlockHeader. return writeBlockHeader(w, 0, h) @@ -143,7 +143,7 @@ func NewBlockHeader(version int32, parentHashes []*daghash.Hash, hashMerkleRoot // readBlockHeader reads a kaspa block header from r. See Deserialize for // decoding block headers stored to disk, such as in a database, as opposed to -// decoding from the wire. +// decoding from the domainmessage. func readBlockHeader(r io.Reader, pver uint32, bh *BlockHeader) error { var numParentBlocks byte err := readElements(r, &bh.Version, &numParentBlocks) @@ -169,7 +169,7 @@ func readBlockHeader(r io.Reader, pver uint32, bh *BlockHeader) error { // writeBlockHeader writes a kaspa block header to w. See Serialize for // encoding block headers to be stored to disk, such as in a database, as -// opposed to encoding for the wire. +// opposed to encoding for the domainmessage. func writeBlockHeader(w io.Writer, pver uint32, bh *BlockHeader) error { timestamp := bh.Timestamp.UnixMilliseconds() if err := writeElements(w, bh.Version, bh.NumParentBlocks()); err != nil { diff --git a/wire/blockheader_test.go b/domainmessage/blockheader_test.go similarity index 95% rename from wire/blockheader_test.go rename to domainmessage/blockheader_test.go index 852e64ff4..8dd8d0265 100644 --- a/wire/blockheader_test.go +++ b/domainmessage/blockheader_test.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "bytes" @@ -47,9 +47,9 @@ func TestBlockHeader(t *testing.T) { } } -// TestBlockHeaderWire tests the BlockHeader wire encode and decode for various +// TestBlockHeaderEncoding tests the BlockHeader domainmessage encode and decode for various // protocol versions. -func TestBlockHeaderWire(t *testing.T) { +func TestBlockHeaderEncoding(t *testing.T) { nonce := uint64(123123) // 0x000000000001e0f3 pver := ProtocolVersion @@ -66,7 +66,7 @@ func TestBlockHeaderWire(t *testing.T) { Nonce: nonce, } - // baseBlockHdrEncoded is the wire encoded bytes of baseBlockHdr. + // baseBlockHdrEncoded is the domainmessage encoded bytes of baseBlockHdr. baseBlockHdrEncoded := []byte{ 0x01, 0x00, 0x00, 0x00, // Version 1 0x02, // NumParentBlocks @@ -98,8 +98,8 @@ func TestBlockHeaderWire(t *testing.T) { tests := []struct { in *BlockHeader // Data to encode out *BlockHeader // Expected decoded data - buf []byte // Wire encoding - pver uint32 // Protocol version for wire encoding + buf []byte // Encoded data + pver uint32 // Protocol version for domainmessage encoding }{ // Latest protocol version. { @@ -112,7 +112,7 @@ func TestBlockHeaderWire(t *testing.T) { t.Logf("Running %d tests", len(tests)) for i, test := range tests { - // Encode to wire format. + // Encode to domainmessage format. var buf bytes.Buffer err := writeBlockHeader(&buf, test.pver, test.in) if err != nil { @@ -137,7 +137,7 @@ func TestBlockHeaderWire(t *testing.T) { continue } - // Decode the block header from wire format. + // Decode the block header from domainmessage format. var bh BlockHeader rbuf := bytes.NewReader(test.buf) err = readBlockHeader(rbuf, test.pver, &bh) @@ -182,7 +182,7 @@ func TestBlockHeaderSerialize(t *testing.T) { Nonce: nonce, } - // baseBlockHdrEncoded is the wire encoded bytes of baseBlockHdr. + // baseBlockHdrEncoded is the domainmessage encoded bytes of baseBlockHdr. baseBlockHdrEncoded := []byte{ 0x01, 0x00, 0x00, 0x00, // Version 1 0x02, // NumParentBlocks diff --git a/wire/common.go b/domainmessage/common.go similarity index 97% rename from wire/common.go rename to domainmessage/common.go index aaec26edf..73206dc66 100644 --- a/wire/common.go +++ b/domainmessage/common.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "encoding/binary" @@ -20,6 +20,9 @@ import ( // MaxVarIntPayload is the maximum payload size for a variable length integer. const MaxVarIntPayload = 9 +// MaxInvPerMsg is the maximum number of inventory vectors that can be in any type of kaspa inv message. +const MaxInvPerMsg = 1 << 17 + var ( // littleEndian is a convenience variable since binary.LittleEndian is // quite long. @@ -160,14 +163,6 @@ func ReadElement(r io.Reader, element interface{}) error { *e = ServiceFlag(rv) return nil - case *InvType: - rv, err := binaryserializer.Uint32(r, littleEndian) - if err != nil { - return err - } - *e = InvType(rv) - return nil - case *KaspaNet: rv, err := binaryserializer.Uint32(r, littleEndian) if err != nil { @@ -292,13 +287,6 @@ func WriteElement(w io.Writer, element interface{}) error { } return nil - case InvType: - err := binaryserializer.PutUint32(w, littleEndian, uint32(e)) - if err != nil { - return err - } - return nil - case KaspaNet: err := binaryserializer.PutUint32(w, littleEndian, uint32(e)) if err != nil { diff --git a/wire/common_test.go b/domainmessage/common_test.go similarity index 87% rename from wire/common_test.go rename to domainmessage/common_test.go index a5a40fc27..25c25596a 100644 --- a/wire/common_test.go +++ b/domainmessage/common_test.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "bytes" @@ -57,13 +57,13 @@ var exampleUTXOCommitment = &daghash.Hash{ 0x65, 0x9C, 0x79, 0x3C, 0xE3, 0x70, 0xD9, 0x5F, } -// TestElementWire tests wire encode and decode for various element types. This +// TestElementEncoding tests domainmessage encode and decode for various element types. This // is mainly to test the "fast" paths in readElement and writeElement which use // type assertions to avoid reflection when possible. -func TestElementWire(t *testing.T) { +func TestElementEncoding(t *testing.T) { tests := []struct { in interface{} // Value to encode - buf []byte // Wire encoding + buf []byte // Encoded value }{ {int32(1), []byte{0x01, 0x00, 0x00, 0x00}}, {uint32(256), []byte{0x00, 0x01, 0x00, 0x00}}, @@ -121,10 +121,6 @@ func TestElementWire(t *testing.T) { ServiceFlag(SFNodeNetwork), []byte{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, }, - { - InvType(InvTypeTx), - []byte{0x01, 0x00, 0x00, 0x00}, - }, { KaspaNet(Mainnet), []byte{0x1d, 0xf7, 0xdc, 0x3d}, @@ -133,7 +129,7 @@ func TestElementWire(t *testing.T) { t.Logf("Running %d tests", len(tests)) for i, test := range tests { - // Write to wire format. + // Write to domainmessage format. var buf bytes.Buffer err := WriteElement(&buf, test.in) if err != nil { @@ -146,7 +142,7 @@ func TestElementWire(t *testing.T) { continue } - // Read from wire format. + // Read from domainmessage format. rbuf := bytes.NewReader(test.buf) val := test.in if reflect.ValueOf(test.in).Kind() != reflect.Ptr { @@ -169,9 +165,9 @@ func TestElementWire(t *testing.T) { } } -// TestElementWireErrors performs negative tests against wire encode and decode +// TestElementEncodingErrors performs negative tests against domainmessage encode and decode // of various element types to confirm error paths work correctly. -func TestElementWireErrors(t *testing.T) { +func TestElementEncodingErrors(t *testing.T) { type writeElementReflect int32 tests := []struct { @@ -206,7 +202,6 @@ func TestElementWireErrors(t *testing.T) { 0, io.ErrShortWrite, io.EOF, }, {ServiceFlag(SFNodeNetwork), 0, io.ErrShortWrite, io.EOF}, - {InvType(InvTypeTx), 0, io.ErrShortWrite, io.EOF}, {KaspaNet(Mainnet), 0, io.ErrShortWrite, io.EOF}, // Type with no supported encoding. {writeElementReflect(0), 0, errNoEncodingForType, errNoEncodingForType}, @@ -214,7 +209,7 @@ func TestElementWireErrors(t *testing.T) { t.Logf("Running %d tests", len(tests)) for i, test := range tests { - // Encode to wire format. + // Encode to domainmessage format. w := newFixedWriter(test.max) err := WriteElement(w, test.in) if !errors.Is(err, test.writeErr) { @@ -223,7 +218,7 @@ func TestElementWireErrors(t *testing.T) { continue } - // Decode from wire format. + // Decode from domainmessage format. r := newFixedReader(test.max, nil) val := test.in if reflect.ValueOf(test.in).Kind() != reflect.Ptr { @@ -238,11 +233,11 @@ func TestElementWireErrors(t *testing.T) { } } -// TestVarIntWire tests wire encode and decode for variable length integers. -func TestVarIntWire(t *testing.T) { +// TestVarIntEncoding tests domainmessage encode and decode for variable length integers. +func TestVarIntEncoding(t *testing.T) { tests := []struct { value uint64 // Value to encode - buf []byte // Wire encoding + buf []byte // Encoded value }{ // Latest protocol version. // Single byte @@ -271,7 +266,7 @@ func TestVarIntWire(t *testing.T) { t.Logf("Running %d tests", len(tests)) for i, test := range tests { - // Encode to wire format. + // Encode to domainmessage format. buf := &bytes.Buffer{} err := WriteVarInt(buf, test.value) if err != nil { @@ -284,7 +279,7 @@ func TestVarIntWire(t *testing.T) { continue } - // Decode from wire format. + // Decode from domainmessage format. rbuf := bytes.NewReader(test.buf) val, err := ReadVarInt(rbuf) if err != nil { @@ -299,12 +294,12 @@ func TestVarIntWire(t *testing.T) { } } -// TestVarIntWireErrors performs negative tests against wire encode and decode +// TestVarIntEncodingErrors performs negative tests against domainmessage encode and decode // of variable length integers to confirm error paths work correctly. -func TestVarIntWireErrors(t *testing.T) { +func TestVarIntEncodingErrors(t *testing.T) { tests := []struct { in uint64 // Value to encode - buf []byte // Wire encoding + buf []byte // Encoded value max int // Max size of fixed buffer to induce errors writeErr error // Expected write error readErr error // Expected read error @@ -324,7 +319,7 @@ func TestVarIntWireErrors(t *testing.T) { t.Logf("Running %d tests", len(tests)) for i, test := range tests { - // Encode to wire format. + // Encode to domainmessage format. w := newFixedWriter(test.max) err := WriteVarInt(w, test.in) if !errors.Is(err, test.writeErr) { @@ -333,7 +328,7 @@ func TestVarIntWireErrors(t *testing.T) { continue } - // Decode from wire format. + // Decode from domainmessage format. r := newFixedReader(test.max, test.buf) _, err = ReadVarInt(r) if !errors.Is(err, test.readErr) { @@ -352,7 +347,7 @@ func TestVarIntNonCanonical(t *testing.T) { tests := []struct { name string // Test name for easier identification in []byte // Value to decode - pver uint32 // Protocol version for wire encoding + pver uint32 // Protocol version for domainmessage encoding }{ { "0 encoded with 3 bytes", []byte{0xfd, 0x00, 0x00}, @@ -384,7 +379,7 @@ func TestVarIntNonCanonical(t *testing.T) { t.Logf("Running %d tests", len(tests)) for i, test := range tests { - // Decode from wire format. + // Decode from domainmessage format. rbuf := bytes.NewReader(test.in) val, err := ReadVarInt(rbuf) if msgErr := &(MessageError{}); !errors.As(err, &msgErr) { @@ -400,7 +395,7 @@ func TestVarIntNonCanonical(t *testing.T) { } } -// TestVarIntWire tests the serialize size for variable length integers. +// TestVarIntEncoding tests the serialize size for variable length integers. func TestVarIntSerializeSize(t *testing.T) { tests := []struct { val uint64 // Value to get the serialized size for @@ -435,8 +430,8 @@ func TestVarIntSerializeSize(t *testing.T) { } } -// TestVarStringWire tests wire encode and decode for variable length strings. -func TestVarStringWire(t *testing.T) { +// TestVarStringEncoding tests domainmessage encode and decode for variable length strings. +func TestVarStringEncoding(t *testing.T) { pver := ProtocolVersion // str256 is a string that takes a 2-byte varint to encode. @@ -445,8 +440,8 @@ func TestVarStringWire(t *testing.T) { tests := []struct { in string // String to encode out string // String to decoded value - buf []byte // Wire encoding - pver uint32 // Protocol version for wire encoding + buf []byte // Encoded value + pver uint32 // Protocol version for domainmessage encoding }{ // Latest protocol version. // Empty string @@ -459,7 +454,7 @@ func TestVarStringWire(t *testing.T) { t.Logf("Running %d tests", len(tests)) for i, test := range tests { - // Encode to wire format. + // Encode to domainmessage format. var buf bytes.Buffer err := WriteVarString(&buf, test.in) if err != nil { @@ -472,7 +467,7 @@ func TestVarStringWire(t *testing.T) { continue } - // Decode from wire format. + // Decode from domainmessage format. rbuf := bytes.NewReader(test.buf) val, err := ReadVarString(rbuf, test.pver) if err != nil { @@ -487,9 +482,9 @@ func TestVarStringWire(t *testing.T) { } } -// TestVarStringWireErrors performs negative tests against wire encode and +// TestVarStringEncodingErrors performs negative tests against domainmessage encode and // decode of variable length strings to confirm error paths work correctly. -func TestVarStringWireErrors(t *testing.T) { +func TestVarStringEncodingErrors(t *testing.T) { pver := ProtocolVersion // str256 is a string that takes a 2-byte varint to encode. @@ -497,8 +492,8 @@ func TestVarStringWireErrors(t *testing.T) { tests := []struct { in string // Value to encode - buf []byte // Wire encoding - pver uint32 // Protocol version for wire encoding + buf []byte // Encoded value + pver uint32 // Protocol version for domainmessage encoding max int // Max size of fixed buffer to induce errors writeErr error // Expected write error readErr error // Expected read error @@ -514,7 +509,7 @@ func TestVarStringWireErrors(t *testing.T) { t.Logf("Running %d tests", len(tests)) for i, test := range tests { - // Encode to wire format. + // Encode to domainmessage format. w := newFixedWriter(test.max) err := WriteVarString(w, test.in) if !errors.Is(err, test.writeErr) { @@ -523,7 +518,7 @@ func TestVarStringWireErrors(t *testing.T) { continue } - // Decode from wire format. + // Decode from domainmessage format. r := newFixedReader(test.max, test.buf) _, err = ReadVarString(r, test.pver) if !errors.Is(err, test.readErr) { @@ -542,8 +537,8 @@ func TestVarStringOverflowErrors(t *testing.T) { pver := ProtocolVersion tests := []struct { - buf []byte // Wire encoding - pver uint32 // Protocol version for wire encoding + buf []byte // Encoded value + pver uint32 // Protocol version for domainmessage encoding err error // Expected error }{ {[]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, @@ -554,7 +549,7 @@ func TestVarStringOverflowErrors(t *testing.T) { t.Logf("Running %d tests", len(tests)) for i, test := range tests { - // Decode from wire format. + // Decode from domainmessage format. rbuf := bytes.NewReader(test.buf) _, err := ReadVarString(rbuf, test.pver) if reflect.TypeOf(err) != reflect.TypeOf(test.err) { @@ -566,8 +561,8 @@ func TestVarStringOverflowErrors(t *testing.T) { } -// TestVarBytesWire tests wire encode and decode for variable length byte array. -func TestVarBytesWire(t *testing.T) { +// TestVarBytesEncoding tests domainmessage encode and decode for variable length byte array. +func TestVarBytesEncoding(t *testing.T) { pver := ProtocolVersion // bytes256 is a byte array that takes a 2-byte varint to encode. @@ -575,8 +570,8 @@ func TestVarBytesWire(t *testing.T) { tests := []struct { in []byte // Byte Array to write - buf []byte // Wire encoding - pver uint32 // Protocol version for wire encoding + buf []byte // Encoded value + pver uint32 // Protocol version for domainmessage encoding }{ // Latest protocol version. // Empty byte array @@ -589,7 +584,7 @@ func TestVarBytesWire(t *testing.T) { t.Logf("Running %d tests", len(tests)) for i, test := range tests { - // Encode to wire format. + // Encode to domainmessage format. var buf bytes.Buffer err := WriteVarBytes(&buf, test.pver, test.in) if err != nil { @@ -602,7 +597,7 @@ func TestVarBytesWire(t *testing.T) { continue } - // Decode from wire format. + // Decode from domainmessage format. rbuf := bytes.NewReader(test.buf) val, err := ReadVarBytes(rbuf, test.pver, MaxMessagePayload, "test payload") @@ -618,9 +613,9 @@ func TestVarBytesWire(t *testing.T) { } } -// TestVarBytesWireErrors performs negative tests against wire encode and +// TestVarBytesEncodingErrors performs negative tests against domainmessage encode and // decode of variable length byte arrays to confirm error paths work correctly. -func TestVarBytesWireErrors(t *testing.T) { +func TestVarBytesEncodingErrors(t *testing.T) { pver := ProtocolVersion // bytes256 is a byte array that takes a 2-byte varint to encode. @@ -628,8 +623,8 @@ func TestVarBytesWireErrors(t *testing.T) { tests := []struct { in []byte // Byte Array to write - buf []byte // Wire encoding - pver uint32 // Protocol version for wire encoding + buf []byte // Encoded value + pver uint32 // Protocol version for domainmessage encoding max int // Max size of fixed buffer to induce errors writeErr error // Expected write error readErr error // Expected read error @@ -645,7 +640,7 @@ func TestVarBytesWireErrors(t *testing.T) { t.Logf("Running %d tests", len(tests)) for i, test := range tests { - // Encode to wire format. + // Encode to domainmessage format. w := newFixedWriter(test.max) err := WriteVarBytes(w, test.pver, test.in) if !errors.Is(err, test.writeErr) { @@ -654,7 +649,7 @@ func TestVarBytesWireErrors(t *testing.T) { continue } - // Decode from wire format. + // Decode from domainmessage format. r := newFixedReader(test.max, test.buf) _, err = ReadVarBytes(r, test.pver, MaxMessagePayload, "test payload") @@ -674,8 +669,8 @@ func TestVarBytesOverflowErrors(t *testing.T) { pver := ProtocolVersion tests := []struct { - buf []byte // Wire encoding - pver uint32 // Protocol version for wire encoding + buf []byte // Encoded value + pver uint32 // Protocol version for domainmessage encoding err error // Expected error }{ {[]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, @@ -686,7 +681,7 @@ func TestVarBytesOverflowErrors(t *testing.T) { t.Logf("Running %d tests", len(tests)) for i, test := range tests { - // Decode from wire format. + // Decode from domainmessage format. rbuf := bytes.NewReader(test.buf) _, err := ReadVarBytes(rbuf, test.pver, MaxMessagePayload, "test payload") diff --git a/wire/doc.go b/domainmessage/doc.go similarity index 80% rename from wire/doc.go rename to domainmessage/doc.go index 5890207cf..39a893409 100644 --- a/wire/doc.go +++ b/domainmessage/doc.go @@ -1,8 +1,8 @@ /* -Package wire implements the kaspa wire protocol. +Package domainmessage implements the kaspa domainmessage protocol. At a high level, this package provides support for marshalling and unmarshalling -supported kaspa messages to and from the wire. This package does not deal +supported kaspa messages to and from the domainmessage. This package does not deal with the specifics of message handling such as what to do when a message is received. This provides the caller with a high level of flexibility. @@ -19,7 +19,7 @@ Message which allows messages of any type to be read, written, or passed around through channels, functions, etc. In addition, concrete implementations of most of the currently supported kaspa messages are provided. For these supported messages, all of the details of marshalling and unmarshalling to and from the -wire using kaspa encoding are handled so the caller doesn't have to concern +domainmessage using kaspa encoding are handled so the caller doesn't have to concern themselves with the specifics. Message Interaction @@ -55,7 +55,7 @@ Protocol Version The protocol version should be negotiated with the remote peer at a higher level than this package via the version (MsgVersion) message exchange, however, -this package provides the wire.ProtocolVersion constant which indicates the +this package provides the domainmessage.ProtocolVersion constant which indicates the latest protocol version this package supports and is typically the value to use for all outbound connections before a potentially lower protocol version is negotiated. @@ -66,11 +66,11 @@ The kaspa network is a magic number which is used to identify the start of a message and which kaspa network the message applies to. This package provides the following constants: - wire.Mainnet - wire.Testnet (Test network) - wire.Regtest (Regression test network) - wire.Simnet (Simulation test network) - wire.Devnet (Development network) + domainmessage.Mainnet + domainmessage.Testnet (Test network) + domainmessage.Regtest (Regression test network) + domainmessage.Simnet (Simulation test network) + domainmessage.Devnet (Development network) Determining Message Type @@ -82,43 +82,43 @@ switch or type assertion. An example of a type switch follows: // Assumes msg is already a valid concrete message such as one created // via NewMsgVersion or read via ReadMessage. switch msg := msg.(type) { - case *wire.MsgVersion: + case *domainmessage.MsgVersion: // The message is a pointer to a MsgVersion struct. fmt.Printf("Protocol version: %d", msg.ProtocolVersion) - case *wire.MsgBlock: + case *domainmessage.MsgBlock: // The message is a pointer to a MsgBlock struct. fmt.Printf("Number of tx in block: %d", msg.Header.TxnCount) } Reading Messages -In order to unmarshall kaspa messages from the wire, use the ReadMessage +In order to unmarshall kaspa messages from the domainmessage, use the ReadMessage function. It accepts any io.Reader, but typically this will be a net.Conn to a remote node running a kaspa peer. Example syntax is: // Reads and validates the next kaspa message from conn using the // protocol version pver and the kaspa network kaspaNet. The returns - // are a wire.Message, a []byte which contains the unmarshalled + // are a domainmessage.Message, a []byte which contains the unmarshalled // raw payload, and a possible error. - msg, rawPayload, err := wire.ReadMessage(conn, pver, kaspaNet) + msg, rawPayload, err := domainmessage.ReadMessage(conn, pver, kaspaNet) if err != nil { // Log and handle the error } Writing Messages -In order to marshall kaspa messages to the wire, use the WriteMessage +In order to marshall kaspa messages to the domainmessage, use the WriteMessage function. It accepts any io.Writer, but typically this will be a net.Conn to a remote node running a kaspa peer. Example syntax to request addresses from a remote peer is: // Create a new getaddr kaspa message. - msg := wire.NewMsgRequestAddresses() + msg := domainmessage.NewMsgRequestAddresses() // Writes a kaspa message msg to conn using the protocol version // pver, and the kaspa network kaspaNet. The return is a possible // error. - err := wire.WriteMessage(conn, msg, pver, kaspaNet) + err := domainmessage.WriteMessage(conn, msg, pver, kaspaNet) if err != nil { // Log and handle the error } @@ -127,8 +127,8 @@ Errors Errors returned by this package are either the raw errors provided by underlying calls to read/write from streams such as io.EOF, io.ErrUnexpectedEOF, and -io.ErrShortWrite, or of type wire.MessageError. This allows the caller to +io.ErrShortWrite, or of type domainmessage.MessageError. This allows the caller to differentiate between general IO errors and malformed messages through type assertions. */ -package wire +package domainmessage diff --git a/wire/error.go b/domainmessage/error.go similarity index 98% rename from wire/error.go rename to domainmessage/error.go index 0f84ac8cb..656d01c30 100644 --- a/wire/error.go +++ b/domainmessage/error.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "fmt" diff --git a/wire/fakemessage_test.go b/domainmessage/fakemessage_test.go similarity index 91% rename from wire/fakemessage_test.go rename to domainmessage/fakemessage_test.go index 94a8f2839..20c7bee11 100644 --- a/wire/fakemessage_test.go +++ b/domainmessage/fakemessage_test.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import "io" @@ -15,7 +15,7 @@ type fakeMessage struct { forceLenErr bool } -// KaspaDecode doesn't do anything. It just satisfies the wire.Message +// KaspaDecode doesn't do anything. It just satisfies the domainmessage.Message // interface. func (msg *fakeMessage) KaspaDecode(r io.Reader, pver uint32) error { return nil @@ -23,7 +23,7 @@ func (msg *fakeMessage) KaspaDecode(r io.Reader, pver uint32) error { // KaspaEncode writes the payload field of the fake message or forces an error // if the forceEncodeErr flag of the fake message is set. It also satisfies the -// wire.Message interface. +// domainmessage.Message interface. func (msg *fakeMessage) KaspaEncode(w io.Writer, pver uint32) error { if msg.forceEncodeErr { err := &MessageError{ diff --git a/wire/fixedIO_test.go b/domainmessage/fixedIO_test.go similarity index 98% rename from wire/fixedIO_test.go rename to domainmessage/fixedIO_test.go index 96de3736a..3d2a3ac7b 100644 --- a/wire/fixedIO_test.go +++ b/domainmessage/fixedIO_test.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "bytes" diff --git a/wire/message.go b/domainmessage/message.go similarity index 99% rename from wire/message.go rename to domainmessage/message.go index 3b62e22f0..06385e5ff 100644 --- a/wire/message.go +++ b/domainmessage/message.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "fmt" diff --git a/wire/msgaddresses.go b/domainmessage/msgaddresses.go similarity index 99% rename from wire/msgaddresses.go rename to domainmessage/msgaddresses.go index d837a6bb8..91e9acab4 100644 --- a/wire/msgaddresses.go +++ b/domainmessage/msgaddresses.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "fmt" diff --git a/wire/msgaddresses_test.go b/domainmessage/msgaddresses_test.go similarity index 98% rename from wire/msgaddresses_test.go rename to domainmessage/msgaddresses_test.go index 52ab1535b..886a7b7c1 100644 --- a/wire/msgaddresses_test.go +++ b/domainmessage/msgaddresses_test.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "net" diff --git a/wire/msgblock.go b/domainmessage/msgblock.go similarity index 91% rename from wire/msgblock.go rename to domainmessage/msgblock.go index 280bcea25..0d83fd3ab 100644 --- a/wire/msgblock.go +++ b/domainmessage/msgblock.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "bytes" @@ -59,7 +59,7 @@ func (msg *MsgBlock) ClearTransactions() { // KaspaDecode decodes r using the kaspa protocol encoding into the receiver. // This is part of the Message interface implementation. // See Deserialize for decoding blocks stored to disk, such as in a database, as -// opposed to decoding blocks from the wire. +// opposed to decoding blocks from the domainmessage. func (msg *MsgBlock) KaspaDecode(r io.Reader, pver uint32) error { err := readBlockHeader(r, pver, &msg.Header) if err != nil { @@ -96,14 +96,14 @@ func (msg *MsgBlock) KaspaDecode(r io.Reader, pver uint32) error { // Deserialize decodes a block from r into the receiver using a format that is // suitable for long-term storage such as a database while respecting the // Version field in the block. This function differs from KaspaDecode in that -// KaspaDecode decodes from the kaspa wire protocol as it was sent across the -// network. The wire encoding can technically differ depending on the protocol +// KaspaDecode decodes from the kaspa domainmessage protocol as it was sent across the +// network. The domainmessage encoding can technically differ depending on the protocol // version and doesn't even really need to match the format of a stored block at // all. As of the time this comment was written, the encoded block is the same // in both instances, but there is a distinct difference and separating the two // allows the API to be flexible enough to deal with changes. func (msg *MsgBlock) Deserialize(r io.Reader) error { - // At the current time, there is no difference between the wire encoding + // At the current time, there is no difference between the domainmessage encoding // at protocol version 0 and the stable long-term storage format. As // a result, make use of KaspaDecode. return msg.KaspaDecode(r, 0) @@ -116,9 +116,9 @@ func (msg *MsgBlock) Deserialize(r io.Reader) error { func (msg *MsgBlock) DeserializeTxLoc(r *bytes.Buffer) ([]TxLoc, error) { fullLen := r.Len() - // At the current time, there is no difference between the wire encoding + // At the current time, there is no difference between the domainmessage encoding // at protocol version 0 and the stable long-term storage format. As - // a result, make use of existing wire protocol functions. + // a result, make use of existing domainmessage protocol functions. err := readBlockHeader(r, 0, &msg.Header) if err != nil { return nil, err @@ -159,7 +159,7 @@ func (msg *MsgBlock) DeserializeTxLoc(r *bytes.Buffer) ([]TxLoc, error) { // KaspaEncode encodes the receiver to w using the kaspa protocol encoding. // This is part of the Message interface implementation. // See Serialize for encoding blocks to be stored to disk, such as in a -// database, as opposed to encoding blocks for the wire. +// database, as opposed to encoding blocks for the domainmessage. func (msg *MsgBlock) KaspaEncode(w io.Writer, pver uint32) error { err := writeBlockHeader(w, pver, &msg.Header) if err != nil { @@ -184,14 +184,14 @@ func (msg *MsgBlock) KaspaEncode(w io.Writer, pver uint32) error { // Serialize encodes the block to w using a format that suitable for long-term // storage such as a database while respecting the Version field in the block. // This function differs from KaspaEncode in that KaspaEncode encodes the block to -// the kaspa wire protocol in order to be sent across the network. The wire +// the kaspa domainmessage protocol in order to be sent across the network. The domainmessage // encoding can technically differ depending on the protocol version and doesn't // even really need to match the format of a stored block at all. As of the // time this comment was written, the encoded block is the same in both // instances, but there is a distinct difference and separating the two allows // the API to be flexible enough to deal with changes. func (msg *MsgBlock) Serialize(w io.Writer) error { - // At the current time, there is no difference between the wire encoding + // At the current time, there is no difference between the domainmessage encoding // at protocol version 0 and the stable long-term storage format. As // a result, make use of KaspaEncode. return msg.KaspaEncode(w, 0) diff --git a/wire/msgblock_test.go b/domainmessage/msgblock_test.go similarity index 95% rename from wire/msgblock_test.go rename to domainmessage/msgblock_test.go index 647965661..5e4e2a863 100644 --- a/wire/msgblock_test.go +++ b/domainmessage/msgblock_test.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "bytes" @@ -144,15 +144,15 @@ func TestConvertToPartial(t *testing.T) { } } -// TestBlockWire tests the MsgBlock wire encode and decode for various numbers +// TestBlockEncoding tests the MsgBlock domainmessage encode and decode for various numbers // of transaction inputs and outputs and protocol versions. -func TestBlockWire(t *testing.T) { +func TestBlockEncoding(t *testing.T) { tests := []struct { in *MsgBlock // Message to encode out *MsgBlock // Expected decoded message - buf []byte // Wire encoding + buf []byte // Encoded value txLocs []TxLoc // Expected transaction locations - pver uint32 // Protocol version for wire encoding + pver uint32 // Protocol version for domainmessage encoding }{ // Latest protocol version. { @@ -166,7 +166,7 @@ func TestBlockWire(t *testing.T) { t.Logf("Running %d tests", len(tests)) for i, test := range tests { - // Encode the message to wire format. + // Encode the message to domainmessage format. var buf bytes.Buffer err := test.in.KaspaEncode(&buf, test.pver) if err != nil { @@ -179,7 +179,7 @@ func TestBlockWire(t *testing.T) { continue } - // Decode the message from wire format. + // Decode the message from domainmessage format. var msg MsgBlock rbuf := bytes.NewReader(test.buf) err = msg.KaspaDecode(rbuf, test.pver) @@ -195,15 +195,15 @@ func TestBlockWire(t *testing.T) { } } -// TestBlockWireErrors performs negative tests against wire encode and decode +// TestBlockEncodingErrors performs negative tests against domainmessage encode and decode // of MsgBlock to confirm error paths work correctly. -func TestBlockWireErrors(t *testing.T) { +func TestBlockEncodingErrors(t *testing.T) { pver := ProtocolVersion tests := []struct { in *MsgBlock // Value to encode - buf []byte // Wire encoding - pver uint32 // Protocol version for wire encoding + buf []byte // Encoded value + pver uint32 // Protocol version for domainmessage encoding max int // Max size of fixed buffer to induce errors writeErr error // Expected write error readErr error // Expected read error @@ -236,7 +236,7 @@ func TestBlockWireErrors(t *testing.T) { t.Logf("Running %d tests", len(tests)) for i, test := range tests { - // Encode to wire format. + // Encode to domainmessage format. w := newFixedWriter(test.max) err := test.in.KaspaEncode(w, test.pver) if !errors.Is(err, test.writeErr) { @@ -245,7 +245,7 @@ func TestBlockWireErrors(t *testing.T) { continue } - // Decode from wire format. + // Decode from domainmessage format. var msg MsgBlock r := newFixedReader(test.max, test.buf) err = msg.KaspaDecode(r, test.pver) @@ -324,7 +324,7 @@ func TestBlockSerialize(t *testing.T) { } } -// TestBlockSerializeErrors performs negative tests against wire encode and +// TestBlockSerializeErrors performs negative tests against domainmessage encode and // decode of MsgBlock to confirm error paths work correctly. func TestBlockSerializeErrors(t *testing.T) { tests := []struct { @@ -400,8 +400,8 @@ func TestBlockOverflowErrors(t *testing.T) { pver := ProtocolVersion tests := []struct { - buf []byte // Wire encoding - pver uint32 // Protocol version for wire encoding + buf []byte // Encoded value + pver uint32 // Protocol version for domainmessage encoding err error // Expected error }{ // Block that claims to have ~uint64(0) transactions. @@ -440,7 +440,7 @@ func TestBlockOverflowErrors(t *testing.T) { t.Logf("Running %d tests", len(tests)) for i, test := range tests { - // Decode from wire format. + // Decode from domainmessage format. var msg MsgBlock r := bytes.NewReader(test.buf) err := msg.KaspaDecode(r, test.pver) @@ -450,7 +450,7 @@ func TestBlockOverflowErrors(t *testing.T) { continue } - // Deserialize from wire format. + // Deserialize from domainmessage format. r = bytes.NewReader(test.buf) err = msg.Deserialize(r) if reflect.TypeOf(err) != reflect.TypeOf(test.err) { @@ -459,7 +459,7 @@ func TestBlockOverflowErrors(t *testing.T) { continue } - // Deserialize with transaction location info from wire format. + // Deserialize with transaction location info from domainmessage format. br := bytes.NewBuffer(test.buf) _, err = msg.DeserializeTxLoc(br) if reflect.TypeOf(err) != reflect.TypeOf(test.err) { diff --git a/wire/msgblocklocator.go b/domainmessage/msgblocklocator.go similarity index 97% rename from wire/msgblocklocator.go rename to domainmessage/msgblocklocator.go index 52f173f89..b6a2b849d 100644 --- a/wire/msgblocklocator.go +++ b/domainmessage/msgblocklocator.go @@ -1,4 +1,4 @@ -package wire +package domainmessage import ( "github.com/kaspanet/kaspad/util/daghash" diff --git a/wire/msgblocklocator_test.go b/domainmessage/msgblocklocator_test.go similarity index 97% rename from wire/msgblocklocator_test.go rename to domainmessage/msgblocklocator_test.go index e6aa70ec8..f35c5e3dc 100644 --- a/wire/msgblocklocator_test.go +++ b/domainmessage/msgblocklocator_test.go @@ -1,4 +1,4 @@ -package wire +package domainmessage import ( "testing" diff --git a/wire/msgdoneibdblocks.go b/domainmessage/msgdoneibdblocks.go similarity index 96% rename from wire/msgdoneibdblocks.go rename to domainmessage/msgdoneibdblocks.go index 6798ed5ea..9d7b9a67d 100644 --- a/wire/msgdoneibdblocks.go +++ b/domainmessage/msgdoneibdblocks.go @@ -1,4 +1,4 @@ -package wire +package domainmessage // MsgDoneIBDBlocks implements the Message interface and represents a kaspa // DoneIBDBlocks message. It is used to notify the IBD syncing peer that the diff --git a/wire/msgibdblock.go b/domainmessage/msgibdblock.go similarity index 97% rename from wire/msgibdblock.go rename to domainmessage/msgibdblock.go index cea3d7765..434ea105e 100644 --- a/wire/msgibdblock.go +++ b/domainmessage/msgibdblock.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage // MsgIBDBlock implements the Message interface and represents a kaspa // ibdblock message. It is used to deliver block and transaction information in diff --git a/wire/msgibdblock_test.go b/domainmessage/msgibdblock_test.go similarity index 89% rename from wire/msgibdblock_test.go rename to domainmessage/msgibdblock_test.go index 00a4311c6..520cf6759 100644 --- a/wire/msgibdblock_test.go +++ b/domainmessage/msgibdblock_test.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "bytes" @@ -65,15 +65,15 @@ func TestIBDBlock(t *testing.T) { } } -// TestIBDBlockWire tests the MsgIBDBlock wire encode and decode for various numbers +// TestIBDBlockEncoding tests the MsgIBDBlock domainmessage encode and decode for various numbers // of transaction inputs and outputs and protocol versions. -func TestIBDBlockWire(t *testing.T) { +func TestIBDBlockEncoding(t *testing.T) { tests := []struct { in *MsgIBDBlock // Message to encode out *MsgIBDBlock // Expected decoded message - buf []byte // Wire encoding + buf []byte // Encoded value txLocs []TxLoc // Expected transaction locations - pver uint32 // Protocol version for wire encoding + pver uint32 // Protocol version for domainmessage encoding }{ // Latest protocol version. { @@ -87,7 +87,7 @@ func TestIBDBlockWire(t *testing.T) { t.Logf("Running %d tests", len(tests)) for i, test := range tests { - // Encode the message to wire format. + // Encode the message to domainmessage format. var buf bytes.Buffer err := test.in.KaspaEncode(&buf, test.pver) if err != nil { @@ -100,7 +100,7 @@ func TestIBDBlockWire(t *testing.T) { continue } - // Decode the message from wire format. + // Decode the message from domainmessage format. var msg MsgIBDBlock msg.MsgBlock = new(MsgBlock) rbuf := bytes.NewReader(test.buf) diff --git a/wire/msginvrelayblock.go b/domainmessage/msginvrelayblock.go similarity index 97% rename from wire/msginvrelayblock.go rename to domainmessage/msginvrelayblock.go index ecec6ab38..72e792832 100644 --- a/wire/msginvrelayblock.go +++ b/domainmessage/msginvrelayblock.go @@ -1,4 +1,4 @@ -package wire +package domainmessage import ( "github.com/kaspanet/kaspad/util/daghash" diff --git a/wire/msginvtransaction.go b/domainmessage/msginvtransaction.go similarity index 97% rename from wire/msginvtransaction.go rename to domainmessage/msginvtransaction.go index 9182f89ce..21c1d7a01 100644 --- a/wire/msginvtransaction.go +++ b/domainmessage/msginvtransaction.go @@ -1,4 +1,4 @@ -package wire +package domainmessage import ( "github.com/kaspanet/kaspad/util/daghash" diff --git a/wire/msgping.go b/domainmessage/msgping.go similarity index 98% rename from wire/msgping.go rename to domainmessage/msgping.go index df194486e..2d1977575 100644 --- a/wire/msgping.go +++ b/domainmessage/msgping.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage // MsgPing implements the Message interface and represents a kaspa ping // message. diff --git a/wire/msgping_test.go b/domainmessage/msgping_test.go similarity index 97% rename from wire/msgping_test.go rename to domainmessage/msgping_test.go index aab80bc7a..9f4c96f73 100644 --- a/wire/msgping_test.go +++ b/domainmessage/msgping_test.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "testing" diff --git a/wire/msgpong.go b/domainmessage/msgpong.go similarity index 97% rename from wire/msgpong.go rename to domainmessage/msgpong.go index 0adf1ee86..3a0aeb1bd 100644 --- a/wire/msgpong.go +++ b/domainmessage/msgpong.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage // MsgPong implements the Message interface and represents a kaspa pong // message which is used primarily to confirm that a connection is still valid diff --git a/wire/msgpong_test.go b/domainmessage/msgpong_test.go similarity index 97% rename from wire/msgpong_test.go rename to domainmessage/msgpong_test.go index e92d725ec..b8053039b 100644 --- a/wire/msgpong_test.go +++ b/domainmessage/msgpong_test.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "testing" diff --git a/wire/msgrequestaddresses.go b/domainmessage/msgrequestaddresses.go similarity index 98% rename from wire/msgrequestaddresses.go rename to domainmessage/msgrequestaddresses.go index d257c85e9..cc123845a 100644 --- a/wire/msgrequestaddresses.go +++ b/domainmessage/msgrequestaddresses.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "github.com/kaspanet/kaspad/util/subnetworkid" diff --git a/wire/msgrequestaddresses_test.go b/domainmessage/msgrequestaddresses_test.go similarity index 95% rename from wire/msgrequestaddresses_test.go rename to domainmessage/msgrequestaddresses_test.go index 9e2238bb6..eede271f2 100644 --- a/wire/msgrequestaddresses_test.go +++ b/domainmessage/msgrequestaddresses_test.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "testing" diff --git a/wire/msgrequestblocklocator.go b/domainmessage/msgrequestblocklocator.go similarity index 97% rename from wire/msgrequestblocklocator.go rename to domainmessage/msgrequestblocklocator.go index 4818a537c..97b3995b6 100644 --- a/wire/msgrequestblocklocator.go +++ b/domainmessage/msgrequestblocklocator.go @@ -1,4 +1,4 @@ -package wire +package domainmessage import ( "github.com/kaspanet/kaspad/util/daghash" diff --git a/wire/msgrequestblocklocator_test.go b/domainmessage/msgrequestblocklocator_test.go similarity index 96% rename from wire/msgrequestblocklocator_test.go rename to domainmessage/msgrequestblocklocator_test.go index 8da0bb688..1693d64d8 100644 --- a/wire/msgrequestblocklocator_test.go +++ b/domainmessage/msgrequestblocklocator_test.go @@ -1,4 +1,4 @@ -package wire +package domainmessage import ( "testing" diff --git a/wire/msgrequestibdblocks.go b/domainmessage/msgrequestibdblocks.go similarity index 97% rename from wire/msgrequestibdblocks.go rename to domainmessage/msgrequestibdblocks.go index ae2f01bf6..afca41378 100644 --- a/wire/msgrequestibdblocks.go +++ b/domainmessage/msgrequestibdblocks.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "github.com/kaspanet/kaspad/util/daghash" diff --git a/wire/msgrequestibdblocks_test.go b/domainmessage/msgrequestibdblocks_test.go similarity index 98% rename from wire/msgrequestibdblocks_test.go rename to domainmessage/msgrequestibdblocks_test.go index 9aa266a09..581fd472d 100644 --- a/wire/msgrequestibdblocks_test.go +++ b/domainmessage/msgrequestibdblocks_test.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "testing" diff --git a/wire/msgrequestnextibdblocks.go b/domainmessage/msgrequestnextibdblocks.go similarity index 96% rename from wire/msgrequestnextibdblocks.go rename to domainmessage/msgrequestnextibdblocks.go index 76a56e364..59be25439 100644 --- a/wire/msgrequestnextibdblocks.go +++ b/domainmessage/msgrequestnextibdblocks.go @@ -1,4 +1,4 @@ -package wire +package domainmessage // MsgRequestNextIBDBlocks implements the Message interface and represents a kaspa // RequestNextIBDBlocks message. It is used to notify the IBD syncer peer to send diff --git a/wire/msgrequestrelayblocks.go b/domainmessage/msgrequestrelayblocks.go similarity index 97% rename from wire/msgrequestrelayblocks.go rename to domainmessage/msgrequestrelayblocks.go index 89bddc8ff..a4d1c36e6 100644 --- a/wire/msgrequestrelayblocks.go +++ b/domainmessage/msgrequestrelayblocks.go @@ -1,4 +1,4 @@ -package wire +package domainmessage import ( "github.com/kaspanet/kaspad/util/daghash" diff --git a/wire/msgrequestselectedtip.go b/domainmessage/msgrequestselectedtip.go similarity index 96% rename from wire/msgrequestselectedtip.go rename to domainmessage/msgrequestselectedtip.go index ddb95e664..3d9bee883 100644 --- a/wire/msgrequestselectedtip.go +++ b/domainmessage/msgrequestselectedtip.go @@ -1,4 +1,4 @@ -package wire +package domainmessage // MsgRequestSelectedTip implements the Message interface and represents a kaspa // RequestSelectedTip message. It is used to request the selected tip of another peer. diff --git a/wire/msgrequestselectedtip_test.go b/domainmessage/msgrequestselectedtip_test.go similarity index 95% rename from wire/msgrequestselectedtip_test.go rename to domainmessage/msgrequestselectedtip_test.go index 6876ece02..826ec7f89 100644 --- a/wire/msgrequestselectedtip_test.go +++ b/domainmessage/msgrequestselectedtip_test.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "testing" diff --git a/wire/msgrequesttransactions.go b/domainmessage/msgrequesttransactions.go similarity index 97% rename from wire/msgrequesttransactions.go rename to domainmessage/msgrequesttransactions.go index 9158b432e..1929596f4 100644 --- a/wire/msgrequesttransactions.go +++ b/domainmessage/msgrequesttransactions.go @@ -1,4 +1,4 @@ -package wire +package domainmessage import ( "github.com/kaspanet/kaspad/util/daghash" diff --git a/wire/msgselectedtip.go b/domainmessage/msgselectedtip.go similarity index 97% rename from wire/msgselectedtip.go rename to domainmessage/msgselectedtip.go index e3af2c7f8..837a30f02 100644 --- a/wire/msgselectedtip.go +++ b/domainmessage/msgselectedtip.go @@ -1,4 +1,4 @@ -package wire +package domainmessage import ( "github.com/kaspanet/kaspad/util/daghash" diff --git a/wire/msgselectedtip_test.go b/domainmessage/msgselectedtip_test.go similarity index 94% rename from wire/msgselectedtip_test.go rename to domainmessage/msgselectedtip_test.go index 930bf5f8e..a6ba1e5e9 100644 --- a/wire/msgselectedtip_test.go +++ b/domainmessage/msgselectedtip_test.go @@ -1,4 +1,4 @@ -package wire +package domainmessage import ( "github.com/kaspanet/kaspad/util/daghash" diff --git a/wire/msgtransactionnotfound.go b/domainmessage/msgtransactionnotfound.go similarity index 97% rename from wire/msgtransactionnotfound.go rename to domainmessage/msgtransactionnotfound.go index 054c91a35..9d7b2a8ef 100644 --- a/wire/msgtransactionnotfound.go +++ b/domainmessage/msgtransactionnotfound.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "github.com/kaspanet/kaspad/util/daghash" diff --git a/wire/msgtx.go b/domainmessage/msgtx.go similarity index 97% rename from wire/msgtx.go rename to domainmessage/msgtx.go index 508321e65..fbbeb5adb 100644 --- a/wire/msgtx.go +++ b/domainmessage/msgtx.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "bytes" @@ -84,7 +84,7 @@ const ( minTxPayload = 10 // freeListMaxScriptSize is the size of each buffer in the free list - // that is used for deserializing scripts from the wire before they are + // that is used for deserializing scripts from the domainmessage before they are // concatenated into a single contiguous buffers. This value was chosen // because it is slightly more than twice the size of the vast majority // of all "standard" scripts. Larger scripts are still deserialized @@ -401,7 +401,7 @@ func (msg *MsgTx) Copy() *MsgTx { // KaspaDecode decodes r using the kaspa protocol encoding into the receiver. // This is part of the Message interface implementation. // See Deserialize for decoding transactions stored to disk, such as in a -// database, as opposed to decoding transactions from the wire. +// database, as opposed to decoding transactions from the domainmessage. func (msg *MsgTx) KaspaDecode(r io.Reader, pver uint32) error { version, err := binaryserializer.Uint32(r, littleEndian) if err != nil { @@ -591,15 +591,15 @@ func (msg *MsgTx) KaspaDecode(r io.Reader, pver uint32) error { // Deserialize decodes a transaction from r into the receiver using a format // that is suitable for long-term storage such as a database while respecting // the Version field in the transaction. This function differs from KaspaDecode -// in that KaspaDecode decodes from the kaspa wire protocol as it was sent -// across the network. The wire encoding can technically differ depending on +// in that KaspaDecode decodes from the kaspa domainmessage protocol as it was sent +// across the network. The domainmessage encoding can technically differ depending on // the protocol version and doesn't even really need to match the format of a // stored transaction at all. As of the time this comment was written, the // encoded transaction is the same in both instances, but there is a distinct // difference and separating the two allows the API to be flexible enough to // deal with changes. func (msg *MsgTx) Deserialize(r io.Reader) error { - // At the current time, there is no difference between the wire encoding + // At the current time, there is no difference between the domainmessage encoding // at protocol version 0 and the stable long-term storage format. As // a result, make use of KaspaDecode. return msg.KaspaDecode(r, 0) @@ -608,7 +608,7 @@ func (msg *MsgTx) Deserialize(r io.Reader) error { // KaspaEncode encodes the receiver to w using the kaspa protocol encoding. // This is part of the Message interface implementation. // See Serialize for encoding transactions to be stored to disk, such as in a -// database, as opposed to encoding transactions for the wire. +// database, as opposed to encoding transactions for the domainmessage. func (msg *MsgTx) KaspaEncode(w io.Writer, pver uint32) error { return msg.encode(w, pver, txEncodingFull) } @@ -697,22 +697,22 @@ func (msg *MsgTx) encode(w io.Writer, pver uint32, encodingFlags txEncoding) err // Serialize encodes the transaction to w using a format that suitable for // long-term storage such as a database while respecting the Version field in // the transaction. This function differs from KaspaEncode in that KaspaEncode -// encodes the transaction to the kaspa wire protocol in order to be sent -// across the network. The wire encoding can technically differ depending on +// encodes the transaction to the kaspa domainmessage protocol in order to be sent +// across the network. The domainmessage encoding can technically differ depending on // the protocol version and doesn't even really need to match the format of a // stored transaction at all. As of the time this comment was written, the // encoded transaction is the same in both instances, but there is a distinct // difference and separating the two allows the API to be flexible enough to // deal with changes. func (msg *MsgTx) Serialize(w io.Writer) error { - // At the current time, there is no difference between the wire encoding + // At the current time, there is no difference between the domainmessage encoding // at protocol version 0 and the stable long-term storage format. As // a result, make use of KaspaEncode. return msg.KaspaEncode(w, 0) } func (msg *MsgTx) serialize(w io.Writer, encodingFlags txEncoding) error { - // At the current time, there is no difference between the wire encoding + // At the current time, there is no difference between the domainmessage encoding // at protocol version 0 and the stable long-term storage format. As // a result, make use of `encode`. return msg.encode(w, 0, encodingFlags) diff --git a/wire/msgtx_test.go b/domainmessage/msgtx_test.go similarity index 96% rename from wire/msgtx_test.go rename to domainmessage/msgtx_test.go index 87122f089..d49e97954 100644 --- a/wire/msgtx_test.go +++ b/domainmessage/msgtx_test.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "bytes" @@ -253,9 +253,9 @@ func TestTxHashAndID(t *testing.T) { } } -// TestTxWire tests the MsgTx wire encode and decode for various numbers +// TestTxEncoding tests the MsgTx domainmessage encode and decode for various numbers // of transaction inputs and outputs and protocol versions. -func TestTxWire(t *testing.T) { +func TestTxEncoding(t *testing.T) { // Empty tx message. noTx := NewNativeMsgTx(1, nil, nil) noTxEncoded := []byte{ @@ -271,8 +271,8 @@ func TestTxWire(t *testing.T) { tests := []struct { in *MsgTx // Message to encode out *MsgTx // Expected decoded message - buf []byte // Wire encoding - pver uint32 // Protocol version for wire encoding + buf []byte // Encoded value + pver uint32 // Protocol version for domainmessage encoding }{ // Latest protocol version with no transactions. { @@ -293,7 +293,7 @@ func TestTxWire(t *testing.T) { t.Logf("Running %d tests", len(tests)) for i, test := range tests { - // Encode the message to wire format. + // Encode the message to domainmessage format. var buf bytes.Buffer err := test.in.KaspaEncode(&buf, test.pver) if err != nil { @@ -306,7 +306,7 @@ func TestTxWire(t *testing.T) { continue } - // Decode the message from wire format. + // Decode the message from domainmessage format. var msg MsgTx rbuf := bytes.NewReader(test.buf) err = msg.KaspaDecode(rbuf, test.pver) @@ -322,15 +322,15 @@ func TestTxWire(t *testing.T) { } } -// TestTxWireErrors performs negative tests against wire encode and decode +// TestTxEncodingErrors performs negative tests against domainmessage encode and decode // of MsgTx to confirm error paths work correctly. -func TestTxWireErrors(t *testing.T) { +func TestTxEncodingErrors(t *testing.T) { pver := ProtocolVersion tests := []struct { in *MsgTx // Value to encode - buf []byte // Wire encoding - pver uint32 // Protocol version for wire encoding + buf []byte // Encoded value + pver uint32 // Protocol version for domainmessage encoding max int // Max size of fixed buffer to induce errors writeErr error // Expected write error readErr error // Expected read error @@ -363,7 +363,7 @@ func TestTxWireErrors(t *testing.T) { t.Logf("Running %d tests", len(tests)) for i, test := range tests { - // Encode to wire format. + // Encode to domainmessage format. w := newFixedWriter(test.max) err := test.in.KaspaEncode(w, test.pver) if !errors.Is(err, test.writeErr) { @@ -372,7 +372,7 @@ func TestTxWireErrors(t *testing.T) { continue } - // Decode from wire format. + // Decode from domainmessage format. var msg MsgTx r := newFixedReader(test.max, test.buf) err = msg.KaspaDecode(r, test.pver) @@ -528,7 +528,7 @@ func TestTxSerialize(t *testing.T) { } } -// TestTxSerializeErrors performs negative tests against wire encode and decode +// TestTxSerializeErrors performs negative tests against domainmessage encode and decode // of MsgTx to confirm error paths work correctly. func TestTxSerializeErrors(t *testing.T) { tests := []struct { @@ -628,8 +628,8 @@ func TestTxOverflowErrors(t *testing.T) { txVer := uint32(1) tests := []struct { - buf []byte // Wire encoding - pver uint32 // Protocol version for wire encoding + buf []byte // Encoded value + pver uint32 // Protocol version for domainmessage encoding version uint32 // Transaction version err error // Expected error }{ @@ -691,7 +691,7 @@ func TestTxOverflowErrors(t *testing.T) { t.Logf("Running %d tests", len(tests)) for i, test := range tests { - // Decode from wire format. + // Decode from domainmessage format. var msg MsgTx r := bytes.NewReader(test.buf) err := msg.KaspaDecode(r, test.pver) @@ -701,7 +701,7 @@ func TestTxOverflowErrors(t *testing.T) { continue } - // Decode from wire format. + // Decode from domainmessage format. r = bytes.NewReader(test.buf) err = msg.Deserialize(r) if reflect.TypeOf(err) != reflect.TypeOf(test.err) { @@ -891,7 +891,7 @@ var multiTxOuts = []*TxOut{ } var multiTx = NewNativeMsgTx(1, multiTxIns, multiTxOuts) -// multiTxEncoded is the wire encoded bytes for multiTx using protocol version +// multiTxEncoded is the domainmessage encoded bytes for multiTx using protocol version // 60002 and is used in the various tests. var multiTxEncoded = []byte{ 0x01, 0x00, 0x00, 0x00, // Version diff --git a/wire/msgverack.go b/domainmessage/msgverack.go similarity index 97% rename from wire/msgverack.go rename to domainmessage/msgverack.go index b5dfb644b..5e2e45173 100644 --- a/wire/msgverack.go +++ b/domainmessage/msgverack.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage // MsgVerAck defines a kaspa verack message which is used for a peer to // acknowledge a version message (MsgVersion) after it has used the information diff --git a/wire/msgverack_test.go b/domainmessage/msgverack_test.go similarity index 95% rename from wire/msgverack_test.go rename to domainmessage/msgverack_test.go index 0ed546d4a..a39f9edbd 100644 --- a/wire/msgverack_test.go +++ b/domainmessage/msgverack_test.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "testing" diff --git a/wire/msgversion.go b/domainmessage/msgversion.go similarity index 96% rename from wire/msgversion.go rename to domainmessage/msgversion.go index fb013b677..fb648c218 100644 --- a/wire/msgversion.go +++ b/domainmessage/msgversion.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "fmt" @@ -20,7 +20,7 @@ import ( // version message (MsgVersion). const MaxUserAgentLen = 256 -// DefaultUserAgent for wire in the stack +// DefaultUserAgent for domainmessage in the stack var DefaultUserAgent = fmt.Sprintf("/kaspad:%s/", version.Version()) // MsgVersion implements the Message interface and represents a kaspa version @@ -37,7 +37,7 @@ type MsgVersion struct { // Bitfield which identifies the enabled services. Services ServiceFlag - // Time the message was generated. This is encoded as an int64 on the wire. + // Time the message was generated. This is encoded as an int64 on the domainmessage. Timestamp mstime.Time // Address of the local peer. @@ -47,7 +47,7 @@ type MsgVersion struct { ID *id.ID // The user agent that generated messsage. This is a encoded as a varString - // on the wire. This has a max length of MaxUserAgentLen. + // on the domainmessage. This has a max length of MaxUserAgentLen. UserAgent string // The selected tip hash of the generator of the version message. diff --git a/wire/msgversion_test.go b/domainmessage/msgversion_test.go similarity index 99% rename from wire/msgversion_test.go rename to domainmessage/msgversion_test.go index 4687b5980..a56719117 100644 --- a/wire/msgversion_test.go +++ b/domainmessage/msgversion_test.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "github.com/davecgh/go-spew/spew" diff --git a/wire/netaddress.go b/domainmessage/netaddress.go similarity index 98% rename from wire/netaddress.go rename to domainmessage/netaddress.go index a1c0e2508..d0bf92844 100644 --- a/wire/netaddress.go +++ b/domainmessage/netaddress.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "github.com/kaspanet/kaspad/util/mstime" @@ -21,7 +21,7 @@ type NetAddress struct { // IP address of the peer. IP net.IP - // Port the peer is using. This is encoded in big endian on the wire + // Port the peer is using. This is encoded in big endian on the domainmessage // which differs from most everything else. Port uint16 } diff --git a/wire/netaddress_test.go b/domainmessage/netaddress_test.go similarity index 98% rename from wire/netaddress_test.go rename to domainmessage/netaddress_test.go index a57036c0f..b9e3b5031 100644 --- a/wire/netaddress_test.go +++ b/domainmessage/netaddress_test.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "net" diff --git a/wire/protocol.go b/domainmessage/protocol.go similarity index 99% rename from wire/protocol.go rename to domainmessage/protocol.go index 3db0b1f72..08bd9fdf6 100644 --- a/wire/protocol.go +++ b/domainmessage/protocol.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import ( "fmt" diff --git a/wire/protocol_test.go b/domainmessage/protocol_test.go similarity index 98% rename from wire/protocol_test.go rename to domainmessage/protocol_test.go index 0fee64bb8..5176566b6 100644 --- a/wire/protocol_test.go +++ b/domainmessage/protocol_test.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. -package wire +package domainmessage import "testing" diff --git a/wire/testdata/megatx.bin.bz2 b/domainmessage/testdata/megatx.bin.bz2 similarity index 100% rename from wire/testdata/megatx.bin.bz2 rename to domainmessage/testdata/megatx.bin.bz2 diff --git a/integration/64_incoming_connections_test.go b/integration/64_incoming_connections_test.go index 15dc7ecf2..1f10cb81e 100644 --- a/integration/64_incoming_connections_test.go +++ b/integration/64_incoming_connections_test.go @@ -8,7 +8,7 @@ import ( "github.com/kaspanet/kaspad/util/locks" - "github.com/kaspanet/kaspad/wire" + "github.com/kaspanet/kaspad/domainmessage" ) func Test64IncomingConnections(t *testing.T) { @@ -42,7 +42,7 @@ func Test64IncomingConnections(t *testing.T) { } blockAdded := false - bully.rpcClient.onBlockAdded = func(header *wire.BlockHeader) { + bully.rpcClient.onBlockAdded = func(header *domainmessage.BlockHeader) { if blockAdded { t.Fatalf("Single bully reported block added twice") } diff --git a/integration/basic_sync_test.go b/integration/basic_sync_test.go index 076763a04..a28b0514b 100644 --- a/integration/basic_sync_test.go +++ b/integration/basic_sync_test.go @@ -4,7 +4,7 @@ import ( "testing" "time" - "github.com/kaspanet/kaspad/wire" + "github.com/kaspanet/kaspad/domainmessage" ) func TestIntegrationBasicSync(t *testing.T) { @@ -16,19 +16,19 @@ func TestIntegrationBasicSync(t *testing.T) { connect(t, appHarness1, appHarness2) connect(t, appHarness2, appHarness3) - app2OnBlockAddedChan := make(chan *wire.BlockHeader) - setOnBlockAddedHandler(t, appHarness2, func(header *wire.BlockHeader) { + app2OnBlockAddedChan := make(chan *domainmessage.BlockHeader) + setOnBlockAddedHandler(t, appHarness2, func(header *domainmessage.BlockHeader) { app2OnBlockAddedChan <- header }) - app3OnBlockAddedChan := make(chan *wire.BlockHeader) - setOnBlockAddedHandler(t, appHarness3, func(header *wire.BlockHeader) { + app3OnBlockAddedChan := make(chan *domainmessage.BlockHeader) + setOnBlockAddedHandler(t, appHarness3, func(header *domainmessage.BlockHeader) { app3OnBlockAddedChan <- header }) block := mineNextBlock(t, appHarness1) - var header *wire.BlockHeader + var header *domainmessage.BlockHeader select { case header = <-app2OnBlockAddedChan: case <-time.After(defaultTimeout): diff --git a/integration/ibd_test.go b/integration/ibd_test.go index cc4acaed3..3eecdd58a 100644 --- a/integration/ibd_test.go +++ b/integration/ibd_test.go @@ -7,7 +7,7 @@ import ( "github.com/kaspanet/kaspad/util/locks" - "github.com/kaspanet/kaspad/wire" + "github.com/kaspanet/kaspad/domainmessage" ) func TestIBD(t *testing.T) { @@ -23,7 +23,7 @@ func TestIBD(t *testing.T) { blockAddedWG := sync.WaitGroup{} blockAddedWG.Add(numBlocks) receivedBlocks := 0 - setOnBlockAddedHandler(t, syncee, func(header *wire.BlockHeader) { + setOnBlockAddedHandler(t, syncee, func(header *domainmessage.BlockHeader) { receivedBlocks++ blockAddedWG.Done() }) diff --git a/integration/mining_test.go b/integration/mining_test.go index 10cca6c9e..e4d25acb4 100644 --- a/integration/mining_test.go +++ b/integration/mining_test.go @@ -6,12 +6,12 @@ import ( clientpkg "github.com/kaspanet/kaspad/rpc/client" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) -func solveBlock(block *util.Block) *wire.MsgBlock { +func solveBlock(block *util.Block) *domainmessage.MsgBlock { msgBlock := block.MsgBlock() targetDifficulty := util.CompactToBig(msgBlock.Header.Bits) initialNonce := rand.Uint64() diff --git a/integration/notifications_test.go b/integration/notifications_test.go index 12fa958b5..87f8a6c8d 100644 --- a/integration/notifications_test.go +++ b/integration/notifications_test.go @@ -3,10 +3,10 @@ package integration import ( "testing" - "github.com/kaspanet/kaspad/wire" + "github.com/kaspanet/kaspad/domainmessage" ) -func setOnBlockAddedHandler(t *testing.T, harness *appHarness, handler func(header *wire.BlockHeader)) { +func setOnBlockAddedHandler(t *testing.T, harness *appHarness, handler func(header *domainmessage.BlockHeader)) { err := harness.rpcClient.NotifyBlocks() if err != nil { t.Fatalf("Error from NotifyBlocks: %s", err) diff --git a/integration/rpc_test.go b/integration/rpc_test.go index 557f2d93c..1d633dd2a 100644 --- a/integration/rpc_test.go +++ b/integration/rpc_test.go @@ -1,21 +1,21 @@ package integration import ( + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util" - "github.com/kaspanet/kaspad/wire" rpcclient "github.com/kaspanet/kaspad/rpc/client" ) type rpcClient struct { *rpcclient.Client - onBlockAdded func(*wire.BlockHeader) + onBlockAdded func(*domainmessage.BlockHeader) } func newRPCClient(rpcAddress string) (*rpcClient, error) { client := &rpcClient{} notificationHandlers := &rpcclient.NotificationHandlers{ - OnFilteredBlockAdded: func(height uint64, header *wire.BlockHeader, txs []*util.Tx) { + OnFilteredBlockAdded: func(height uint64, header *domainmessage.BlockHeader, txs []*util.Tx) { if client.onBlockAdded != nil { client.onBlockAdded(header) } diff --git a/integration/tx_relay_test.go b/integration/tx_relay_test.go index 2d5615762..d6371a7c7 100644 --- a/integration/tx_relay_test.go +++ b/integration/tx_relay_test.go @@ -7,9 +7,9 @@ import ( "time" "github.com/kaspanet/go-secp256k1" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/txscript" "github.com/kaspanet/kaspad/util" - "github.com/kaspanet/kaspad/wire" ) func TestTxRelay(t *testing.T) { @@ -21,8 +21,8 @@ func TestTxRelay(t *testing.T) { connect(t, payer, mediator) connect(t, mediator, payee) - payeeBlockAddedChan := make(chan *wire.BlockHeader) - setOnBlockAddedHandler(t, payee, func(header *wire.BlockHeader) { + payeeBlockAddedChan := make(chan *domainmessage.BlockHeader) + setOnBlockAddedHandler(t, payee, func(header *domainmessage.BlockHeader) { payeeBlockAddedChan <- header }) // skip the first block because it's paying to genesis script @@ -70,7 +70,7 @@ func TestTxRelay(t *testing.T) { } } -func waitForPayeeToReceiveBlock(t *testing.T, payeeBlockAddedChan chan *wire.BlockHeader) { +func waitForPayeeToReceiveBlock(t *testing.T, payeeBlockAddedChan chan *domainmessage.BlockHeader) { select { case <-payeeBlockAddedChan: case <-time.After(defaultTimeout): @@ -78,9 +78,9 @@ func waitForPayeeToReceiveBlock(t *testing.T, payeeBlockAddedChan chan *wire.Blo } } -func generateTx(t *testing.T, firstBlockCoinbase *wire.MsgTx, payer, payee *appHarness) *wire.MsgTx { - txIns := make([]*wire.TxIn, 1) - txIns[0] = wire.NewTxIn(wire.NewOutpoint(firstBlockCoinbase.TxID(), 0), []byte{}) +func generateTx(t *testing.T, firstBlockCoinbase *domainmessage.MsgTx, payer, payee *appHarness) *domainmessage.MsgTx { + txIns := make([]*domainmessage.TxIn, 1) + txIns[0] = domainmessage.NewTxIn(domainmessage.NewOutpoint(firstBlockCoinbase.TxID(), 0), []byte{}) payeeAddress, err := util.DecodeAddress(payee.miningAddress, util.Bech32PrefixKaspaSim) if err != nil { @@ -91,11 +91,11 @@ func generateTx(t *testing.T, firstBlockCoinbase *wire.MsgTx, payer, payee *appH t.Fatalf("Error generating script: %+v", err) } - txOuts := []*wire.TxOut{wire.NewTxOut(firstBlockCoinbase.TxOut[0].Value-1, toScript)} + txOuts := []*domainmessage.TxOut{domainmessage.NewTxOut(firstBlockCoinbase.TxOut[0].Value-1, toScript)} fromScript := firstBlockCoinbase.TxOut[0].ScriptPubKey - tx := wire.NewNativeMsgTx(wire.TxVersion, txIns, txOuts) + tx := domainmessage.NewNativeMsgTx(domainmessage.TxVersion, txIns, txOuts) privateKeyBytes, err := hex.DecodeString(payer.miningAddressPrivateKey) if err != nil { diff --git a/mempool/error.go b/mempool/error.go index 1b81a3ba9..09b18698b 100644 --- a/mempool/error.go +++ b/mempool/error.go @@ -150,7 +150,7 @@ func extractRejectCode(err error) (RejectCode, bool) { } // ErrToRejectErr examines the underlying type of the error and returns a reject -// code and string appropriate to be sent in a wire.MsgReject message. +// code and string appropriate to be sent in a domainmessage.MsgReject message. func ErrToRejectErr(err error) (RejectCode, string) { // Return the reject code along with the error text if it can be // extracted from the error. diff --git a/mempool/mempool.go b/mempool/mempool.go index 38c2c3b71..66afce177 100644 --- a/mempool/mempool.go +++ b/mempool/mempool.go @@ -15,13 +15,13 @@ import ( "github.com/pkg/errors" "github.com/kaspanet/kaspad/blockdag" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/logger" "github.com/kaspanet/kaspad/mining" "github.com/kaspanet/kaspad/txscript" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/subnetworkid" - "github.com/kaspanet/kaspad/wire" ) const ( @@ -129,10 +129,10 @@ type TxPool struct { cfg Config pool map[daghash.TxID]*TxDesc depends map[daghash.TxID]*TxDesc - dependsByPrev map[wire.Outpoint]map[daghash.TxID]*TxDesc + dependsByPrev map[domainmessage.Outpoint]map[daghash.TxID]*TxDesc orphans map[daghash.TxID]*orphanTx - orphansByPrev map[wire.Outpoint]map[daghash.TxID]*util.Tx - outpoints map[wire.Outpoint]*util.Tx + orphansByPrev map[domainmessage.Outpoint]map[daghash.TxID]*util.Tx + outpoints map[domainmessage.Outpoint]*util.Tx // nextExpireScan is the time after which the orphan pool will be // scanned in order to evict orphans. This is NOT a hard deadline as @@ -174,7 +174,7 @@ func (mp *TxPool) removeOrphan(tx *util.Tx, removeRedeemers bool) { // Remove any orphans that redeem outputs from this one if requested. if removeRedeemers { - prevOut := wire.Outpoint{TxID: *txID} + prevOut := domainmessage.Outpoint{TxID: *txID} for txOutIdx := range tx.MsgTx().TxOut { prevOut.Index = uint32(txOutIdx) for _, orphan := range mp.orphansByPrev[prevOut] { @@ -479,7 +479,7 @@ func (mp *TxPool) removeTransaction(tx *util.Tx, removeDependants bool, restoreI if removeDependants { // Remove any transactions which rely on this one. for i := uint32(0); i < uint32(len(tx.MsgTx().TxOut)); i++ { - prevOut := wire.Outpoint{TxID: *txID, Index: i} + prevOut := domainmessage.Outpoint{TxID: *txID, Index: i} if txRedeemer, exists := mp.outpoints[prevOut]; exists { err := mp.removeTransaction(txRedeemer, true, false) if err != nil { @@ -541,7 +541,7 @@ func (mp *TxPool) removeTransactionWithDiff(tx *util.Tx, diff *blockdag.UTXODiff // removeTransactionUTXOEntriesFromDiff removes tx's UTXOEntries from the diff func (mp *TxPool) removeTransactionUTXOEntriesFromDiff(tx *util.Tx, diff *blockdag.UTXODiff) error { for idx := range tx.MsgTx().TxOut { - outpoint := *wire.NewOutpoint(tx.ID(), uint32(idx)) + outpoint := *domainmessage.NewOutpoint(tx.ID(), uint32(idx)) entry, exists := mp.mpUTXOSet.Get(outpoint) if exists { err := diff.RemoveEntry(outpoint, entry) @@ -583,7 +583,7 @@ func (mp *TxPool) markTransactionOutputsUnspent(tx *util.Tx, diff *blockdag.UTXO // processRemovedTransactionDependencies processes the dependencies of a // transaction tx that was just now removed from the mempool func (mp *TxPool) processRemovedTransactionDependencies(tx *util.Tx) { - prevOut := wire.Outpoint{TxID: *tx.ID()} + prevOut := domainmessage.Outpoint{TxID: *tx.ID()} for txOutIdx := range tx.MsgTx().TxOut { // Skip to the next available output if there are none. prevOut.Index = uint32(txOutIdx) @@ -664,7 +664,7 @@ func (mp *TxPool) removeDoubleSpends(tx *util.Tx) error { // helper for maybeAcceptTransaction. // // This function MUST be called with the mempool lock held (for writes). -func (mp *TxPool) addTransaction(tx *util.Tx, fee uint64, parentsInPool []*wire.Outpoint) (*TxDesc, error) { +func (mp *TxPool) addTransaction(tx *util.Tx, fee uint64, parentsInPool []*domainmessage.Outpoint) (*TxDesc, error) { // Add the transaction to the pool and mark the referenced outpoints // as spent by the pool. mass, err := blockdag.CalcTxMassFromUTXOSet(tx, mp.mpUTXOSet) @@ -728,7 +728,7 @@ func (mp *TxPool) checkPoolDoubleSpend(tx *util.Tx) error { // CheckSpend checks whether the passed outpoint is already spent by a // transaction in the mempool. If that's the case the spending transaction will // be returned, if not nil will be returned. -func (mp *TxPool) CheckSpend(op wire.Outpoint) *util.Tx { +func (mp *TxPool) CheckSpend(op domainmessage.Outpoint) *util.Tx { mp.mtx.RLock() defer mp.mtx.RUnlock() txR := mp.outpoints[op] @@ -783,9 +783,9 @@ func (mp *TxPool) FetchTransaction(txID *daghash.TxID) (*util.Tx, bool) { // checkTransactionMassSanity checks that a transaction must not exceed the maximum allowed block mass when serialized. func checkTransactionMassSanity(tx *util.Tx) error { serializedTxSize := tx.MsgTx().SerializeSize() - if serializedTxSize*blockdag.MassPerTxByte > wire.MaxMassPerTx { + if serializedTxSize*blockdag.MassPerTxByte > domainmessage.MaxMassPerTx { str := fmt.Sprintf("serialized transaction is too big - got "+ - "%d, max %d", serializedTxSize, wire.MaxMassPerBlock) + "%d, max %d", serializedTxSize, domainmessage.MaxMassPerBlock) return txRuleError(RejectInvalid, str) } return nil @@ -912,7 +912,7 @@ func (mp *TxPool) maybeAcceptTransaction(tx *util.Tx, rejectDupOrphans bool) ([] // Don't allow the transaction if it exists in the DAG and is // not already fully spent. - prevOut := wire.Outpoint{TxID: *txID} + prevOut := domainmessage.Outpoint{TxID: *txID} for txOutIdx := range tx.MsgTx().TxOut { prevOut.Index = uint32(txOutIdx) _, ok := mp.mpUTXOSet.Get(prevOut) @@ -927,7 +927,7 @@ func (mp *TxPool) maybeAcceptTransaction(tx *util.Tx, rejectDupOrphans bool) ([] // is not handled by this function, and the caller should use // maybeAddOrphan if this behavior is desired. var missingParents []*daghash.TxID - var parentsInPool []*wire.Outpoint + var parentsInPool []*domainmessage.Outpoint for _, txIn := range tx.MsgTx().TxIn { if _, ok := mp.mpUTXOSet.Get(txIn.PreviousOutpoint); !ok { // Must make a copy of the hash here since the iterator @@ -1075,7 +1075,7 @@ func (mp *TxPool) processOrphans(acceptedTx *util.Tx) []*TxDesc { firstElement := processList.Remove(processList.Front()) processItem := firstElement.(*util.Tx) - prevOut := wire.Outpoint{TxID: *processItem.ID()} + prevOut := domainmessage.Outpoint{TxID: *processItem.ID()} for txOutIdx := range processItem.MsgTx().TxOut { // Look up all orphans that redeem the output that is // now available. This will typically only be one, but @@ -1392,11 +1392,11 @@ func New(cfg *Config) *TxPool { cfg: *cfg, pool: make(map[daghash.TxID]*TxDesc), depends: make(map[daghash.TxID]*TxDesc), - dependsByPrev: make(map[wire.Outpoint]map[daghash.TxID]*TxDesc), + dependsByPrev: make(map[domainmessage.Outpoint]map[daghash.TxID]*TxDesc), orphans: make(map[daghash.TxID]*orphanTx), - orphansByPrev: make(map[wire.Outpoint]map[daghash.TxID]*util.Tx), + orphansByPrev: make(map[domainmessage.Outpoint]map[daghash.TxID]*util.Tx), nextExpireScan: mstime.Now().Add(orphanExpireScanInterval), - outpoints: make(map[wire.Outpoint]*util.Tx), + outpoints: make(map[domainmessage.Outpoint]*util.Tx), mpUTXOSet: mpUTXO, } } diff --git a/mempool/mempool_test.go b/mempool/mempool_test.go index 5f71decd2..43fa41339 100644 --- a/mempool/mempool_test.go +++ b/mempool/mempool_test.go @@ -22,11 +22,11 @@ import ( "github.com/kaspanet/kaspad/blockdag" "github.com/kaspanet/kaspad/dagconfig" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/mining" "github.com/kaspanet/kaspad/txscript" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) // fakeDAG is used by the pool harness to provide generated test utxos and @@ -82,7 +82,7 @@ func calcSequenceLock(tx *util.Tx, // spendableOutpoint is a convenience type that houses a particular utxo and the // amount associated with it. type spendableOutpoint struct { - outpoint wire.Outpoint + outpoint domainmessage.Outpoint amount util.Amount } @@ -91,7 +91,7 @@ type spendableOutpoint struct { // transactions. func txOutToSpendableOutpoint(tx *util.Tx, outputNum uint32) spendableOutpoint { return spendableOutpoint{ - outpoint: wire.Outpoint{TxID: *tx.ID(), Index: outputNum}, + outpoint: domainmessage.Outpoint{TxID: *tx.ID(), Index: outputNum}, amount: util.Amount(tx.MsgTx().TxOut[outputNum].Value), } } @@ -125,16 +125,16 @@ func (p *poolHarness) CreateCoinbaseTx(blueScore uint64, numOutputs uint32) (*ut return nil, err } - txIns := []*wire.TxIn{{ + txIns := []*domainmessage.TxIn{{ // Coinbase transactions have no inputs, so previous outpoint is // zero hash and max index. - PreviousOutpoint: *wire.NewOutpoint(&daghash.TxID{}, - wire.MaxPrevOutIndex), + PreviousOutpoint: *domainmessage.NewOutpoint(&daghash.TxID{}, + domainmessage.MaxPrevOutIndex), SignatureScript: coinbaseScript, - Sequence: wire.MaxTxInSequenceNum, + Sequence: domainmessage.MaxTxInSequenceNum, }} - txOuts := []*wire.TxOut{} + txOuts := []*domainmessage.TxOut{} totalInput := blockdag.CalcBlockSubsidy(blueScore, p.dagParams) amountPerOutput := totalInput / uint64(numOutputs) remainder := totalInput - amountPerOutput*uint64(numOutputs) @@ -145,13 +145,13 @@ func (p *poolHarness) CreateCoinbaseTx(blueScore uint64, numOutputs uint32) (*ut if i == numOutputs-1 { amount = amountPerOutput + remainder } - txOuts = append(txOuts, &wire.TxOut{ + txOuts = append(txOuts, &domainmessage.TxOut{ ScriptPubKey: p.payScript, Value: amount, }) } - return util.NewTx(wire.NewNativeMsgTx(wire.TxVersion, txIns, txOuts)), nil + return util.NewTx(domainmessage.NewNativeMsgTx(domainmessage.TxVersion, txIns, txOuts)), nil } // CreateSignedTxForSubnetwork creates a new signed transaction that consumes the provided @@ -169,16 +169,16 @@ func (p *poolHarness) CreateSignedTxForSubnetwork(inputs []spendableOutpoint, nu amountPerOutput := uint64(totalInput) / uint64(numOutputs) remainder := uint64(totalInput) - amountPerOutput*uint64(numOutputs) - var txIns []*wire.TxIn + var txIns []*domainmessage.TxIn for _, input := range inputs { - txIns = append(txIns, &wire.TxIn{ + txIns = append(txIns, &domainmessage.TxIn{ PreviousOutpoint: input.outpoint, SignatureScript: p.signatureScript, - Sequence: wire.MaxTxInSequenceNum, + Sequence: domainmessage.MaxTxInSequenceNum, }) } - var txOuts []*wire.TxOut + var txOuts []*domainmessage.TxOut for i := uint32(0); i < numOutputs; i++ { // Ensure the final output accounts for any remainder that might // be left from splitting the input amount. @@ -186,13 +186,13 @@ func (p *poolHarness) CreateSignedTxForSubnetwork(inputs []spendableOutpoint, nu if i == numOutputs-1 { amount = amountPerOutput + remainder } - txOuts = append(txOuts, &wire.TxOut{ + txOuts = append(txOuts, &domainmessage.TxOut{ ScriptPubKey: p.payScript, Value: amount, }) } - tx := wire.NewSubnetworkMsgTx(wire.TxVersion, txIns, txOuts, subnetworkID, gas, []byte{}) + tx := domainmessage.NewSubnetworkMsgTx(domainmessage.TxVersion, txIns, txOuts, subnetworkID, gas, []byte{}) // Sign the new transaction. for i := range tx.TxIn { @@ -224,21 +224,21 @@ func (p *poolHarness) CreateTxChain(firstOutput spendableOutpoint, numTxns uint3 // associated with the harness. spendableAmount = spendableAmount - txRelayFeeForTest - txIn := &wire.TxIn{ + txIn := &domainmessage.TxIn{ PreviousOutpoint: prevOutpoint, SignatureScript: p.signatureScript, - Sequence: wire.MaxTxInSequenceNum, + Sequence: domainmessage.MaxTxInSequenceNum, } - txOut := &wire.TxOut{ + txOut := &domainmessage.TxOut{ ScriptPubKey: p.payScript, Value: uint64(spendableAmount), } - tx := wire.NewNativeMsgTx(wire.TxVersion, []*wire.TxIn{txIn}, []*wire.TxOut{txOut}) + tx := domainmessage.NewNativeMsgTx(domainmessage.TxVersion, []*domainmessage.TxIn{txIn}, []*domainmessage.TxOut{txOut}) txChain = append(txChain, util.NewTx(tx)) // Next transaction uses outputs from this one. - prevOutpoint = wire.Outpoint{TxID: *tx.TxID(), Index: 0} + prevOutpoint = domainmessage.Outpoint{TxID: *tx.TxID(), Index: 0} } return txChain, nil @@ -246,12 +246,12 @@ func (p *poolHarness) CreateTxChain(firstOutput spendableOutpoint, numTxns uint3 func (tc *testContext) mineTransactions(transactions []*util.Tx, numberOfBlocks uint64) []spendableOutpoint { var outpoints []spendableOutpoint - msgTxs := make([]*wire.MsgTx, len(transactions)) + msgTxs := make([]*domainmessage.MsgTx, len(transactions)) for i, tx := range transactions { msgTxs[i] = tx.MsgTx() } for i := uint64(0); i < numberOfBlocks; i++ { - var blockTxs []*wire.MsgTx + var blockTxs []*domainmessage.MsgTx if i == 0 { blockTxs = msgTxs } @@ -292,7 +292,7 @@ func (tc *testContext) mineTransactions(transactions []*util.Tx, numberOfBlocks for i, txOut := range coinbaseTx.TxOut { outpoints = append(outpoints, spendableOutpoint{ - outpoint: *wire.NewOutpoint(coinbaseTx.TxID(), uint32(i)), + outpoint: *domainmessage.NewOutpoint(coinbaseTx.TxID(), uint32(i)), amount: util.Amount(txOut.Value), }) } @@ -455,21 +455,21 @@ func testPoolMembership(tc *testContext, tx *util.Tx, inOrphanPool, inTxPool boo } func (p *poolHarness) createTx(outpoint spendableOutpoint, fee uint64, numOutputs int64) (*util.Tx, error) { - txIns := []*wire.TxIn{{ + txIns := []*domainmessage.TxIn{{ PreviousOutpoint: outpoint.outpoint, SignatureScript: nil, - Sequence: wire.MaxTxInSequenceNum, + Sequence: domainmessage.MaxTxInSequenceNum, }} - var txOuts []*wire.TxOut + var txOuts []*domainmessage.TxOut amountPerOutput := (uint64(outpoint.amount) - fee) / uint64(numOutputs) for i := int64(0); i < numOutputs; i++ { - txOuts = append(txOuts, &wire.TxOut{ + txOuts = append(txOuts, &domainmessage.TxOut{ ScriptPubKey: p.payScript, Value: amountPerOutput, }) } - tx := wire.NewNativeMsgTx(wire.TxVersion, txIns, txOuts) + tx := domainmessage.NewNativeMsgTx(domainmessage.TxVersion, txIns, txOuts) // Sign the new transaction. tx.TxIn[0].SignatureScript = p.signatureScript @@ -506,7 +506,7 @@ func TestProcessTransaction(t *testing.T) { orphanedTx, err := harness.CreateSignedTx([]spendableOutpoint{{ amount: util.Amount(5000000000), - outpoint: wire.Outpoint{TxID: daghash.TxID{}, Index: 1}, + outpoint: domainmessage.Outpoint{TxID: daghash.TxID{}, Index: 1}, }}, 1) if err != nil { t.Fatalf("unable to create signed tx: %v", err) @@ -574,7 +574,7 @@ func TestProcessTransaction(t *testing.T) { if err != nil { t.Fatalf("Unexpected error from harness.createTx: %s", err) } - nonStdTx.MsgTx().Version = wire.TxVersion + 1 + nonStdTx.MsgTx().Version = domainmessage.TxVersion + 1 _, err = harness.txPool.ProcessTransaction(nonStdTx, true, 0) if err == nil { t.Errorf("ProcessTransaction: expected an error, not nil") @@ -641,7 +641,7 @@ func TestProcessTransaction(t *testing.T) { if err != nil { t.Fatalf("NewShaHashFromStr: unexpected error: %v", err) } - dummyPrevOut := wire.Outpoint{TxID: *dummyPrevOutTxID, Index: 1} + dummyPrevOut := domainmessage.Outpoint{TxID: *dummyPrevOutTxID, Index: 1} dummySigScript := bytes.Repeat([]byte{0x00}, 65) addrHash := [20]byte{0x01} @@ -654,23 +654,23 @@ func TestProcessTransaction(t *testing.T) { if err != nil { t.Fatalf("PayToAddrScript: unexpected error: %v", err) } - p2shTx := util.NewTx(wire.NewNativeMsgTx(1, nil, []*wire.TxOut{{Value: 5000000000, ScriptPubKey: p2shScriptPubKey}})) + p2shTx := util.NewTx(domainmessage.NewNativeMsgTx(1, nil, []*domainmessage.TxOut{{Value: 5000000000, ScriptPubKey: p2shScriptPubKey}})) if isAccepted, err := harness.txPool.mpUTXOSet.AddTx(p2shTx.MsgTx(), currentBlueScore+1); err != nil { t.Fatalf("AddTx unexpectedly failed. Error: %s", err) } else if !isAccepted { t.Fatalf("AddTx unexpectedly didn't add tx %s", p2shTx.ID()) } - txIns := []*wire.TxIn{{ - PreviousOutpoint: wire.Outpoint{TxID: *p2shTx.ID(), Index: 0}, + txIns := []*domainmessage.TxIn{{ + PreviousOutpoint: domainmessage.Outpoint{TxID: *p2shTx.ID(), Index: 0}, SignatureScript: wrappedP2SHNonStdSigScript, - Sequence: wire.MaxTxInSequenceNum, + Sequence: domainmessage.MaxTxInSequenceNum, }} - txOuts := []*wire.TxOut{{ + txOuts := []*domainmessage.TxOut{{ Value: 5000000000, ScriptPubKey: dummyScriptPubKey, }} - nonStdSigScriptTx := util.NewTx(wire.NewNativeMsgTx(1, txIns, txOuts)) + nonStdSigScriptTx := util.NewTx(domainmessage.NewNativeMsgTx(1, txIns, txOuts)) _, err = harness.txPool.ProcessTransaction(nonStdSigScriptTx, true, 0) if err == nil { t.Errorf("ProcessTransaction: expected an error, not nil") @@ -688,10 +688,10 @@ func TestProcessTransaction(t *testing.T) { } // Checks that a transaction with no outputs will not get rejected - noOutsTx := util.NewTx(wire.NewNativeMsgTx(1, []*wire.TxIn{{ + noOutsTx := util.NewTx(domainmessage.NewNativeMsgTx(1, []*domainmessage.TxIn{{ PreviousOutpoint: dummyPrevOut, SignatureScript: dummySigScript, - Sequence: wire.MaxTxInSequenceNum, + Sequence: domainmessage.MaxTxInSequenceNum, }}, nil)) _, err = harness.txPool.ProcessTransaction(noOutsTx, true, 0) @@ -738,16 +738,16 @@ func TestProcessTransaction(t *testing.T) { t.Errorf("Unexpected error code. Expected %v but got %v", RejectInsufficientFee, code) } - txIns = []*wire.TxIn{{ + txIns = []*domainmessage.TxIn{{ PreviousOutpoint: spendableOuts[5].outpoint, SignatureScript: []byte{02, 01}, // Unparsable script - Sequence: wire.MaxTxInSequenceNum, + Sequence: domainmessage.MaxTxInSequenceNum, }} - txOuts = []*wire.TxOut{{ + txOuts = []*domainmessage.TxOut{{ Value: 1, ScriptPubKey: dummyScriptPubKey, }} - tx = util.NewTx(wire.NewNativeMsgTx(1, txIns, txOuts)) + tx = util.NewTx(domainmessage.NewNativeMsgTx(1, txIns, txOuts)) _, err = harness.txPool.ProcessTransaction(tx, true, 0) fmt.Println(err) if err == nil { @@ -826,7 +826,7 @@ func TestDoubleSpendsFromDAG(t *testing.T) { } dag := harness.txPool.cfg.DAG - blockdag.PrepareAndProcessBlockForTest(t, dag, dag.TipHashes(), []*wire.MsgTx{tx.MsgTx()}) + blockdag.PrepareAndProcessBlockForTest(t, dag, dag.TipHashes(), []*domainmessage.MsgTx{tx.MsgTx()}) // Check that a transaction that double spends the DAG UTXO set is orphaned. doubleSpendTx, err := harness.createTx(spendableOuts[0], uint64(txRelayFeeForTest), 2) @@ -875,7 +875,7 @@ func TestFetchTransaction(t *testing.T) { orphanedTx, err := harness.CreateSignedTx([]spendableOutpoint{{ amount: util.Amount(5000000000), - outpoint: wire.Outpoint{TxID: daghash.TxID{1}, Index: 1}, + outpoint: domainmessage.Outpoint{TxID: daghash.TxID{1}, Index: 1}, }}, 1) if err != nil { t.Fatalf("unable to create signed tx: %v", err) @@ -1035,7 +1035,7 @@ func TestOrphanExpiration(t *testing.T) { expiredTx, err := harness.CreateSignedTx([]spendableOutpoint{{ amount: util.Amount(5000000000), - outpoint: wire.Outpoint{TxID: daghash.TxID{}, Index: 0}, + outpoint: domainmessage.Outpoint{TxID: daghash.TxID{}, Index: 0}, }}, 1) if err != nil { t.Fatalf("Unexpected error on harness.CreateSignedTx: %s", err) @@ -1049,7 +1049,7 @@ func TestOrphanExpiration(t *testing.T) { tx1, err := harness.CreateSignedTx([]spendableOutpoint{{ amount: util.Amount(5000000000), - outpoint: wire.Outpoint{TxID: daghash.TxID{1}, Index: 0}, + outpoint: domainmessage.Outpoint{TxID: daghash.TxID{1}, Index: 0}, }}, 1) if err != nil { t.Fatalf("Unexpected error on harness.CreateSignedTx: %s", err) @@ -1069,7 +1069,7 @@ func TestOrphanExpiration(t *testing.T) { tx2, err := harness.CreateSignedTx([]spendableOutpoint{{ amount: util.Amount(5000000000), - outpoint: wire.Outpoint{TxID: daghash.TxID{2}, Index: 0}, + outpoint: domainmessage.Outpoint{TxID: daghash.TxID{2}, Index: 0}, }}, 1) if err != nil { t.Fatalf("Unexpected error on harness.CreateSignedTx: %s", err) @@ -1098,7 +1098,7 @@ func TestMaxOrphanTxSize(t *testing.T) { tx, err := harness.CreateSignedTx([]spendableOutpoint{{ amount: util.Amount(5000000000), - outpoint: wire.Outpoint{TxID: daghash.TxID{}, Index: 0}, + outpoint: domainmessage.Outpoint{TxID: daghash.TxID{}, Index: 0}, }}, 1) if err != nil { t.Fatalf("unable to create signed tx: %v", err) @@ -1227,7 +1227,7 @@ func TestRemoveOrphansByTag(t *testing.T) { orphanedTx1, err := harness.CreateSignedTx([]spendableOutpoint{{ amount: util.Amount(5000000000), - outpoint: wire.Outpoint{TxID: daghash.TxID{1}, Index: 1}, + outpoint: domainmessage.Outpoint{TxID: daghash.TxID{1}, Index: 1}, }}, 1) if err != nil { t.Fatalf("unable to create signed tx: %v", err) @@ -1235,7 +1235,7 @@ func TestRemoveOrphansByTag(t *testing.T) { harness.txPool.ProcessTransaction(orphanedTx1, true, 1) orphanedTx2, err := harness.CreateSignedTx([]spendableOutpoint{{ amount: util.Amount(5000000000), - outpoint: wire.Outpoint{TxID: daghash.TxID{2}, Index: 2}, + outpoint: domainmessage.Outpoint{TxID: daghash.TxID{2}, Index: 2}, }}, 1) if err != nil { t.Fatalf("unable to create signed tx: %v", err) @@ -1243,7 +1243,7 @@ func TestRemoveOrphansByTag(t *testing.T) { harness.txPool.ProcessTransaction(orphanedTx2, true, 1) orphanedTx3, err := harness.CreateSignedTx([]spendableOutpoint{{ amount: util.Amount(5000000000), - outpoint: wire.Outpoint{TxID: daghash.TxID{3}, Index: 3}, + outpoint: domainmessage.Outpoint{TxID: daghash.TxID{3}, Index: 3}, }}, 1) if err != nil { t.Fatalf("unable to create signed tx: %v", err) @@ -1252,7 +1252,7 @@ func TestRemoveOrphansByTag(t *testing.T) { orphanedTx4, err := harness.CreateSignedTx([]spendableOutpoint{{ amount: util.Amount(5000000000), - outpoint: wire.Outpoint{TxID: daghash.TxID{4}, Index: 4}, + outpoint: domainmessage.Outpoint{TxID: daghash.TxID{4}, Index: 4}, }}, 1) if err != nil { t.Fatalf("unable to create signed tx: %v", err) @@ -1312,7 +1312,7 @@ func TestBasicOrphanRemoval(t *testing.T) { // and ensure the state of all other orphans are unaffected. nonChainedOrphanTx, err := harness.CreateSignedTx([]spendableOutpoint{{ amount: util.Amount(5000000000), - outpoint: wire.Outpoint{TxID: daghash.TxID{}, Index: 0}, + outpoint: domainmessage.Outpoint{TxID: daghash.TxID{}, Index: 0}, }}, 1) if err != nil { t.Fatalf("unable to create signed tx: %v", err) @@ -1536,7 +1536,7 @@ func TestCheckSpend(t *testing.T) { // Now all but the last tx should be spent by the next. for i := 0; i < len(chainedTxns)-1; i++ { - op = wire.Outpoint{ + op = domainmessage.Outpoint{ TxID: *chainedTxns[i].ID(), Index: 0, } @@ -1549,7 +1549,7 @@ func TestCheckSpend(t *testing.T) { } // The last tx should have no spend. - op = wire.Outpoint{ + op = domainmessage.Outpoint{ TxID: *chainedTxns[txChainLength-1].ID(), Index: 0, } @@ -1681,7 +1681,7 @@ func TestHandleNewBlock(t *testing.T) { orphanTx, err := harness.CreateSignedTx([]spendableOutpoint{{ amount: util.Amount(2500000000 - txRelayFeeForTest), - outpoint: wire.Outpoint{TxID: *txID, Index: 0}, + outpoint: domainmessage.Outpoint{TxID: *txID, Index: 0}, }}, 1) if err != nil { t.Fatalf("unable to create signed tx: %v", err) @@ -1757,8 +1757,8 @@ func TestHandleNewBlock(t *testing.T) { } // dummyBlock defines a block on the block DAG. It is used to test block operations. -var dummyBlock = wire.MsgBlock{ - Header: wire.BlockHeader{ +var dummyBlock = domainmessage.MsgBlock{ + Header: domainmessage.BlockHeader{ Version: 1, ParentHashes: []*daghash.Hash{ { @@ -1783,11 +1783,11 @@ var dummyBlock = wire.MsgBlock{ Bits: 0x1e00ffff, // 503382015 Nonce: 0x000ae53f, // 714047 }, - Transactions: []*wire.MsgTx{ + Transactions: []*domainmessage.MsgTx{ { Version: 1, - TxIn: []*wire.TxIn{}, - TxOut: []*wire.TxOut{ + TxIn: []*domainmessage.TxIn{}, + TxOut: []*domainmessage.TxOut{ { Value: 0x12a05f200, // 5000000000 ScriptPubKey: []byte{ diff --git a/mempool/policy.go b/mempool/policy.go index f3d09b942..89f312768 100644 --- a/mempool/policy.go +++ b/mempool/policy.go @@ -9,9 +9,9 @@ import ( "github.com/kaspanet/kaspad/util/mstime" "github.com/kaspanet/kaspad/blockdag" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/txscript" "github.com/kaspanet/kaspad/util" - "github.com/kaspanet/kaspad/wire" ) const ( @@ -118,7 +118,7 @@ func checkInputsStandard(tx *util.Tx, utxoSet blockdag.UTXOSet) error { // Dust is defined in terms of the minimum transaction 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. -func isDust(txOut *wire.TxOut, minRelayTxFee util.Amount) bool { +func isDust(txOut *domainmessage.TxOut, minRelayTxFee util.Amount) bool { // Unspendable outputs are considered dust. if txscript.IsUnspendable(txOut.ScriptPubKey) { return true diff --git a/mempool/policy_test.go b/mempool/policy_test.go index 5971d3b8d..ca4bc3cc5 100644 --- a/mempool/policy_test.go +++ b/mempool/policy_test.go @@ -6,11 +6,11 @@ package mempool import ( "bytes" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/txscript" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/mstime" - "github.com/kaspanet/kaspad/wire" "github.com/pkg/errors" "testing" ) @@ -102,47 +102,47 @@ func TestDust(t *testing.T) { tests := []struct { name string // test description - txOut wire.TxOut + txOut domainmessage.TxOut relayFee util.Amount // minimum relay transaction fee. isDust bool }{ { // Any value is allowed with a zero relay fee. "zero value with zero relay fee", - wire.TxOut{Value: 0, ScriptPubKey: scriptPubKey}, + domainmessage.TxOut{Value: 0, ScriptPubKey: scriptPubKey}, 0, false, }, { // Zero value is dust with any relay fee" "zero value with very small tx fee", - wire.TxOut{Value: 0, ScriptPubKey: scriptPubKey}, + domainmessage.TxOut{Value: 0, ScriptPubKey: scriptPubKey}, 1, true, }, { "38 byte public key script with value 584", - wire.TxOut{Value: 584, ScriptPubKey: scriptPubKey}, + domainmessage.TxOut{Value: 584, ScriptPubKey: scriptPubKey}, 1000, true, }, { "38 byte public key script with value 585", - wire.TxOut{Value: 585, ScriptPubKey: scriptPubKey}, + domainmessage.TxOut{Value: 585, ScriptPubKey: scriptPubKey}, 1000, false, }, { // Maximum allowed value is never dust. "max sompi amount is never dust", - wire.TxOut{Value: util.MaxSompi, ScriptPubKey: scriptPubKey}, + domainmessage.TxOut{Value: util.MaxSompi, ScriptPubKey: scriptPubKey}, util.MaxSompi, false, }, { // Maximum int64 value causes overflow. "maximum int64 value", - wire.TxOut{Value: 1<<63 - 1, ScriptPubKey: scriptPubKey}, + domainmessage.TxOut{Value: 1<<63 - 1, ScriptPubKey: scriptPubKey}, 1<<63 - 1, true, }, @@ -150,7 +150,7 @@ func TestDust(t *testing.T) { // Unspendable scriptPubKey due to an invalid public key // script. "unspendable scriptPubKey", - wire.TxOut{Value: 5000, ScriptPubKey: []byte{0x01}}, + domainmessage.TxOut{Value: 5000, ScriptPubKey: []byte{0x01}}, 0, // no relay fee true, }, @@ -172,12 +172,12 @@ func TestCheckTransactionStandard(t *testing.T) { if err != nil { t.Fatalf("NewShaHashFromStr: unexpected error: %v", err) } - dummyPrevOut := wire.Outpoint{TxID: *prevOutTxID, Index: 1} + dummyPrevOut := domainmessage.Outpoint{TxID: *prevOutTxID, Index: 1} dummySigScript := bytes.Repeat([]byte{0x00}, 65) - dummyTxIn := wire.TxIn{ + dummyTxIn := domainmessage.TxIn{ PreviousOutpoint: dummyPrevOut, SignatureScript: dummySigScript, - Sequence: wire.MaxTxInSequenceNum, + Sequence: domainmessage.MaxTxInSequenceNum, } addrHash := [20]byte{0x01} addr, err := util.NewAddressPubKeyHash(addrHash[:], util.Bech32PrefixKaspaTest) @@ -188,45 +188,45 @@ func TestCheckTransactionStandard(t *testing.T) { if err != nil { t.Fatalf("PayToAddrScript: unexpected error: %v", err) } - dummyTxOut := wire.TxOut{ + dummyTxOut := domainmessage.TxOut{ Value: 100000000, // 1 KAS ScriptPubKey: dummyScriptPubKey, } tests := []struct { name string - tx *wire.MsgTx + tx *domainmessage.MsgTx height uint64 isStandard bool code RejectCode }{ { name: "Typical pay-to-pubkey-hash transaction", - tx: wire.NewNativeMsgTx(1, []*wire.TxIn{&dummyTxIn}, []*wire.TxOut{&dummyTxOut}), + tx: domainmessage.NewNativeMsgTx(1, []*domainmessage.TxIn{&dummyTxIn}, []*domainmessage.TxOut{&dummyTxOut}), height: 300000, isStandard: true, }, { name: "Transaction version too high", - tx: wire.NewNativeMsgTx(wire.TxVersion+1, []*wire.TxIn{&dummyTxIn}, []*wire.TxOut{&dummyTxOut}), + tx: domainmessage.NewNativeMsgTx(domainmessage.TxVersion+1, []*domainmessage.TxIn{&dummyTxIn}, []*domainmessage.TxOut{&dummyTxOut}), height: 300000, isStandard: false, code: RejectNonstandard, }, { name: "Transaction is not finalized", - tx: wire.NewNativeMsgTxWithLocktime(1, []*wire.TxIn{{ + tx: domainmessage.NewNativeMsgTxWithLocktime(1, []*domainmessage.TxIn{{ PreviousOutpoint: dummyPrevOut, SignatureScript: dummySigScript, Sequence: 0, - }}, []*wire.TxOut{&dummyTxOut}, 300001), + }}, []*domainmessage.TxOut{&dummyTxOut}, 300001), height: 300000, isStandard: false, code: RejectNonstandard, }, { name: "Transaction size is too large", - tx: wire.NewNativeMsgTx(1, []*wire.TxIn{&dummyTxIn}, []*wire.TxOut{{ + tx: domainmessage.NewNativeMsgTx(1, []*domainmessage.TxIn{&dummyTxIn}, []*domainmessage.TxOut{{ Value: 0, ScriptPubKey: bytes.Repeat([]byte{0x00}, MaxStandardTxSize+1), @@ -237,31 +237,31 @@ func TestCheckTransactionStandard(t *testing.T) { }, { name: "Signature script size is too large", - tx: wire.NewNativeMsgTx(1, []*wire.TxIn{{ + tx: domainmessage.NewNativeMsgTx(1, []*domainmessage.TxIn{{ PreviousOutpoint: dummyPrevOut, SignatureScript: bytes.Repeat([]byte{0x00}, maxStandardSigScriptSize+1), - Sequence: wire.MaxTxInSequenceNum, - }}, []*wire.TxOut{&dummyTxOut}), + Sequence: domainmessage.MaxTxInSequenceNum, + }}, []*domainmessage.TxOut{&dummyTxOut}), height: 300000, isStandard: false, code: RejectNonstandard, }, { name: "Signature script that does more than push data", - tx: wire.NewNativeMsgTx(1, []*wire.TxIn{{ + tx: domainmessage.NewNativeMsgTx(1, []*domainmessage.TxIn{{ PreviousOutpoint: dummyPrevOut, SignatureScript: []byte{ txscript.OpCheckSigVerify}, - Sequence: wire.MaxTxInSequenceNum, - }}, []*wire.TxOut{&dummyTxOut}), + Sequence: domainmessage.MaxTxInSequenceNum, + }}, []*domainmessage.TxOut{&dummyTxOut}), height: 300000, isStandard: false, code: RejectNonstandard, }, { name: "Valid but non standard public key script", - tx: wire.NewNativeMsgTx(1, []*wire.TxIn{&dummyTxIn}, []*wire.TxOut{{ + tx: domainmessage.NewNativeMsgTx(1, []*domainmessage.TxIn{&dummyTxIn}, []*domainmessage.TxOut{{ Value: 100000000, ScriptPubKey: []byte{txscript.OpTrue}, }}), @@ -271,7 +271,7 @@ func TestCheckTransactionStandard(t *testing.T) { }, { name: "Dust output", - tx: wire.NewNativeMsgTx(1, []*wire.TxIn{&dummyTxIn}, []*wire.TxOut{{ + tx: domainmessage.NewNativeMsgTx(1, []*domainmessage.TxIn{&dummyTxIn}, []*domainmessage.TxOut{{ Value: 0, ScriptPubKey: dummyScriptPubKey, }}), @@ -281,7 +281,7 @@ func TestCheckTransactionStandard(t *testing.T) { }, { name: "Nulldata transaction", - tx: wire.NewNativeMsgTx(1, []*wire.TxIn{&dummyTxIn}, []*wire.TxOut{{ + tx: domainmessage.NewNativeMsgTx(1, []*domainmessage.TxIn{&dummyTxIn}, []*domainmessage.TxOut{{ Value: 0, ScriptPubKey: []byte{txscript.OpReturn}, }}), diff --git a/mining/mining.go b/mining/mining.go index 57e36a844..f027bdf21 100644 --- a/mining/mining.go +++ b/mining/mining.go @@ -10,10 +10,10 @@ import ( "time" "github.com/kaspanet/kaspad/blockdag" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/txscript" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) const ( @@ -65,7 +65,7 @@ type BlockTemplate struct { // Block is a block that is ready to be solved by miners. Thus, it is // completely valid with the exception of satisfying the proof-of-work // requirement. - Block *wire.MsgBlock + Block *domainmessage.MsgBlock // TxMasses contains the mass of each transaction in the generated // template performs. @@ -213,7 +213,7 @@ func (g *BlkTmplGenerator) NewBlockTemplate(payToAddress util.Address, extraNonc // consensus rules. Finally, it will update the target difficulty if needed // based on the new time for the test networks since their target difficulty can // change based upon time. -func (g *BlkTmplGenerator) UpdateBlockTime(msgBlock *wire.MsgBlock) error { +func (g *BlkTmplGenerator) UpdateBlockTime(msgBlock *domainmessage.MsgBlock) error { // The new timestamp is potentially adjusted to ensure it comes after // the median time of the last several blocks per the DAG consensus // rules. diff --git a/mining/test_utils.go b/mining/test_utils.go index 06d96ce39..bf30369e2 100644 --- a/mining/test_utils.go +++ b/mining/test_utils.go @@ -7,10 +7,10 @@ import ( "github.com/pkg/errors" "github.com/kaspanet/kaspad/blockdag" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/txscript" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) // fakeTxSource is a simple implementation of TxSource interface @@ -36,8 +36,8 @@ func (txs *fakeTxSource) HaveTransaction(txID *daghash.TxID) bool { } // PrepareBlockForTest generates a block with the proper merkle roots, coinbase transaction etc. This function is used for test purposes only -func PrepareBlockForTest(dag *blockdag.BlockDAG, parentHashes []*daghash.Hash, transactions []*wire.MsgTx, forceTransactions bool, -) (*wire.MsgBlock, error) { +func PrepareBlockForTest(dag *blockdag.BlockDAG, parentHashes []*daghash.Hash, transactions []*domainmessage.MsgTx, forceTransactions bool, +) (*domainmessage.MsgBlock, error) { newVirtual, err := blockdag.GetVirtualFromParentsForTest(dag, parentHashes) if err != nil { @@ -76,7 +76,7 @@ func PrepareBlockForTest(dag *blockdag.BlockDAG, parentHashes []*daghash.Hash, t return nil, err } - txsToAdd := make([]*wire.MsgTx, 0) + txsToAdd := make([]*domainmessage.MsgTx, 0) for _, tx := range transactions { found := false for _, blockTx := range template.Block.Transactions { diff --git a/netadapter/netadapter.go b/netadapter/netadapter.go index aa14d63bb..42e1ab3e0 100644 --- a/netadapter/netadapter.go +++ b/netadapter/netadapter.go @@ -7,11 +7,11 @@ import ( "sync/atomic" "github.com/kaspanet/kaspad/config" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/netadapter/id" routerpkg "github.com/kaspanet/kaspad/netadapter/router" "github.com/kaspanet/kaspad/netadapter/server" "github.com/kaspanet/kaspad/netadapter/server/grpcserver" - "github.com/kaspanet/kaspad/wire" "github.com/pkg/errors" ) @@ -139,7 +139,7 @@ func (na *NetAdapter) ID() *id.ID { // Broadcast sends the given `message` to every peer corresponding // to each NetConnection in the given netConnections -func (na *NetAdapter) Broadcast(netConnections []*NetConnection, message wire.Message) error { +func (na *NetAdapter) Broadcast(netConnections []*NetConnection, message domainmessage.Message) error { na.connectionsLock.RLock() defer na.connectionsLock.RUnlock() @@ -158,7 +158,7 @@ func (na *NetAdapter) Broadcast(netConnections []*NetConnection, message wire.Me // GetBestLocalAddress returns the most appropriate local address to use // for the given remote address. -func (na *NetAdapter) GetBestLocalAddress() (*wire.NetAddress, error) { +func (na *NetAdapter) GetBestLocalAddress() (*domainmessage.NetAddress, error) { //TODO(libp2p) Reimplement this, and check reachability to the other node if len(na.cfg.ExternalIPs) > 0 { host, portString, err := net.SplitHostPort(na.cfg.ExternalIPs[0]) @@ -181,7 +181,7 @@ func (na *NetAdapter) GetBestLocalAddress() (*wire.NetAddress, error) { return nil, errors.Errorf("Cannot resolve IP address for host '%s'", host) } } - return wire.NewNetAddressIPPort(ip, uint16(portInt), wire.SFNodeNetwork), nil + return domainmessage.NewNetAddressIPPort(ip, uint16(portInt), domainmessage.SFNodeNetwork), nil } listenAddress := na.cfg.Listeners[0] @@ -206,7 +206,7 @@ func (na *NetAdapter) GetBestLocalAddress() (*wire.NetAddress, error) { continue } - return wire.NewNetAddressIPPort(ip, uint16(portInt), wire.SFNodeNetwork), nil + return domainmessage.NewNetAddressIPPort(ip, uint16(portInt), domainmessage.SFNodeNetwork), nil } return nil, errors.New("no address was found") } diff --git a/netadapter/netconnection.go b/netadapter/netconnection.go index 347ea77bd..b47f7706e 100644 --- a/netadapter/netconnection.go +++ b/netadapter/netconnection.go @@ -3,8 +3,8 @@ package netadapter import ( "fmt" + "github.com/kaspanet/kaspad/domainmessage" routerpkg "github.com/kaspanet/kaspad/netadapter/router" - "github.com/kaspanet/kaspad/wire" "github.com/kaspanet/kaspad/netadapter/id" "github.com/kaspanet/kaspad/netadapter/server" @@ -72,8 +72,8 @@ func (c *NetConnection) IsOutbound() bool { } // NetAddress returns the NetAddress associated with this connection -func (c *NetConnection) NetAddress() *wire.NetAddress { - return wire.NewNetAddress(c.connection.Address(), 0) +func (c *NetConnection) NetAddress() *domainmessage.NetAddress { + return domainmessage.NewNetAddress(c.connection.Address(), 0) } // SetOnInvalidMessageHandler sets a handler function diff --git a/netadapter/router/route.go b/netadapter/router/route.go index 0515f103e..d0c41de5b 100644 --- a/netadapter/router/route.go +++ b/netadapter/router/route.go @@ -6,7 +6,7 @@ import ( "github.com/kaspanet/kaspad/protocol/protocolerrors" - "github.com/kaspanet/kaspad/wire" + "github.com/kaspanet/kaspad/domainmessage" "github.com/pkg/errors" ) @@ -30,7 +30,7 @@ type onCapacityReachedHandler func() // Route represents an incoming or outgoing Router route type Route struct { - channel chan wire.Message + channel chan domainmessage.Message // closed and closeLock are used to protect us from writing to a closed channel // reads use the channel's built-in mechanism to check if the channel is closed closed bool @@ -46,13 +46,13 @@ func NewRoute() *Route { func newRouteWithCapacity(capacity int) *Route { return &Route{ - channel: make(chan wire.Message, capacity), + channel: make(chan domainmessage.Message, capacity), closed: false, } } // Enqueue enqueues a message to the Route -func (r *Route) Enqueue(message wire.Message) error { +func (r *Route) Enqueue(message domainmessage.Message) error { r.closeLock.Lock() defer r.closeLock.Unlock() @@ -67,7 +67,7 @@ func (r *Route) Enqueue(message wire.Message) error { } // Dequeue dequeues a message from the Route -func (r *Route) Dequeue() (wire.Message, error) { +func (r *Route) Dequeue() (domainmessage.Message, error) { message, isOpen := <-r.channel if !isOpen { return nil, errors.WithStack(ErrRouteClosed) @@ -77,7 +77,7 @@ func (r *Route) Dequeue() (wire.Message, error) { // DequeueWithTimeout attempts to dequeue a message from the Route // and returns an error if the given timeout expires first. -func (r *Route) DequeueWithTimeout(timeout time.Duration) (wire.Message, error) { +func (r *Route) DequeueWithTimeout(timeout time.Duration) (domainmessage.Message, error) { select { case <-time.After(timeout): return nil, errors.Wrapf(ErrTimeout, "got timeout after %s", timeout) diff --git a/netadapter/router/router.go b/netadapter/router/router.go index 5b763cb46..09afc0aa2 100644 --- a/netadapter/router/router.go +++ b/netadapter/router/router.go @@ -3,11 +3,11 @@ package router import ( "sync" - "github.com/kaspanet/kaspad/wire" + "github.com/kaspanet/kaspad/domainmessage" "github.com/pkg/errors" ) -const outgoingRouteMaxMessages = wire.MaxInvPerMsg + DefaultMaxMessages +const outgoingRouteMaxMessages = domainmessage.MaxInvPerMsg + DefaultMaxMessages // OnRouteCapacityReachedHandler is a function that is to // be called when one of the routes reaches capacity. @@ -16,7 +16,7 @@ type OnRouteCapacityReachedHandler func() // Router routes messages by type to their respective // input channels type Router struct { - incomingRoutes map[wire.MessageCommand]*Route + incomingRoutes map[domainmessage.MessageCommand]*Route incomingRoutesLock sync.RWMutex outgoingRoute *Route @@ -27,7 +27,7 @@ type Router struct { // NewRouter creates a new empty router func NewRouter() *Router { router := Router{ - incomingRoutes: make(map[wire.MessageCommand]*Route), + incomingRoutes: make(map[domainmessage.MessageCommand]*Route), outgoingRoute: newRouteWithCapacity(outgoingRouteMaxMessages), } router.outgoingRoute.setOnCapacityReachedHandler(func() { @@ -44,7 +44,7 @@ func (r *Router) SetOnRouteCapacityReachedHandler(onRouteCapacityReachedHandler // AddIncomingRoute registers the messages of types `messageTypes` to // be routed to the given `route` -func (r *Router) AddIncomingRoute(messageTypes []wire.MessageCommand) (*Route, error) { +func (r *Router) AddIncomingRoute(messageTypes []domainmessage.MessageCommand) (*Route, error) { route := NewRoute() for _, messageType := range messageTypes { if r.doesIncomingRouteExist(messageType) { @@ -60,7 +60,7 @@ func (r *Router) AddIncomingRoute(messageTypes []wire.MessageCommand) (*Route, e // RemoveRoute unregisters the messages of types `messageTypes` from // the router -func (r *Router) RemoveRoute(messageTypes []wire.MessageCommand) error { +func (r *Router) RemoveRoute(messageTypes []domainmessage.MessageCommand) error { for _, messageType := range messageTypes { if !r.doesIncomingRouteExist(messageType) { return errors.Errorf("a route for '%s' does not exist", messageType) @@ -72,7 +72,7 @@ func (r *Router) RemoveRoute(messageTypes []wire.MessageCommand) error { // EnqueueIncomingMessage enqueues the given message to the // appropriate route -func (r *Router) EnqueueIncomingMessage(message wire.Message) error { +func (r *Router) EnqueueIncomingMessage(message domainmessage.Message) error { route, ok := r.incomingRoute(message.Command()) if !ok { return errors.Errorf("a route for '%s' does not exist", message.Command()) @@ -101,7 +101,7 @@ func (r *Router) Close() { r.outgoingRoute.Close() } -func (r *Router) incomingRoute(messageType wire.MessageCommand) (*Route, bool) { +func (r *Router) incomingRoute(messageType domainmessage.MessageCommand) (*Route, bool) { r.incomingRoutesLock.RLock() defer r.incomingRoutesLock.RUnlock() @@ -109,7 +109,7 @@ func (r *Router) incomingRoute(messageType wire.MessageCommand) (*Route, bool) { return route, ok } -func (r *Router) doesIncomingRouteExist(messageType wire.MessageCommand) bool { +func (r *Router) doesIncomingRouteExist(messageType domainmessage.MessageCommand) bool { r.incomingRoutesLock.RLock() defer r.incomingRoutesLock.RUnlock() @@ -117,14 +117,14 @@ func (r *Router) doesIncomingRouteExist(messageType wire.MessageCommand) bool { return ok } -func (r *Router) setIncomingRoute(messageType wire.MessageCommand, route *Route) { +func (r *Router) setIncomingRoute(messageType domainmessage.MessageCommand, route *Route) { r.incomingRoutesLock.Lock() defer r.incomingRoutesLock.Unlock() r.incomingRoutes[messageType] = route } -func (r *Router) deleteIncomingRoute(messageType wire.MessageCommand) { +func (r *Router) deleteIncomingRoute(messageType domainmessage.MessageCommand) { r.incomingRoutesLock.Lock() defer r.incomingRoutesLock.Unlock() diff --git a/netadapter/server/grpcserver/connection_loops.go b/netadapter/server/grpcserver/connection_loops.go index c2369fee9..23db318e6 100644 --- a/netadapter/server/grpcserver/connection_loops.go +++ b/netadapter/server/grpcserver/connection_loops.go @@ -46,7 +46,7 @@ func (c *gRPCConnection) sendLoop() error { return spew.Sdump(message) })) - messageProto, err := protowire.FromWireMessage(message) + messageProto, err := protowire.FromDomainMessage(message) if err != nil { return err } @@ -69,7 +69,7 @@ func (c *gRPCConnection) receiveLoop() error { } return err } - message, err := protoMessage.ToWireMessage() + message, err := protoMessage.ToDomainMessage() if err != nil { c.onInvalidMessageHandler(err) return err diff --git a/netadapter/server/grpcserver/protowire/common.go b/netadapter/server/grpcserver/protowire/common.go index b547dac9f..ec475af5a 100644 --- a/netadapter/server/grpcserver/protowire/common.go +++ b/netadapter/server/grpcserver/protowire/common.go @@ -3,10 +3,10 @@ package protowire import ( "math" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/mstime" "github.com/kaspanet/kaspad/util/subnetworkid" - "github.com/kaspanet/kaspad/wire" "github.com/pkg/errors" ) @@ -86,19 +86,19 @@ func wireSubnetworkIDToProto(id *subnetworkid.SubnetworkID) *SubnetworkID { } } -func (x *NetAddress) toWire() (*wire.NetAddress, error) { +func (x *NetAddress) toWire() (*domainmessage.NetAddress, error) { if x.Port > math.MaxUint16 { return nil, errors.Errorf("port number is larger than %d", math.MaxUint16) } - return &wire.NetAddress{ + return &domainmessage.NetAddress{ Timestamp: mstime.UnixMilliseconds(x.Timestamp), - Services: wire.ServiceFlag(x.Services), + Services: domainmessage.ServiceFlag(x.Services), IP: x.Ip, Port: uint16(x.Port), }, nil } -func wireNetAddressToProto(address *wire.NetAddress) *NetAddress { +func wireNetAddressToProto(address *domainmessage.NetAddress) *NetAddress { return &NetAddress{ Timestamp: address.Timestamp.UnixMilliseconds(), Services: uint64(address.Services), diff --git a/netadapter/server/grpcserver/protowire/message_addresses.go b/netadapter/server/grpcserver/protowire/message_addresses.go index a02a9fd2e..6984718a9 100644 --- a/netadapter/server/grpcserver/protowire/message_addresses.go +++ b/netadapter/server/grpcserver/protowire/message_addresses.go @@ -1,15 +1,15 @@ package protowire import ( - "github.com/kaspanet/kaspad/wire" + "github.com/kaspanet/kaspad/domainmessage" "github.com/pkg/errors" ) -func (x *KaspadMessage_Addresses) toWireMessage() (wire.Message, error) { +func (x *KaspadMessage_Addresses) toDomainMessage() (domainmessage.Message, error) { protoAddresses := x.Addresses - if len(x.Addresses.AddressList) > wire.MaxAddressesPerMsg { + if len(x.Addresses.AddressList) > domainmessage.MaxAddressesPerMsg { return nil, errors.Errorf("too many addresses for message "+ - "[count %d, max %d]", len(x.Addresses.AddressList), wire.MaxAddressesPerMsg) + "[count %d, max %d]", len(x.Addresses.AddressList), domainmessage.MaxAddressesPerMsg) } subnetworkID, err := protoAddresses.SubnetworkID.toWire() @@ -17,24 +17,24 @@ func (x *KaspadMessage_Addresses) toWireMessage() (wire.Message, error) { return nil, err } - addressList := make([]*wire.NetAddress, len(protoAddresses.AddressList)) + addressList := make([]*domainmessage.NetAddress, len(protoAddresses.AddressList)) for i, address := range protoAddresses.AddressList { addressList[i], err = address.toWire() if err != nil { return nil, err } } - return &wire.MsgAddresses{ + return &domainmessage.MsgAddresses{ IncludeAllSubnetworks: protoAddresses.IncludeAllSubnetworks, SubnetworkID: subnetworkID, AddrList: addressList, }, nil } -func (x *KaspadMessage_Addresses) fromWireMessage(msgAddresses *wire.MsgAddresses) error { - if len(msgAddresses.AddrList) > wire.MaxAddressesPerMsg { +func (x *KaspadMessage_Addresses) fromDomainMessage(msgAddresses *domainmessage.MsgAddresses) error { + if len(msgAddresses.AddrList) > domainmessage.MaxAddressesPerMsg { return errors.Errorf("too many addresses for message "+ - "[count %d, max %d]", len(msgAddresses.AddrList), wire.MaxAddressesPerMsg) + "[count %d, max %d]", len(msgAddresses.AddrList), domainmessage.MaxAddressesPerMsg) } addressList := make([]*NetAddress, len(msgAddresses.AddrList)) diff --git a/netadapter/server/grpcserver/protowire/message_block.go b/netadapter/server/grpcserver/protowire/message_block.go index ffe07e3f7..72ea3d8cf 100644 --- a/netadapter/server/grpcserver/protowire/message_block.go +++ b/netadapter/server/grpcserver/protowire/message_block.go @@ -1,24 +1,24 @@ package protowire import ( + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util/mstime" - "github.com/kaspanet/kaspad/wire" "github.com/pkg/errors" ) -func (x *KaspadMessage_Block) toWireMessage() (wire.Message, error) { - return x.Block.toWireMessage() +func (x *KaspadMessage_Block) toDomainMessage() (domainmessage.Message, error) { + return x.Block.toDomainMessage() } -func (x *KaspadMessage_Block) fromWireMessage(msgBlock *wire.MsgBlock) error { +func (x *KaspadMessage_Block) fromDomainMessage(msgBlock *domainmessage.MsgBlock) error { x.Block = new(BlockMessage) - return x.Block.fromWireMessage(msgBlock) + return x.Block.fromDomainMessage(msgBlock) } -func (x *BlockMessage) toWireMessage() (wire.Message, error) { - if len(x.Transactions) > wire.MaxTxPerBlock { +func (x *BlockMessage) toDomainMessage() (domainmessage.Message, error) { + if len(x.Transactions) > domainmessage.MaxTxPerBlock { return nil, errors.Errorf("too many transactions to fit into a block "+ - "[count %d, max %d]", len(x.Transactions), wire.MaxTxPerBlock) + "[count %d, max %d]", len(x.Transactions), domainmessage.MaxTxPerBlock) } protoBlockHeader := x.Header @@ -46,7 +46,7 @@ func (x *BlockMessage) toWireMessage() (wire.Message, error) { return nil, err } - header := wire.BlockHeader{ + header := domainmessage.BlockHeader{ Version: protoBlockHeader.Version, ParentHashes: parentHashes, HashMerkleRoot: hashMerkleRoot, @@ -57,25 +57,25 @@ func (x *BlockMessage) toWireMessage() (wire.Message, error) { Nonce: protoBlockHeader.Nonce, } - transactions := make([]*wire.MsgTx, len(x.Transactions)) + transactions := make([]*domainmessage.MsgTx, len(x.Transactions)) for i, protoTx := range x.Transactions { - msgTx, err := protoTx.toWireMessage() + msgTx, err := protoTx.toDomainMessage() if err != nil { return nil, err } - transactions[i] = msgTx.(*wire.MsgTx) + transactions[i] = msgTx.(*domainmessage.MsgTx) } - return &wire.MsgBlock{ + return &domainmessage.MsgBlock{ Header: header, Transactions: transactions, }, nil } -func (x *BlockMessage) fromWireMessage(msgBlock *wire.MsgBlock) error { - if len(msgBlock.Transactions) > wire.MaxTxPerBlock { +func (x *BlockMessage) fromDomainMessage(msgBlock *domainmessage.MsgBlock) error { + if len(msgBlock.Transactions) > domainmessage.MaxTxPerBlock { return errors.Errorf("too many transactions to fit into a block "+ - "[count %d, max %d]", len(msgBlock.Transactions), wire.MaxTxPerBlock) + "[count %d, max %d]", len(msgBlock.Transactions), domainmessage.MaxTxPerBlock) } header := msgBlock.Header @@ -92,7 +92,7 @@ func (x *BlockMessage) fromWireMessage(msgBlock *wire.MsgBlock) error { protoTransactions := make([]*TransactionMessage, len(msgBlock.Transactions)) for i, tx := range msgBlock.Transactions { protoTx := new(TransactionMessage) - protoTx.fromWireMessage(tx) + protoTx.fromDomainMessage(tx) protoTransactions[i] = protoTx } *x = BlockMessage{ diff --git a/netadapter/server/grpcserver/protowire/message_block_locator.go b/netadapter/server/grpcserver/protowire/message_block_locator.go index a27831b59..09fc1ab4c 100644 --- a/netadapter/server/grpcserver/protowire/message_block_locator.go +++ b/netadapter/server/grpcserver/protowire/message_block_locator.go @@ -1,26 +1,26 @@ package protowire import ( - "github.com/kaspanet/kaspad/wire" + "github.com/kaspanet/kaspad/domainmessage" "github.com/pkg/errors" ) -func (x *KaspadMessage_BlockLocator) toWireMessage() (wire.Message, error) { - if len(x.BlockLocator.Hashes) > wire.MaxBlockLocatorsPerMsg { +func (x *KaspadMessage_BlockLocator) toDomainMessage() (domainmessage.Message, error) { + if len(x.BlockLocator.Hashes) > domainmessage.MaxBlockLocatorsPerMsg { return nil, errors.Errorf("too many block locator hashes for message "+ - "[count %d, max %d]", len(x.BlockLocator.Hashes), wire.MaxBlockLocatorsPerMsg) + "[count %d, max %d]", len(x.BlockLocator.Hashes), domainmessage.MaxBlockLocatorsPerMsg) } hashes, err := protoHashesToWire(x.BlockLocator.Hashes) if err != nil { return nil, err } - return &wire.MsgBlockLocator{BlockLocatorHashes: hashes}, nil + return &domainmessage.MsgBlockLocator{BlockLocatorHashes: hashes}, nil } -func (x *KaspadMessage_BlockLocator) fromWireMessage(msgBlockLocator *wire.MsgBlockLocator) error { - if len(msgBlockLocator.BlockLocatorHashes) > wire.MaxBlockLocatorsPerMsg { +func (x *KaspadMessage_BlockLocator) fromDomainMessage(msgBlockLocator *domainmessage.MsgBlockLocator) error { + if len(msgBlockLocator.BlockLocatorHashes) > domainmessage.MaxBlockLocatorsPerMsg { return errors.Errorf("too many block locator hashes for message "+ - "[count %d, max %d]", len(msgBlockLocator.BlockLocatorHashes), wire.MaxBlockLocatorsPerMsg) + "[count %d, max %d]", len(msgBlockLocator.BlockLocatorHashes), domainmessage.MaxBlockLocatorsPerMsg) } x.BlockLocator = &BlockLocatorMessage{ Hashes: wireHashesToProto(msgBlockLocator.BlockLocatorHashes), diff --git a/netadapter/server/grpcserver/protowire/message_done_ibd_blocks.go b/netadapter/server/grpcserver/protowire/message_done_ibd_blocks.go index ad88c9a03..c7c91d5d9 100644 --- a/netadapter/server/grpcserver/protowire/message_done_ibd_blocks.go +++ b/netadapter/server/grpcserver/protowire/message_done_ibd_blocks.go @@ -1,11 +1,11 @@ package protowire -import "github.com/kaspanet/kaspad/wire" +import "github.com/kaspanet/kaspad/domainmessage" -func (x *KaspadMessage_DoneIBDBlocks) toWireMessage() (wire.Message, error) { - return &wire.MsgDoneIBDBlocks{}, nil +func (x *KaspadMessage_DoneIBDBlocks) toDomainMessage() (domainmessage.Message, error) { + return &domainmessage.MsgDoneIBDBlocks{}, nil } -func (x *KaspadMessage_DoneIBDBlocks) fromWireMessage(_ *wire.MsgDoneIBDBlocks) error { +func (x *KaspadMessage_DoneIBDBlocks) fromDomainMessage(_ *domainmessage.MsgDoneIBDBlocks) error { return nil } diff --git a/netadapter/server/grpcserver/protowire/message_ibd_block.go b/netadapter/server/grpcserver/protowire/message_ibd_block.go index bd472a38f..46516dce2 100644 --- a/netadapter/server/grpcserver/protowire/message_ibd_block.go +++ b/netadapter/server/grpcserver/protowire/message_ibd_block.go @@ -1,16 +1,16 @@ package protowire -import "github.com/kaspanet/kaspad/wire" +import "github.com/kaspanet/kaspad/domainmessage" -func (x *KaspadMessage_IbdBlock) toWireMessage() (wire.Message, error) { - msgBlock, err := x.IbdBlock.toWireMessage() +func (x *KaspadMessage_IbdBlock) toDomainMessage() (domainmessage.Message, error) { + msgBlock, err := x.IbdBlock.toDomainMessage() if err != nil { return nil, err } - return &wire.MsgIBDBlock{MsgBlock: msgBlock.(*wire.MsgBlock)}, nil + return &domainmessage.MsgIBDBlock{MsgBlock: msgBlock.(*domainmessage.MsgBlock)}, nil } -func (x *KaspadMessage_IbdBlock) fromWireMessage(msgIBDBlock *wire.MsgIBDBlock) error { +func (x *KaspadMessage_IbdBlock) fromDomainMessage(msgIBDBlock *domainmessage.MsgIBDBlock) error { x.IbdBlock = new(BlockMessage) - return x.IbdBlock.fromWireMessage(msgIBDBlock.MsgBlock) + return x.IbdBlock.fromDomainMessage(msgIBDBlock.MsgBlock) } diff --git a/netadapter/server/grpcserver/protowire/message_inv_relay_block.go b/netadapter/server/grpcserver/protowire/message_inv_relay_block.go index 1b071255e..fd366a01c 100644 --- a/netadapter/server/grpcserver/protowire/message_inv_relay_block.go +++ b/netadapter/server/grpcserver/protowire/message_inv_relay_block.go @@ -1,17 +1,17 @@ package protowire -import "github.com/kaspanet/kaspad/wire" +import "github.com/kaspanet/kaspad/domainmessage" -func (x *KaspadMessage_InvRelayBlock) toWireMessage() (wire.Message, error) { +func (x *KaspadMessage_InvRelayBlock) toDomainMessage() (domainmessage.Message, error) { hash, err := x.InvRelayBlock.Hash.toWire() if err != nil { return nil, err } - return &wire.MsgInvRelayBlock{Hash: hash}, nil + return &domainmessage.MsgInvRelayBlock{Hash: hash}, nil } -func (x *KaspadMessage_InvRelayBlock) fromWireMessage(msgInvRelayBlock *wire.MsgInvRelayBlock) error { +func (x *KaspadMessage_InvRelayBlock) fromDomainMessage(msgInvRelayBlock *domainmessage.MsgInvRelayBlock) error { x.InvRelayBlock = &InvRelayBlockMessage{ Hash: wireHashToProto(msgInvRelayBlock.Hash), } diff --git a/netadapter/server/grpcserver/protowire/message_inv_transactions.go b/netadapter/server/grpcserver/protowire/message_inv_transactions.go index ccf702d30..9640f9303 100644 --- a/netadapter/server/grpcserver/protowire/message_inv_transactions.go +++ b/netadapter/server/grpcserver/protowire/message_inv_transactions.go @@ -1,27 +1,27 @@ package protowire import ( - "github.com/kaspanet/kaspad/wire" + "github.com/kaspanet/kaspad/domainmessage" "github.com/pkg/errors" ) -func (x *KaspadMessage_InvTransactions) toWireMessage() (wire.Message, error) { - if len(x.InvTransactions.Ids) > wire.MaxInvPerTxInvMsg { +func (x *KaspadMessage_InvTransactions) toDomainMessage() (domainmessage.Message, error) { + if len(x.InvTransactions.Ids) > domainmessage.MaxInvPerTxInvMsg { return nil, errors.Errorf("too many hashes for message "+ - "[count %d, max %d]", len(x.InvTransactions.Ids), wire.MaxInvPerTxInvMsg) + "[count %d, max %d]", len(x.InvTransactions.Ids), domainmessage.MaxInvPerTxInvMsg) } ids, err := protoTransactionIDsToWire(x.InvTransactions.Ids) if err != nil { return nil, err } - return &wire.MsgInvTransaction{TxIDs: ids}, nil + return &domainmessage.MsgInvTransaction{TxIDs: ids}, nil } -func (x *KaspadMessage_InvTransactions) fromWireMessage(msgInvTransaction *wire.MsgInvTransaction) error { - if len(msgInvTransaction.TxIDs) > wire.MaxInvPerTxInvMsg { +func (x *KaspadMessage_InvTransactions) fromDomainMessage(msgInvTransaction *domainmessage.MsgInvTransaction) error { + if len(msgInvTransaction.TxIDs) > domainmessage.MaxInvPerTxInvMsg { return errors.Errorf("too many hashes for message "+ - "[count %d, max %d]", len(msgInvTransaction.TxIDs), wire.MaxInvPerTxInvMsg) + "[count %d, max %d]", len(msgInvTransaction.TxIDs), domainmessage.MaxInvPerTxInvMsg) } x.InvTransactions = &InvTransactionsMessage{ diff --git a/netadapter/server/grpcserver/protowire/message_ping.go b/netadapter/server/grpcserver/protowire/message_ping.go index 0a95f08e5..682af3283 100644 --- a/netadapter/server/grpcserver/protowire/message_ping.go +++ b/netadapter/server/grpcserver/protowire/message_ping.go @@ -1,16 +1,16 @@ package protowire import ( - "github.com/kaspanet/kaspad/wire" + "github.com/kaspanet/kaspad/domainmessage" ) -func (x *KaspadMessage_Ping) toWireMessage() (wire.Message, error) { - return &wire.MsgPing{ +func (x *KaspadMessage_Ping) toDomainMessage() (domainmessage.Message, error) { + return &domainmessage.MsgPing{ Nonce: x.Ping.Nonce, }, nil } -func (x *KaspadMessage_Ping) fromWireMessage(msgPing *wire.MsgPing) error { +func (x *KaspadMessage_Ping) fromDomainMessage(msgPing *domainmessage.MsgPing) error { x.Ping = &PingMessage{ Nonce: msgPing.Nonce, } diff --git a/netadapter/server/grpcserver/protowire/message_pong.go b/netadapter/server/grpcserver/protowire/message_pong.go index f84d46f26..cc8dc09dd 100644 --- a/netadapter/server/grpcserver/protowire/message_pong.go +++ b/netadapter/server/grpcserver/protowire/message_pong.go @@ -1,16 +1,16 @@ package protowire import ( - "github.com/kaspanet/kaspad/wire" + "github.com/kaspanet/kaspad/domainmessage" ) -func (x *KaspadMessage_Pong) toWireMessage() (wire.Message, error) { - return &wire.MsgPong{ +func (x *KaspadMessage_Pong) toDomainMessage() (domainmessage.Message, error) { + return &domainmessage.MsgPong{ Nonce: x.Pong.Nonce, }, nil } -func (x *KaspadMessage_Pong) fromWireMessage(msgPong *wire.MsgPong) error { +func (x *KaspadMessage_Pong) fromDomainMessage(msgPong *domainmessage.MsgPong) error { x.Pong = &PongMessage{ Nonce: msgPong.Nonce, } diff --git a/netadapter/server/grpcserver/protowire/message_request_addresses.go b/netadapter/server/grpcserver/protowire/message_request_addresses.go index 16ad3b8ac..99ee88086 100644 --- a/netadapter/server/grpcserver/protowire/message_request_addresses.go +++ b/netadapter/server/grpcserver/protowire/message_request_addresses.go @@ -1,23 +1,23 @@ package protowire import ( - "github.com/kaspanet/kaspad/wire" + "github.com/kaspanet/kaspad/domainmessage" ) -func (x *KaspadMessage_RequestAddresses) toWireMessage() (wire.Message, error) { +func (x *KaspadMessage_RequestAddresses) toDomainMessage() (domainmessage.Message, error) { protoGetAddresses := x.RequestAddresses subnetworkID, err := protoGetAddresses.SubnetworkID.toWire() if err != nil { return nil, err } - return &wire.MsgRequestAddresses{ + return &domainmessage.MsgRequestAddresses{ IncludeAllSubnetworks: protoGetAddresses.IncludeAllSubnetworks, SubnetworkID: subnetworkID, }, nil } -func (x *KaspadMessage_RequestAddresses) fromWireMessage(msgGetAddresses *wire.MsgRequestAddresses) error { +func (x *KaspadMessage_RequestAddresses) fromDomainMessage(msgGetAddresses *domainmessage.MsgRequestAddresses) error { x.RequestAddresses = &RequestAddressesMessage{ IncludeAllSubnetworks: msgGetAddresses.IncludeAllSubnetworks, SubnetworkID: wireSubnetworkIDToProto(msgGetAddresses.SubnetworkID), diff --git a/netadapter/server/grpcserver/protowire/message_request_block_locator.go b/netadapter/server/grpcserver/protowire/message_request_block_locator.go index 2347f7636..be7785630 100644 --- a/netadapter/server/grpcserver/protowire/message_request_block_locator.go +++ b/netadapter/server/grpcserver/protowire/message_request_block_locator.go @@ -1,8 +1,8 @@ package protowire -import "github.com/kaspanet/kaspad/wire" +import "github.com/kaspanet/kaspad/domainmessage" -func (x *KaspadMessage_RequestBlockLocator) toWireMessage() (wire.Message, error) { +func (x *KaspadMessage_RequestBlockLocator) toDomainMessage() (domainmessage.Message, error) { lowHash, err := x.RequestBlockLocator.LowHash.toWire() if err != nil { return nil, err @@ -13,13 +13,13 @@ func (x *KaspadMessage_RequestBlockLocator) toWireMessage() (wire.Message, error return nil, err } - return &wire.MsgRequestBlockLocator{ + return &domainmessage.MsgRequestBlockLocator{ LowHash: lowHash, HighHash: highHash, }, nil } -func (x *KaspadMessage_RequestBlockLocator) fromWireMessage(msgGetBlockLocator *wire.MsgRequestBlockLocator) error { +func (x *KaspadMessage_RequestBlockLocator) fromDomainMessage(msgGetBlockLocator *domainmessage.MsgRequestBlockLocator) error { x.RequestBlockLocator = &RequestBlockLocatorMessage{ LowHash: wireHashToProto(msgGetBlockLocator.LowHash), HighHash: wireHashToProto(msgGetBlockLocator.HighHash), diff --git a/netadapter/server/grpcserver/protowire/message_request_ibd_blocks.go b/netadapter/server/grpcserver/protowire/message_request_ibd_blocks.go index 2b0a0775b..74c1ab4f1 100644 --- a/netadapter/server/grpcserver/protowire/message_request_ibd_blocks.go +++ b/netadapter/server/grpcserver/protowire/message_request_ibd_blocks.go @@ -1,8 +1,8 @@ package protowire -import "github.com/kaspanet/kaspad/wire" +import "github.com/kaspanet/kaspad/domainmessage" -func (x *KaspadMessage_RequestIBDBlocks) toWireMessage() (wire.Message, error) { +func (x *KaspadMessage_RequestIBDBlocks) toDomainMessage() (domainmessage.Message, error) { lowHash, err := x.RequestIBDBlocks.LowHash.toWire() if err != nil { return nil, err @@ -13,13 +13,13 @@ func (x *KaspadMessage_RequestIBDBlocks) toWireMessage() (wire.Message, error) { return nil, err } - return &wire.MsgRequestIBDBlocks{ + return &domainmessage.MsgRequestIBDBlocks{ LowHash: lowHash, HighHash: highHash, }, nil } -func (x *KaspadMessage_RequestIBDBlocks) fromWireMessage(msgGetBlocks *wire.MsgRequestIBDBlocks) error { +func (x *KaspadMessage_RequestIBDBlocks) fromDomainMessage(msgGetBlocks *domainmessage.MsgRequestIBDBlocks) error { x.RequestIBDBlocks = &RequestIBDBlocksMessage{ LowHash: wireHashToProto(msgGetBlocks.LowHash), HighHash: wireHashToProto(msgGetBlocks.HighHash), diff --git a/netadapter/server/grpcserver/protowire/message_request_next_ibd_blocks.go b/netadapter/server/grpcserver/protowire/message_request_next_ibd_blocks.go index ee98fa49b..f1da7c1ae 100644 --- a/netadapter/server/grpcserver/protowire/message_request_next_ibd_blocks.go +++ b/netadapter/server/grpcserver/protowire/message_request_next_ibd_blocks.go @@ -1,11 +1,11 @@ package protowire -import "github.com/kaspanet/kaspad/wire" +import "github.com/kaspanet/kaspad/domainmessage" -func (x *KaspadMessage_RequestNextIBDBlocks) toWireMessage() (wire.Message, error) { - return &wire.MsgRequestNextIBDBlocks{}, nil +func (x *KaspadMessage_RequestNextIBDBlocks) toDomainMessage() (domainmessage.Message, error) { + return &domainmessage.MsgRequestNextIBDBlocks{}, nil } -func (x *KaspadMessage_RequestNextIBDBlocks) fromWireMessage(_ *wire.MsgRequestNextIBDBlocks) error { +func (x *KaspadMessage_RequestNextIBDBlocks) fromDomainMessage(_ *domainmessage.MsgRequestNextIBDBlocks) error { return nil } diff --git a/netadapter/server/grpcserver/protowire/message_request_relay_blocks.go b/netadapter/server/grpcserver/protowire/message_request_relay_blocks.go index 24c1bf0ce..9027e206f 100644 --- a/netadapter/server/grpcserver/protowire/message_request_relay_blocks.go +++ b/netadapter/server/grpcserver/protowire/message_request_relay_blocks.go @@ -1,26 +1,26 @@ package protowire import ( - "github.com/kaspanet/kaspad/wire" + "github.com/kaspanet/kaspad/domainmessage" "github.com/pkg/errors" ) -func (x *KaspadMessage_RequestRelayBlocks) toWireMessage() (wire.Message, error) { - if len(x.RequestRelayBlocks.Hashes) > wire.MsgRequestRelayBlocksHashes { +func (x *KaspadMessage_RequestRelayBlocks) toDomainMessage() (domainmessage.Message, error) { + if len(x.RequestRelayBlocks.Hashes) > domainmessage.MsgRequestRelayBlocksHashes { return nil, errors.Errorf("too many hashes for message "+ - "[count %d, max %d]", len(x.RequestRelayBlocks.Hashes), wire.MsgRequestRelayBlocksHashes) + "[count %d, max %d]", len(x.RequestRelayBlocks.Hashes), domainmessage.MsgRequestRelayBlocksHashes) } hashes, err := protoHashesToWire(x.RequestRelayBlocks.Hashes) if err != nil { return nil, err } - return &wire.MsgRequestRelayBlocks{Hashes: hashes}, nil + return &domainmessage.MsgRequestRelayBlocks{Hashes: hashes}, nil } -func (x *KaspadMessage_RequestRelayBlocks) fromWireMessage(msgGetRelayBlocks *wire.MsgRequestRelayBlocks) error { - if len(msgGetRelayBlocks.Hashes) > wire.MsgRequestRelayBlocksHashes { +func (x *KaspadMessage_RequestRelayBlocks) fromDomainMessage(msgGetRelayBlocks *domainmessage.MsgRequestRelayBlocks) error { + if len(msgGetRelayBlocks.Hashes) > domainmessage.MsgRequestRelayBlocksHashes { return errors.Errorf("too many hashes for message "+ - "[count %d, max %d]", len(msgGetRelayBlocks.Hashes), wire.MsgRequestRelayBlocksHashes) + "[count %d, max %d]", len(msgGetRelayBlocks.Hashes), domainmessage.MsgRequestRelayBlocksHashes) } x.RequestRelayBlocks = &RequestRelayBlocksMessage{ diff --git a/netadapter/server/grpcserver/protowire/message_request_selected_tip.go b/netadapter/server/grpcserver/protowire/message_request_selected_tip.go index 6a97797c1..f799296f2 100644 --- a/netadapter/server/grpcserver/protowire/message_request_selected_tip.go +++ b/netadapter/server/grpcserver/protowire/message_request_selected_tip.go @@ -1,11 +1,11 @@ package protowire -import "github.com/kaspanet/kaspad/wire" +import "github.com/kaspanet/kaspad/domainmessage" -func (x *KaspadMessage_RequestSelectedTip) toWireMessage() (wire.Message, error) { - return &wire.MsgRequestSelectedTip{}, nil +func (x *KaspadMessage_RequestSelectedTip) toDomainMessage() (domainmessage.Message, error) { + return &domainmessage.MsgRequestSelectedTip{}, nil } -func (x *KaspadMessage_RequestSelectedTip) fromWireMessage(_ *wire.MsgRequestSelectedTip) error { +func (x *KaspadMessage_RequestSelectedTip) fromDomainMessage(_ *domainmessage.MsgRequestSelectedTip) error { return nil } diff --git a/netadapter/server/grpcserver/protowire/message_request_transactions.go b/netadapter/server/grpcserver/protowire/message_request_transactions.go index 927353b1a..4f83cfc82 100644 --- a/netadapter/server/grpcserver/protowire/message_request_transactions.go +++ b/netadapter/server/grpcserver/protowire/message_request_transactions.go @@ -1,27 +1,27 @@ package protowire import ( - "github.com/kaspanet/kaspad/wire" + "github.com/kaspanet/kaspad/domainmessage" "github.com/pkg/errors" ) -func (x *KaspadMessage_RequestTransactions) toWireMessage() (wire.Message, error) { - if len(x.RequestTransactions.Ids) > wire.MaxInvPerRequestTransactionsMsg { +func (x *KaspadMessage_RequestTransactions) toDomainMessage() (domainmessage.Message, error) { + if len(x.RequestTransactions.Ids) > domainmessage.MaxInvPerRequestTransactionsMsg { return nil, errors.Errorf("too many hashes for message "+ - "[count %d, max %d]", len(x.RequestTransactions.Ids), wire.MaxInvPerRequestTransactionsMsg) + "[count %d, max %d]", len(x.RequestTransactions.Ids), domainmessage.MaxInvPerRequestTransactionsMsg) } ids, err := protoTransactionIDsToWire(x.RequestTransactions.Ids) if err != nil { return nil, err } - return &wire.MsgRequestTransactions{IDs: ids}, nil + return &domainmessage.MsgRequestTransactions{IDs: ids}, nil } -func (x *KaspadMessage_RequestTransactions) fromWireMessage(msgGetTransactions *wire.MsgRequestTransactions) error { - if len(msgGetTransactions.IDs) > wire.MaxInvPerRequestTransactionsMsg { +func (x *KaspadMessage_RequestTransactions) fromDomainMessage(msgGetTransactions *domainmessage.MsgRequestTransactions) error { + if len(msgGetTransactions.IDs) > domainmessage.MaxInvPerRequestTransactionsMsg { return errors.Errorf("too many hashes for message "+ - "[count %d, max %d]", len(x.RequestTransactions.Ids), wire.MaxInvPerRequestTransactionsMsg) + "[count %d, max %d]", len(x.RequestTransactions.Ids), domainmessage.MaxInvPerRequestTransactionsMsg) } x.RequestTransactions = &RequestTransactionsMessage{ diff --git a/netadapter/server/grpcserver/protowire/message_selected_tip.go b/netadapter/server/grpcserver/protowire/message_selected_tip.go index 8774db81a..f03f93e98 100644 --- a/netadapter/server/grpcserver/protowire/message_selected_tip.go +++ b/netadapter/server/grpcserver/protowire/message_selected_tip.go @@ -1,17 +1,17 @@ package protowire -import "github.com/kaspanet/kaspad/wire" +import "github.com/kaspanet/kaspad/domainmessage" -func (x *KaspadMessage_SelectedTip) toWireMessage() (wire.Message, error) { +func (x *KaspadMessage_SelectedTip) toDomainMessage() (domainmessage.Message, error) { hash, err := x.SelectedTip.SelectedTipHash.toWire() if err != nil { return nil, err } - return &wire.MsgSelectedTip{SelectedTipHash: hash}, nil + return &domainmessage.MsgSelectedTip{SelectedTipHash: hash}, nil } -func (x *KaspadMessage_SelectedTip) fromWireMessage(msgSelectedTip *wire.MsgSelectedTip) error { +func (x *KaspadMessage_SelectedTip) fromDomainMessage(msgSelectedTip *domainmessage.MsgSelectedTip) error { x.SelectedTip = &SelectedTipMessage{ SelectedTipHash: wireHashToProto(msgSelectedTip.SelectedTipHash), } diff --git a/netadapter/server/grpcserver/protowire/message_transaction.go b/netadapter/server/grpcserver/protowire/message_transaction.go index 9d18b5a35..9794f43bc 100644 --- a/netadapter/server/grpcserver/protowire/message_transaction.go +++ b/netadapter/server/grpcserver/protowire/message_transaction.go @@ -1,36 +1,36 @@ package protowire import ( + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" "github.com/pkg/errors" ) -func (x *KaspadMessage_Transaction) toWireMessage() (wire.Message, error) { - return x.Transaction.toWireMessage() +func (x *KaspadMessage_Transaction) toDomainMessage() (domainmessage.Message, error) { + return x.Transaction.toDomainMessage() } -func (x *KaspadMessage_Transaction) fromWireMessage(msgTx *wire.MsgTx) error { +func (x *KaspadMessage_Transaction) fromDomainMessage(msgTx *domainmessage.MsgTx) error { x.Transaction = new(TransactionMessage) - x.Transaction.fromWireMessage(msgTx) + x.Transaction.fromDomainMessage(msgTx) return nil } -func (x *TransactionMessage) toWireMessage() (wire.Message, error) { - inputs := make([]*wire.TxIn, len(x.Inputs)) +func (x *TransactionMessage) toDomainMessage() (domainmessage.Message, error) { + inputs := make([]*domainmessage.TxIn, len(x.Inputs)) for i, protoInput := range x.Inputs { prevTxID, err := protoInput.PreviousOutpoint.TransactionID.toWire() if err != nil { return nil, err } - outpoint := wire.NewOutpoint(prevTxID, protoInput.PreviousOutpoint.Index) - inputs[i] = wire.NewTxIn(outpoint, protoInput.SignatureScript) + outpoint := domainmessage.NewOutpoint(prevTxID, protoInput.PreviousOutpoint.Index) + inputs[i] = domainmessage.NewTxIn(outpoint, protoInput.SignatureScript) } - outputs := make([]*wire.TxOut, len(x.Outputs)) + outputs := make([]*domainmessage.TxOut, len(x.Outputs)) for i, protoOutput := range x.Outputs { - outputs[i] = &wire.TxOut{ + outputs[i] = &domainmessage.TxOut{ Value: protoOutput.Value, ScriptPubKey: protoOutput.ScriptPubKey, } @@ -53,7 +53,7 @@ func (x *TransactionMessage) toWireMessage() (wire.Message, error) { } } - return &wire.MsgTx{ + return &domainmessage.MsgTx{ Version: x.Version, TxIn: inputs, TxOut: outputs, @@ -65,7 +65,7 @@ func (x *TransactionMessage) toWireMessage() (wire.Message, error) { }, nil } -func (x *TransactionMessage) fromWireMessage(msgTx *wire.MsgTx) { +func (x *TransactionMessage) fromDomainMessage(msgTx *domainmessage.MsgTx) { protoInputs := make([]*TransactionInput, len(msgTx.TxIn)) for i, input := range msgTx.TxIn { protoInputs[i] = &TransactionInput{ diff --git a/netadapter/server/grpcserver/protowire/message_transaction_not_found.go b/netadapter/server/grpcserver/protowire/message_transaction_not_found.go index 86ab4c2df..03608f745 100644 --- a/netadapter/server/grpcserver/protowire/message_transaction_not_found.go +++ b/netadapter/server/grpcserver/protowire/message_transaction_not_found.go @@ -1,18 +1,18 @@ package protowire import ( - "github.com/kaspanet/kaspad/wire" + "github.com/kaspanet/kaspad/domainmessage" ) -func (x *KaspadMessage_TransactionNotFound) toWireMessage() (wire.Message, error) { +func (x *KaspadMessage_TransactionNotFound) toDomainMessage() (domainmessage.Message, error) { id, err := x.TransactionNotFound.Id.toWire() if err != nil { return nil, err } - return wire.NewMsgTransactionNotFound(id), nil + return domainmessage.NewMsgTransactionNotFound(id), nil } -func (x *KaspadMessage_TransactionNotFound) fromWireMessage(msgTransactionsNotFound *wire.MsgTransactionNotFound) error { +func (x *KaspadMessage_TransactionNotFound) fromDomainMessage(msgTransactionsNotFound *domainmessage.MsgTransactionNotFound) error { x.TransactionNotFound = &TransactionNotFoundMessage{ Id: wireTransactionIDToProto(msgTransactionsNotFound.ID), } diff --git a/netadapter/server/grpcserver/protowire/message_verack.go b/netadapter/server/grpcserver/protowire/message_verack.go index d2b4b71b5..42fb22049 100644 --- a/netadapter/server/grpcserver/protowire/message_verack.go +++ b/netadapter/server/grpcserver/protowire/message_verack.go @@ -1,11 +1,11 @@ package protowire -import "github.com/kaspanet/kaspad/wire" +import "github.com/kaspanet/kaspad/domainmessage" -func (x *KaspadMessage_Verack) toWireMessage() (wire.Message, error) { - return &wire.MsgVerAck{}, nil +func (x *KaspadMessage_Verack) toDomainMessage() (domainmessage.Message, error) { + return &domainmessage.MsgVerAck{}, nil } -func (x *KaspadMessage_Verack) fromWireMessage(_ *wire.MsgVerAck) error { +func (x *KaspadMessage_Verack) fromDomainMessage(_ *domainmessage.MsgVerAck) error { return nil } diff --git a/netadapter/server/grpcserver/protowire/message_version.go b/netadapter/server/grpcserver/protowire/message_version.go index 5f4ab3a65..daa6639f8 100644 --- a/netadapter/server/grpcserver/protowire/message_version.go +++ b/netadapter/server/grpcserver/protowire/message_version.go @@ -1,14 +1,14 @@ package protowire import ( + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/netadapter/id" "github.com/kaspanet/kaspad/util/mstime" - "github.com/kaspanet/kaspad/wire" ) -func (x *KaspadMessage_Version) toWireMessage() (wire.Message, error) { +func (x *KaspadMessage_Version) toDomainMessage() (domainmessage.Message, error) { // Address is optional for non-listening nodes - var address *wire.NetAddress + var address *domainmessage.NetAddress if x.Version.Address != nil { var err error address, err = x.Version.Address.toWire() @@ -27,14 +27,14 @@ func (x *KaspadMessage_Version) toWireMessage() (wire.Message, error) { return nil, err } - err = wire.ValidateUserAgent(x.Version.UserAgent) + err = domainmessage.ValidateUserAgent(x.Version.UserAgent) if err != nil { return nil, err } - return &wire.MsgVersion{ + return &domainmessage.MsgVersion{ ProtocolVersion: x.Version.ProtocolVersion, - Services: wire.ServiceFlag(x.Version.Services), + Services: domainmessage.ServiceFlag(x.Version.Services), Timestamp: mstime.UnixMilliseconds(x.Version.Timestamp), Address: address, ID: id.FromBytes(x.Version.Id), @@ -45,8 +45,8 @@ func (x *KaspadMessage_Version) toWireMessage() (wire.Message, error) { }, nil } -func (x *KaspadMessage_Version) fromWireMessage(msgVersion *wire.MsgVersion) error { - err := wire.ValidateUserAgent(msgVersion.UserAgent) +func (x *KaspadMessage_Version) fromDomainMessage(msgVersion *domainmessage.MsgVersion) error { + err := domainmessage.ValidateUserAgent(msgVersion.UserAgent) if err != nil { return err } diff --git a/netadapter/server/grpcserver/protowire/wire.go b/netadapter/server/grpcserver/protowire/wire.go index 0d34dc572..8ce15e3fc 100644 --- a/netadapter/server/grpcserver/protowire/wire.go +++ b/netadapter/server/grpcserver/protowire/wire.go @@ -1,21 +1,21 @@ package protowire import ( - "github.com/kaspanet/kaspad/wire" + "github.com/kaspanet/kaspad/domainmessage" "github.com/pkg/errors" ) type converter interface { - toWireMessage() (wire.Message, error) + toDomainMessage() (domainmessage.Message, error) } -// ToWireMessage converts a KaspadMessage to its wire.Message representation -func (x *KaspadMessage) ToWireMessage() (wire.Message, error) { - return x.Payload.(converter).toWireMessage() +// ToDomainMessage converts a KaspadMessage to its domainmessage.Message representation +func (x *KaspadMessage) ToDomainMessage() (domainmessage.Message, error) { + return x.Payload.(converter).toDomainMessage() } -// FromWireMessage creates a KaspadMessage from a wire.Message -func FromWireMessage(message wire.Message) (*KaspadMessage, error) { +// FromDomainMessage creates a KaspadMessage from a domainmessage.Message +func FromDomainMessage(message domainmessage.Message) (*KaspadMessage, error) { payload, err := toPayload(message) if err != nil { return nil, err @@ -25,151 +25,151 @@ func FromWireMessage(message wire.Message) (*KaspadMessage, error) { }, nil } -func toPayload(message wire.Message) (isKaspadMessage_Payload, error) { +func toPayload(message domainmessage.Message) (isKaspadMessage_Payload, error) { switch message := message.(type) { - case *wire.MsgAddresses: + case *domainmessage.MsgAddresses: payload := new(KaspadMessage_Addresses) - err := payload.fromWireMessage(message) + err := payload.fromDomainMessage(message) if err != nil { return nil, err } return payload, nil - case *wire.MsgBlock: + case *domainmessage.MsgBlock: payload := new(KaspadMessage_Block) - err := payload.fromWireMessage(message) + err := payload.fromDomainMessage(message) if err != nil { return nil, err } return payload, nil - case *wire.MsgRequestBlockLocator: + case *domainmessage.MsgRequestBlockLocator: payload := new(KaspadMessage_RequestBlockLocator) - err := payload.fromWireMessage(message) + err := payload.fromDomainMessage(message) if err != nil { return nil, err } return payload, nil - case *wire.MsgBlockLocator: + case *domainmessage.MsgBlockLocator: payload := new(KaspadMessage_BlockLocator) - err := payload.fromWireMessage(message) + err := payload.fromDomainMessage(message) if err != nil { return nil, err } return payload, nil - case *wire.MsgRequestAddresses: + case *domainmessage.MsgRequestAddresses: payload := new(KaspadMessage_RequestAddresses) - err := payload.fromWireMessage(message) + err := payload.fromDomainMessage(message) if err != nil { return nil, err } return payload, nil - case *wire.MsgRequestIBDBlocks: + case *domainmessage.MsgRequestIBDBlocks: payload := new(KaspadMessage_RequestIBDBlocks) - err := payload.fromWireMessage(message) + err := payload.fromDomainMessage(message) if err != nil { return nil, err } return payload, nil - case *wire.MsgRequestNextIBDBlocks: + case *domainmessage.MsgRequestNextIBDBlocks: payload := new(KaspadMessage_RequestNextIBDBlocks) - err := payload.fromWireMessage(message) + err := payload.fromDomainMessage(message) if err != nil { return nil, err } return payload, nil - case *wire.MsgDoneIBDBlocks: + case *domainmessage.MsgDoneIBDBlocks: payload := new(KaspadMessage_DoneIBDBlocks) - err := payload.fromWireMessage(message) + err := payload.fromDomainMessage(message) if err != nil { return nil, err } return payload, nil - case *wire.MsgRequestRelayBlocks: + case *domainmessage.MsgRequestRelayBlocks: payload := new(KaspadMessage_RequestRelayBlocks) - err := payload.fromWireMessage(message) + err := payload.fromDomainMessage(message) if err != nil { return nil, err } return payload, nil - case *wire.MsgRequestSelectedTip: + case *domainmessage.MsgRequestSelectedTip: payload := new(KaspadMessage_RequestSelectedTip) - err := payload.fromWireMessage(message) + err := payload.fromDomainMessage(message) if err != nil { return nil, err } return payload, nil - case *wire.MsgRequestTransactions: + case *domainmessage.MsgRequestTransactions: payload := new(KaspadMessage_RequestTransactions) - err := payload.fromWireMessage(message) + err := payload.fromDomainMessage(message) if err != nil { return nil, err } return payload, nil - case *wire.MsgTransactionNotFound: + case *domainmessage.MsgTransactionNotFound: payload := new(KaspadMessage_TransactionNotFound) - err := payload.fromWireMessage(message) + err := payload.fromDomainMessage(message) if err != nil { return nil, err } return payload, nil - case *wire.MsgIBDBlock: + case *domainmessage.MsgIBDBlock: payload := new(KaspadMessage_IbdBlock) - err := payload.fromWireMessage(message) + err := payload.fromDomainMessage(message) if err != nil { return nil, err } return payload, nil - case *wire.MsgInvRelayBlock: + case *domainmessage.MsgInvRelayBlock: payload := new(KaspadMessage_InvRelayBlock) - err := payload.fromWireMessage(message) + err := payload.fromDomainMessage(message) if err != nil { return nil, err } return payload, nil - case *wire.MsgInvTransaction: + case *domainmessage.MsgInvTransaction: payload := new(KaspadMessage_InvTransactions) - err := payload.fromWireMessage(message) + err := payload.fromDomainMessage(message) if err != nil { return nil, err } return payload, nil - case *wire.MsgPing: + case *domainmessage.MsgPing: payload := new(KaspadMessage_Ping) - err := payload.fromWireMessage(message) + err := payload.fromDomainMessage(message) if err != nil { return nil, err } return payload, nil - case *wire.MsgPong: + case *domainmessage.MsgPong: payload := new(KaspadMessage_Pong) - err := payload.fromWireMessage(message) + err := payload.fromDomainMessage(message) if err != nil { return nil, err } return payload, nil - case *wire.MsgSelectedTip: + case *domainmessage.MsgSelectedTip: payload := new(KaspadMessage_SelectedTip) - err := payload.fromWireMessage(message) + err := payload.fromDomainMessage(message) if err != nil { return nil, err } return payload, nil - case *wire.MsgTx: + case *domainmessage.MsgTx: payload := new(KaspadMessage_Transaction) - err := payload.fromWireMessage(message) + err := payload.fromDomainMessage(message) if err != nil { return nil, err } return payload, nil - case *wire.MsgVerAck: + case *domainmessage.MsgVerAck: payload := new(KaspadMessage_Verack) - err := payload.fromWireMessage(message) + err := payload.fromDomainMessage(message) if err != nil { return nil, err } return payload, nil - case *wire.MsgVersion: + case *domainmessage.MsgVersion: payload := new(KaspadMessage_Version) - err := payload.fromWireMessage(message) + err := payload.fromDomainMessage(message) if err != nil { return nil, err } diff --git a/netadapter/standalone/minimal_net_adapter.go b/netadapter/standalone/minimal_net_adapter.go index 57e315e4d..86428b4df 100644 --- a/netadapter/standalone/minimal_net_adapter.go +++ b/netadapter/standalone/minimal_net_adapter.go @@ -8,8 +8,8 @@ import ( "github.com/kaspanet/kaspad/protocol/common" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/netadapter/router" - "github.com/kaspanet/kaspad/wire" "github.com/kaspanet/kaspad/config" "github.com/kaspanet/kaspad/netadapter" @@ -89,9 +89,9 @@ func handlePingPong(routes *Routes) error { return err } - pingMessage := message.(*wire.MsgPing) + pingMessage := message.(*domainmessage.MsgPing) - err = routes.OutgoingRoute.Enqueue(&wire.MsgPong{Nonce: pingMessage.Nonce}) + err = routes.OutgoingRoute.Enqueue(&domainmessage.MsgPong{Nonce: pingMessage.Nonce}) if err != nil { return err } @@ -104,12 +104,12 @@ func handleHandshake(routes *Routes, ourID *id.ID) error { return err } - versionMessage, ok := msg.(*wire.MsgVersion) + versionMessage, ok := msg.(*domainmessage.MsgVersion) if !ok { - return errors.Errorf("expected first message to be of type %s, but got %s", wire.CmdVersion, msg.Command()) + return errors.Errorf("expected first message to be of type %s, but got %s", domainmessage.CmdVersion, msg.Command()) } - err = routes.OutgoingRoute.Enqueue(&wire.MsgVersion{ + err = routes.OutgoingRoute.Enqueue(&domainmessage.MsgVersion{ ProtocolVersion: versionMessage.ProtocolVersion, Services: versionMessage.Services, Timestamp: mstime.Now(), @@ -129,12 +129,12 @@ func handleHandshake(routes *Routes, ourID *id.ID) error { return err } - _, ok = msg.(*wire.MsgVerAck) + _, ok = msg.(*domainmessage.MsgVerAck) if !ok { - return errors.Errorf("expected second message to be of type %s, but got %s", wire.CmdVerAck, msg.Command()) + return errors.Errorf("expected second message to be of type %s, but got %s", domainmessage.CmdVerAck, msg.Command()) } - err = routes.OutgoingRoute.Enqueue(&wire.MsgVerAck{}) + err = routes.OutgoingRoute.Enqueue(&domainmessage.MsgVerAck{}) if err != nil { return err } @@ -143,11 +143,11 @@ func handleHandshake(routes *Routes, ourID *id.ID) error { } func generateRouteInitializer() (netadapter.RouterInitializer, <-chan *Routes) { - cmdsWithBuiltInRoutes := []wire.MessageCommand{wire.CmdVerAck, wire.CmdVersion, wire.CmdPing} + cmdsWithBuiltInRoutes := []domainmessage.MessageCommand{domainmessage.CmdVerAck, domainmessage.CmdVersion, domainmessage.CmdPing} - everythingElse := make([]wire.MessageCommand, 0, len(wire.MessageCommandToString)-len(cmdsWithBuiltInRoutes)) + everythingElse := make([]domainmessage.MessageCommand, 0, len(domainmessage.MessageCommandToString)-len(cmdsWithBuiltInRoutes)) outerLoop: - for command := range wire.MessageCommandToString { + for command := range domainmessage.MessageCommandToString { for _, cmdWithBuiltInRoute := range cmdsWithBuiltInRoutes { if command == cmdWithBuiltInRoute { continue outerLoop @@ -160,11 +160,11 @@ outerLoop: routesChan := make(chan *Routes) routeInitializer := func(router *router.Router, netConnection *netadapter.NetConnection) { - handshakeRoute, err := router.AddIncomingRoute([]wire.MessageCommand{wire.CmdVersion, wire.CmdVerAck}) + handshakeRoute, err := router.AddIncomingRoute([]domainmessage.MessageCommand{domainmessage.CmdVersion, domainmessage.CmdVerAck}) if err != nil { panic(errors.Wrap(err, "error registering handshake route")) } - pingRoute, err := router.AddIncomingRoute([]wire.MessageCommand{wire.CmdPing}) + pingRoute, err := router.AddIncomingRoute([]domainmessage.MessageCommand{domainmessage.CmdPing}) if err != nil { panic(errors.Wrap(err, "error registering ping route")) } diff --git a/netadapter/standalone/routes.go b/netadapter/standalone/routes.go index cc80ac6ba..e9fabbe98 100644 --- a/netadapter/standalone/routes.go +++ b/netadapter/standalone/routes.go @@ -7,8 +7,8 @@ import ( "github.com/pkg/errors" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/netadapter/router" - "github.com/kaspanet/kaspad/wire" ) // Routes holds the incoming and outgoing routes of a connection created by MinimalNetAdapter @@ -21,7 +21,7 @@ type Routes struct { // WaitForMessageOfType waits for a message of requested type up to `timeout`, skipping all messages of any other type // received while waiting -func (r *Routes) WaitForMessageOfType(command wire.MessageCommand, timeout time.Duration) (wire.Message, error) { +func (r *Routes) WaitForMessageOfType(command domainmessage.MessageCommand, timeout time.Duration) (domainmessage.Message, error) { timeoutTime := time.Now().Add(timeout) for { message, err := r.IncomingRoute.DequeueWithTimeout(timeoutTime.Sub(time.Now())) diff --git a/protocol/flowcontext/blocks.go b/protocol/flowcontext/blocks.go index b6803115c..a8f8bd7d5 100644 --- a/protocol/flowcontext/blocks.go +++ b/protocol/flowcontext/blocks.go @@ -4,10 +4,10 @@ import ( "sync/atomic" "github.com/kaspanet/kaspad/blockdag" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/protocol/flows/blockrelay" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) // OnNewBlock updates the mempool after a new block arrival, and @@ -47,10 +47,10 @@ func (f *FlowContext) broadcastTransactionsAfterBlockAdded(block *util.Block, tr if len(txIDsToBroadcast) == 0 { return nil } - if len(txIDsToBroadcast) > wire.MaxInvPerTxInvMsg { - txIDsToBroadcast = txIDsToBroadcast[:wire.MaxInvPerTxInvMsg] + if len(txIDsToBroadcast) > domainmessage.MaxInvPerTxInvMsg { + txIDsToBroadcast = txIDsToBroadcast[:domainmessage.MaxInvPerTxInvMsg] } - inv := wire.NewMsgInvTransaction(txIDsToBroadcast) + inv := domainmessage.NewMsgInvTransaction(txIDsToBroadcast) return f.Broadcast(inv) } @@ -66,5 +66,5 @@ func (f *FlowContext) AddBlock(block *util.Block, flags blockdag.BehaviorFlags) if err != nil { return err } - return f.Broadcast(wire.NewMsgInvBlock(block.Hash())) + return f.Broadcast(domainmessage.NewMsgInvBlock(block.Hash())) } diff --git a/protocol/flowcontext/network.go b/protocol/flowcontext/network.go index 3d644150d..822d35d68 100644 --- a/protocol/flowcontext/network.go +++ b/protocol/flowcontext/network.go @@ -2,10 +2,10 @@ package flowcontext import ( "github.com/kaspanet/kaspad/connmanager" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/netadapter" "github.com/kaspanet/kaspad/protocol/common" peerpkg "github.com/kaspanet/kaspad/protocol/peer" - "github.com/kaspanet/kaspad/wire" "github.com/pkg/errors" ) @@ -47,7 +47,7 @@ func (f *FlowContext) readyPeerConnections() []*netadapter.NetConnection { } // Broadcast broadcast the given message to all the ready peers. -func (f *FlowContext) Broadcast(message wire.Message) error { +func (f *FlowContext) Broadcast(message domainmessage.Message) error { return f.netAdapter.Broadcast(f.readyPeerConnections(), message) } diff --git a/protocol/flowcontext/transactions.go b/protocol/flowcontext/transactions.go index c386eb099..95bda7553 100644 --- a/protocol/flowcontext/transactions.go +++ b/protocol/flowcontext/transactions.go @@ -1,11 +1,11 @@ package flowcontext import ( + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/mempool" "github.com/kaspanet/kaspad/protocol/flows/relaytransactions" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" "github.com/pkg/errors" "time" ) @@ -25,7 +25,7 @@ func (f *FlowContext) AddTransaction(tx *util.Tx) error { } f.transactionsToRebroadcast[*tx.ID()] = tx - inv := wire.NewMsgInvTransaction([]*daghash.TxID{tx.ID()}) + inv := domainmessage.NewMsgInvTransaction([]*daghash.TxID{tx.ID()}) return f.Broadcast(inv) } diff --git a/protocol/flows/addressexchange/receiveaddresses.go b/protocol/flows/addressexchange/receiveaddresses.go index 710671f5d..38810bc29 100644 --- a/protocol/flows/addressexchange/receiveaddresses.go +++ b/protocol/flows/addressexchange/receiveaddresses.go @@ -3,11 +3,11 @@ package addressexchange import ( "github.com/kaspanet/kaspad/addressmanager" "github.com/kaspanet/kaspad/config" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/netadapter/router" "github.com/kaspanet/kaspad/protocol/common" peerpkg "github.com/kaspanet/kaspad/protocol/peer" "github.com/kaspanet/kaspad/protocol/protocolerrors" - "github.com/kaspanet/kaspad/wire" ) // ReceiveAddressesContext is the interface for the context needed for the ReceiveAddresses flow. @@ -25,7 +25,7 @@ func ReceiveAddresses(context ReceiveAddressesContext, incomingRoute *router.Rou } subnetworkID := peer.SubnetworkID() - msgGetAddresses := wire.NewMsgRequestAddresses(false, subnetworkID) + msgGetAddresses := domainmessage.NewMsgRequestAddresses(false, subnetworkID) err := outgoingRoute.Enqueue(msgGetAddresses) if err != nil { return err @@ -36,7 +36,7 @@ func ReceiveAddresses(context ReceiveAddressesContext, incomingRoute *router.Rou return err } - msgAddresses := message.(*wire.MsgAddresses) + msgAddresses := message.(*domainmessage.MsgAddresses) if len(msgAddresses.AddrList) > addressmanager.GetAddressesMax { return protocolerrors.Errorf(true, "address count excceeded %d", addressmanager.GetAddressesMax) } @@ -53,7 +53,7 @@ func ReceiveAddresses(context ReceiveAddressesContext, incomingRoute *router.Rou // TODO(libp2p) Consider adding to peer known addresses set // TODO(libp2p) Replace with real peer IP - fakeSourceAddress := new(wire.NetAddress) + fakeSourceAddress := new(domainmessage.NetAddress) context.AddressManager().AddAddresses(msgAddresses.AddrList, fakeSourceAddress, msgAddresses.SubnetworkID) return nil } diff --git a/protocol/flows/addressexchange/sendaddresses.go b/protocol/flows/addressexchange/sendaddresses.go index 0a11bdc11..2f93ba83d 100644 --- a/protocol/flows/addressexchange/sendaddresses.go +++ b/protocol/flows/addressexchange/sendaddresses.go @@ -2,8 +2,8 @@ package addressexchange import ( "github.com/kaspanet/kaspad/addressmanager" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/netadapter/router" - "github.com/kaspanet/kaspad/wire" "math/rand" ) @@ -20,10 +20,10 @@ func SendAddresses(context SendAddressesContext, incomingRoute *router.Route, ou return err } - msgGetAddresses := message.(*wire.MsgRequestAddresses) + msgGetAddresses := message.(*domainmessage.MsgRequestAddresses) addresses := context.AddressManager().AddressCache(msgGetAddresses.IncludeAllSubnetworks, msgGetAddresses.SubnetworkID) - msgAddresses := wire.NewMsgAddresses(msgGetAddresses.IncludeAllSubnetworks, msgGetAddresses.SubnetworkID) + msgAddresses := domainmessage.NewMsgAddresses(msgGetAddresses.IncludeAllSubnetworks, msgGetAddresses.SubnetworkID) err = msgAddresses.AddAddresses(shuffleAddresses(addresses)...) if err != nil { return err @@ -33,14 +33,14 @@ func SendAddresses(context SendAddressesContext, incomingRoute *router.Route, ou } // shuffleAddresses randomizes the given addresses sent if there are more than the maximum allowed in one message. -func shuffleAddresses(addresses []*wire.NetAddress) []*wire.NetAddress { +func shuffleAddresses(addresses []*domainmessage.NetAddress) []*domainmessage.NetAddress { addressCount := len(addresses) - if addressCount < wire.MaxAddressesPerMsg { + if addressCount < domainmessage.MaxAddressesPerMsg { return addresses } - shuffleAddresses := make([]*wire.NetAddress, addressCount) + shuffleAddresses := make([]*domainmessage.NetAddress, addressCount) copy(shuffleAddresses, addresses) rand.Shuffle(addressCount, func(i, j int) { @@ -48,6 +48,6 @@ func shuffleAddresses(addresses []*wire.NetAddress) []*wire.NetAddress { }) // Truncate it to the maximum size. - shuffleAddresses = shuffleAddresses[:wire.MaxAddressesPerMsg] + shuffleAddresses = shuffleAddresses[:domainmessage.MaxAddressesPerMsg] return shuffleAddresses } diff --git a/protocol/flows/blockrelay/handle_relay_block_requests.go b/protocol/flows/blockrelay/handle_relay_block_requests.go index d292b0d84..345d00f48 100644 --- a/protocol/flows/blockrelay/handle_relay_block_requests.go +++ b/protocol/flows/blockrelay/handle_relay_block_requests.go @@ -2,10 +2,10 @@ package blockrelay import ( "github.com/kaspanet/kaspad/blockdag" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/netadapter/router" peerpkg "github.com/kaspanet/kaspad/protocol/peer" "github.com/kaspanet/kaspad/protocol/protocolerrors" - "github.com/kaspanet/kaspad/wire" "github.com/pkg/errors" ) @@ -14,7 +14,7 @@ type RelayBlockRequestsContext interface { DAG() *blockdag.BlockDAG } -// HandleRelayBlockRequests listens to wire.MsgRequestRelayBlocks messages and sends +// HandleRelayBlockRequests listens to domainmessage.MsgRequestRelayBlocks messages and sends // their corresponding blocks to the requesting peer. func HandleRelayBlockRequests(context RelayBlockRequestsContext, incomingRoute *router.Route, outgoingRoute *router.Route, peer *peerpkg.Peer) error { @@ -24,7 +24,7 @@ func HandleRelayBlockRequests(context RelayBlockRequestsContext, incomingRoute * if err != nil { return err } - getRelayBlocksMessage := message.(*wire.MsgRequestRelayBlocks) + getRelayBlocksMessage := message.(*domainmessage.MsgRequestRelayBlocks) for _, hash := range getRelayBlocksMessage.Hashes { // Fetch the block from the database. block, err := context.DAG().BlockByHash(hash) diff --git a/protocol/flows/blockrelay/handle_relay_invs.go b/protocol/flows/blockrelay/handle_relay_invs.go index bc47902ac..22b5da812 100644 --- a/protocol/flows/blockrelay/handle_relay_invs.go +++ b/protocol/flows/blockrelay/handle_relay_invs.go @@ -2,6 +2,7 @@ package blockrelay import ( "github.com/kaspanet/kaspad/blockdag" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/netadapter" "github.com/kaspanet/kaspad/netadapter/router" "github.com/kaspanet/kaspad/protocol/blocklogger" @@ -11,7 +12,6 @@ import ( "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/daghash" mathUtil "github.com/kaspanet/kaspad/util/math" - "github.com/kaspanet/kaspad/wire" "github.com/pkg/errors" ) @@ -23,17 +23,17 @@ type RelayInvsContext interface { SharedRequestedBlocks() *SharedRequestedBlocks StartIBDIfRequired() IsInIBD() bool - Broadcast(message wire.Message) error + Broadcast(message domainmessage.Message) error } type handleRelayInvsFlow struct { RelayInvsContext incomingRoute, outgoingRoute *router.Route peer *peerpkg.Peer - invsQueue []*wire.MsgInvRelayBlock + invsQueue []*domainmessage.MsgInvRelayBlock } -// HandleRelayInvs listens to wire.MsgInvRelayBlock messages, requests their corresponding blocks if they +// HandleRelayInvs listens to domainmessage.MsgInvRelayBlock messages, requests their corresponding blocks if they // are missing, adds them to the DAG and propagates them to the rest of the network. func HandleRelayInvs(context RelayInvsContext, incomingRoute *router.Route, outgoingRoute *router.Route, peer *peerpkg.Peer) error { @@ -43,7 +43,7 @@ func HandleRelayInvs(context RelayInvsContext, incomingRoute *router.Route, outg incomingRoute: incomingRoute, outgoingRoute: outgoingRoute, peer: peer, - invsQueue: make([]*wire.MsgInvRelayBlock, 0), + invsQueue: make([]*domainmessage.MsgInvRelayBlock, 0), } return flow.start() } @@ -81,10 +81,10 @@ func (flow *handleRelayInvsFlow) start() error { } } -func (flow *handleRelayInvsFlow) readInv() (*wire.MsgInvRelayBlock, error) { +func (flow *handleRelayInvsFlow) readInv() (*domainmessage.MsgInvRelayBlock, error) { if len(flow.invsQueue) > 0 { - var inv *wire.MsgInvRelayBlock + var inv *domainmessage.MsgInvRelayBlock inv, flow.invsQueue = flow.invsQueue[0], flow.invsQueue[1:] return inv, nil } @@ -94,7 +94,7 @@ func (flow *handleRelayInvsFlow) readInv() (*wire.MsgInvRelayBlock, error) { return nil, err } - inv, ok := msg.(*wire.MsgInvRelayBlock) + inv, ok := msg.(*domainmessage.MsgInvRelayBlock) if !ok { return nil, protocolerrors.Errorf(true, "unexpected %s message in the block relay handleRelayInvsFlow while "+ "expecting an inv message", msg.Command()) @@ -103,7 +103,7 @@ func (flow *handleRelayInvsFlow) readInv() (*wire.MsgInvRelayBlock, error) { } func (flow *handleRelayInvsFlow) requestBlocks(requestQueue *hashesQueueSet) error { - numHashesToRequest := mathUtil.MinInt(wire.MsgRequestRelayBlocksHashes, requestQueue.len()) + numHashesToRequest := mathUtil.MinInt(domainmessage.MsgRequestRelayBlocksHashes, requestQueue.len()) hashesToRequest := requestQueue.dequeue(numHashesToRequest) pendingBlocks := map[daghash.Hash]struct{}{} @@ -127,7 +127,7 @@ func (flow *handleRelayInvsFlow) requestBlocks(requestQueue *hashesQueueSet) err // clean from any pending blocks. defer flow.SharedRequestedBlocks().removeSet(pendingBlocks) - getRelayBlocksMsg := wire.NewMsgRequestRelayBlocks(filteredHashesToRequest) + getRelayBlocksMsg := domainmessage.NewMsgRequestRelayBlocks(filteredHashesToRequest) err := flow.outgoingRoute.Enqueue(getRelayBlocksMsg) if err != nil { return err @@ -160,9 +160,9 @@ func (flow *handleRelayInvsFlow) requestBlocks(requestQueue *hashesQueueSet) err // readMsgBlock returns the next msgBlock in msgChan, and populates invsQueue with any inv messages that meanwhile arrive. // -// Note: this function assumes msgChan can contain only wire.MsgInvRelayBlock and wire.MsgBlock messages. +// Note: this function assumes msgChan can contain only domainmessage.MsgInvRelayBlock and domainmessage.MsgBlock messages. func (flow *handleRelayInvsFlow) readMsgBlock() ( - msgBlock *wire.MsgBlock, err error) { + msgBlock *domainmessage.MsgBlock, err error) { for { message, err := flow.incomingRoute.DequeueWithTimeout(common.DefaultTimeout) @@ -171,9 +171,9 @@ func (flow *handleRelayInvsFlow) readMsgBlock() ( } switch message := message.(type) { - case *wire.MsgInvRelayBlock: + case *domainmessage.MsgInvRelayBlock: flow.invsQueue = append(flow.invsQueue, message) - case *wire.MsgBlock: + case *domainmessage.MsgBlock: return message, nil default: return nil, errors.Errorf("unexpected message %s", message.Command()) @@ -230,7 +230,7 @@ func (flow *handleRelayInvsFlow) processAndRelayBlock(requestQueue *hashesQueueS // sm.restartSyncIfNeeded() //// Clear the rejected transactions. //sm.rejectedTxns = make(map[daghash.TxID]struct{}) - err = flow.Broadcast(wire.NewMsgInvBlock(blockHash)) + err = flow.Broadcast(domainmessage.NewMsgInvBlock(blockHash)) if err != nil { return err } diff --git a/protocol/flows/handshake/handshake.go b/protocol/flows/handshake/handshake.go index c3c4e57a7..ee52ec735 100644 --- a/protocol/flows/handshake/handshake.go +++ b/protocol/flows/handshake/handshake.go @@ -12,11 +12,11 @@ import ( "github.com/kaspanet/kaspad/config" "github.com/kaspanet/kaspad/netadapter" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/netadapter/router" routerpkg "github.com/kaspanet/kaspad/netadapter/router" peerpkg "github.com/kaspanet/kaspad/protocol/peer" "github.com/kaspanet/kaspad/util/locks" - "github.com/kaspanet/kaspad/wire" "github.com/pkg/errors" ) @@ -48,7 +48,7 @@ func HandleHandshake(context HandleHandshakeContext, netConnection *netadapter.N peer = peerpkg.New(netConnection) - var peerAddress *wire.NetAddress + var peerAddress *domainmessage.NetAddress spawn("HandleHandshake-ReceiveVersion", func() { defer wg.Done() address, err := ReceiveVersion(context, receiveVersionRoute, outgoingRoute, peer) diff --git a/protocol/flows/handshake/receiveversion.go b/protocol/flows/handshake/receiveversion.go index d762552ed..6715557ef 100644 --- a/protocol/flows/handshake/receiveversion.go +++ b/protocol/flows/handshake/receiveversion.go @@ -1,11 +1,11 @@ package handshake import ( + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/netadapter/router" "github.com/kaspanet/kaspad/protocol/common" peerpkg "github.com/kaspanet/kaspad/protocol/peer" "github.com/kaspanet/kaspad/protocol/protocolerrors" - "github.com/kaspanet/kaspad/wire" ) var ( @@ -16,7 +16,7 @@ var ( // minAcceptableProtocolVersion is the lowest protocol version that a // connected peer may support. - minAcceptableProtocolVersion = wire.ProtocolVersion + minAcceptableProtocolVersion = domainmessage.ProtocolVersion ) type receiveVersionFlow struct { @@ -28,7 +28,7 @@ type receiveVersionFlow struct { // ReceiveVersion waits for the peer to send a version message, sends a // verack in response, and updates its info accordingly. func ReceiveVersion(context HandleHandshakeContext, incomingRoute *router.Route, outgoingRoute *router.Route, - peer *peerpkg.Peer) (*wire.NetAddress, error) { + peer *peerpkg.Peer) (*domainmessage.NetAddress, error) { flow := &receiveVersionFlow{ HandleHandshakeContext: context, @@ -40,13 +40,13 @@ func ReceiveVersion(context HandleHandshakeContext, incomingRoute *router.Route, return flow.start() } -func (flow *receiveVersionFlow) start() (*wire.NetAddress, error) { +func (flow *receiveVersionFlow) start() (*domainmessage.NetAddress, error) { message, err := flow.incomingRoute.DequeueWithTimeout(common.DefaultTimeout) if err != nil { return nil, err } - msgVersion, ok := message.(*wire.MsgVersion) + msgVersion, ok := message.(*domainmessage.MsgVersion) if !ok { return nil, protocolerrors.New(true, "a version message must precede all others") } @@ -59,7 +59,7 @@ func (flow *receiveVersionFlow) start() (*wire.NetAddress, error) { // too old. // // NOTE: If minAcceptableProtocolVersion is raised to be higher than - // wire.RejectVersion, this should send a reject packet before + // domainmessage.RejectVersion, this should send a reject packet before // disconnecting. if msgVersion.ProtocolVersion < minAcceptableProtocolVersion { //TODO(libp2p) create error type for disconnect but don't ban @@ -86,7 +86,7 @@ func (flow *receiveVersionFlow) start() (*wire.NetAddress, error) { //} flow.peer.UpdateFieldsFromMsgVersion(msgVersion) - err = flow.outgoingRoute.Enqueue(wire.NewMsgVerAck()) + err = flow.outgoingRoute.Enqueue(domainmessage.NewMsgVerAck()) if err != nil { return nil, err } diff --git a/protocol/flows/handshake/sendversion.go b/protocol/flows/handshake/sendversion.go index 6f344bea2..108449b71 100644 --- a/protocol/flows/handshake/sendversion.go +++ b/protocol/flows/handshake/sendversion.go @@ -1,10 +1,10 @@ package handshake import ( + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/netadapter/router" "github.com/kaspanet/kaspad/protocol/common" "github.com/kaspanet/kaspad/version" - "github.com/kaspanet/kaspad/wire" ) var ( @@ -18,11 +18,11 @@ var ( // defaultServices describes the default services that are supported by // the server. - defaultServices = wire.SFNodeNetwork | wire.SFNodeBloom | wire.SFNodeCF + defaultServices = domainmessage.SFNodeNetwork | domainmessage.SFNodeBloom | domainmessage.SFNodeCF // defaultRequiredServices describes the default services that are // required to be supported by outbound peers. - defaultRequiredServices = wire.SFNodeNetwork + defaultRequiredServices = domainmessage.SFNodeNetwork ) type sendVersionFlow struct { @@ -49,14 +49,14 @@ func (flow *sendVersionFlow) start() error { if err != nil { return err } - msg := wire.NewMsgVersion(localAddress, flow.NetAdapter().ID(), selectedTipHash, subnetworkID) + msg := domainmessage.NewMsgVersion(localAddress, flow.NetAdapter().ID(), selectedTipHash, subnetworkID) msg.AddUserAgent(userAgentName, userAgentVersion, flow.Config().UserAgentComments...) // Advertise the services flag msg.Services = defaultServices // Advertise our max supported protocol version. - msg.ProtocolVersion = wire.ProtocolVersion + msg.ProtocolVersion = domainmessage.ProtocolVersion // Advertise if inv messages for transactions are desired. msg.DisableRelayTx = flow.Config().BlocksOnly diff --git a/protocol/flows/ibd/handle_request_block_locator.go b/protocol/flows/ibd/handle_request_block_locator.go index 658ccfc11..f319cd0da 100644 --- a/protocol/flows/ibd/handle_request_block_locator.go +++ b/protocol/flows/ibd/handle_request_block_locator.go @@ -2,10 +2,10 @@ package ibd import ( "github.com/kaspanet/kaspad/blockdag" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/netadapter/router" "github.com/kaspanet/kaspad/protocol/protocolerrors" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) // RequestBlockLocatorContext is the interface for the context needed for the HandleRequestBlockLocator flow. @@ -57,13 +57,13 @@ func (flow *handleRequestBlockLocatorFlow) receiveGetBlockLocator() (lowHash *da if err != nil { return nil, nil, err } - msgGetBlockLocator := message.(*wire.MsgRequestBlockLocator) + msgGetBlockLocator := message.(*domainmessage.MsgRequestBlockLocator) return msgGetBlockLocator.LowHash, msgGetBlockLocator.HighHash, nil } func (flow *handleRequestBlockLocatorFlow) sendBlockLocator(locator blockdag.BlockLocator) error { - msgBlockLocator := wire.NewMsgBlockLocator(locator) + msgBlockLocator := domainmessage.NewMsgBlockLocator(locator) err := flow.outgoingRoute.Enqueue(msgBlockLocator) if err != nil { return err diff --git a/protocol/flows/ibd/handle_request_ibd_blocks.go b/protocol/flows/ibd/handle_request_ibd_blocks.go index b79a05de9..5d4475fba 100644 --- a/protocol/flows/ibd/handle_request_ibd_blocks.go +++ b/protocol/flows/ibd/handle_request_ibd_blocks.go @@ -3,10 +3,10 @@ package ibd import ( "errors" "github.com/kaspanet/kaspad/blockdag" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/netadapter/router" "github.com/kaspanet/kaspad/protocol/protocolerrors" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) const ibdBatchSize = router.DefaultMaxMessages @@ -66,12 +66,12 @@ func (flow *handleRequestBlocksFlow) start() error { return err } - if _, ok := message.(*wire.MsgRequestNextIBDBlocks); !ok { + if _, ok := message.(*domainmessage.MsgRequestNextIBDBlocks); !ok { return protocolerrors.Errorf(true, "received unexpected message type. "+ - "expected: %s, got: %s", wire.CmdRequestNextIBDBlocks, message.Command()) + "expected: %s, got: %s", domainmessage.CmdRequestNextIBDBlocks, message.Command()) } } - err = flow.outgoingRoute.Enqueue(wire.NewMsgDoneIBDBlocks()) + err = flow.outgoingRoute.Enqueue(domainmessage.NewMsgDoneIBDBlocks()) if err != nil { return err } @@ -85,15 +85,15 @@ func receiveRequestIBDBlocks(incomingRoute *router.Route) (lowHash *daghash.Hash if err != nil { return nil, nil, err } - msgRequestIBDBlocks := message.(*wire.MsgRequestIBDBlocks) + msgRequestIBDBlocks := message.(*domainmessage.MsgRequestIBDBlocks) return msgRequestIBDBlocks.LowHash, msgRequestIBDBlocks.HighHash, nil } func (flow *handleRequestBlocksFlow) buildMsgIBDBlocks(lowHash *daghash.Hash, - highHash *daghash.Hash) ([]*wire.MsgIBDBlock, error) { + highHash *daghash.Hash) ([]*domainmessage.MsgIBDBlock, error) { - const maxHashesInMsgIBDBlocks = wire.MaxInvPerMsg + const maxHashesInMsgIBDBlocks = domainmessage.MaxInvPerMsg blockHashes, err := flow.DAG().AntiPastHashesBetween(lowHash, highHash, maxHashesInMsgIBDBlocks) if err != nil { if errors.Is(err, blockdag.ErrInvalidParameter) { @@ -103,19 +103,19 @@ func (flow *handleRequestBlocksFlow) buildMsgIBDBlocks(lowHash *daghash.Hash, return nil, err } - msgIBDBlocks := make([]*wire.MsgIBDBlock, len(blockHashes)) + msgIBDBlocks := make([]*domainmessage.MsgIBDBlock, len(blockHashes)) for i, blockHash := range blockHashes { block, err := flow.DAG().BlockByHash(blockHash) if err != nil { return nil, err } - msgIBDBlocks[i] = wire.NewMsgIBDBlock(block.MsgBlock()) + msgIBDBlocks[i] = domainmessage.NewMsgIBDBlock(block.MsgBlock()) } return msgIBDBlocks, nil } -func (flow *handleRequestBlocksFlow) sendMsgIBDBlocks(msgIBDBlocks []*wire.MsgIBDBlock) error { +func (flow *handleRequestBlocksFlow) sendMsgIBDBlocks(msgIBDBlocks []*domainmessage.MsgIBDBlock) error { for _, msgIBDBlock := range msgIBDBlocks { err := flow.outgoingRoute.Enqueue(msgIBDBlock) if err != nil { diff --git a/protocol/flows/ibd/ibd.go b/protocol/flows/ibd/ibd.go index 43f027dd8..6dbf54448 100644 --- a/protocol/flows/ibd/ibd.go +++ b/protocol/flows/ibd/ibd.go @@ -2,13 +2,13 @@ package ibd import ( "github.com/kaspanet/kaspad/blockdag" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/netadapter/router" "github.com/kaspanet/kaspad/protocol/common" peerpkg "github.com/kaspanet/kaspad/protocol/peer" "github.com/kaspanet/kaspad/protocol/protocolerrors" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) // HandleIBDContext is the interface for the context needed for the HandleIBD flow. @@ -96,7 +96,7 @@ func (flow *handleIBDFlow) findHighestSharedBlockHash(peerSelectedTipHash *dagha func (flow *handleIBDFlow) sendGetBlockLocator(lowHash *daghash.Hash, highHash *daghash.Hash) error { - msgGetBlockLocator := wire.NewMsgRequestBlockLocator(highHash, lowHash) + msgGetBlockLocator := domainmessage.NewMsgRequestBlockLocator(highHash, lowHash) return flow.outgoingRoute.Enqueue(msgGetBlockLocator) } @@ -105,11 +105,11 @@ func (flow *handleIBDFlow) receiveBlockLocator() (blockLocatorHashes []*daghash. if err != nil { return nil, err } - msgBlockLocator, ok := message.(*wire.MsgBlockLocator) + msgBlockLocator, ok := message.(*domainmessage.MsgBlockLocator) if !ok { return nil, protocolerrors.Errorf(true, "received unexpected message type. "+ - "expected: %s, got: %s", wire.CmdBlockLocator, message.Command()) + "expected: %s, got: %s", domainmessage.CmdBlockLocator, message.Command()) } return msgBlockLocator.BlockLocatorHashes, nil } @@ -140,7 +140,7 @@ func (flow *handleIBDFlow) downloadBlocks(highestSharedBlockHash *daghash.Hash, blocksReceived++ if blocksReceived%ibdBatchSize == 0 { - err = flow.outgoingRoute.Enqueue(wire.NewMsgRequestNextIBDBlocks()) + err = flow.outgoingRoute.Enqueue(domainmessage.NewMsgRequestNextIBDBlocks()) if err != nil { return err } @@ -151,28 +151,28 @@ func (flow *handleIBDFlow) downloadBlocks(highestSharedBlockHash *daghash.Hash, func (flow *handleIBDFlow) sendGetBlocks(highestSharedBlockHash *daghash.Hash, peerSelectedTipHash *daghash.Hash) error { - msgGetBlockInvs := wire.NewMsgRequstIBDBlocks(highestSharedBlockHash, peerSelectedTipHash) + msgGetBlockInvs := domainmessage.NewMsgRequstIBDBlocks(highestSharedBlockHash, peerSelectedTipHash) return flow.outgoingRoute.Enqueue(msgGetBlockInvs) } -func (flow *handleIBDFlow) receiveIBDBlock() (msgIBDBlock *wire.MsgIBDBlock, doneIBD bool, err error) { +func (flow *handleIBDFlow) receiveIBDBlock() (msgIBDBlock *domainmessage.MsgIBDBlock, doneIBD bool, err error) { message, err := flow.incomingRoute.DequeueWithTimeout(common.DefaultTimeout) if err != nil { return nil, false, err } switch message := message.(type) { - case *wire.MsgIBDBlock: + case *domainmessage.MsgIBDBlock: return message, false, nil - case *wire.MsgDoneIBDBlocks: + case *domainmessage.MsgDoneIBDBlocks: return nil, true, nil default: return nil, false, protocolerrors.Errorf(true, "received unexpected message type. "+ - "expected: %s, got: %s", wire.CmdIBDBlock, message.Command()) + "expected: %s, got: %s", domainmessage.CmdIBDBlock, message.Command()) } } -func (flow *handleIBDFlow) processIBDBlock(msgIBDBlock *wire.MsgIBDBlock) error { +func (flow *handleIBDFlow) processIBDBlock(msgIBDBlock *domainmessage.MsgIBDBlock) error { block := util.NewBlock(msgIBDBlock.MsgBlock) if flow.DAG().IsInDAG(block.Hash()) { diff --git a/protocol/flows/ibd/selectedtip/handle_request_selected_tip.go b/protocol/flows/ibd/selectedtip/handle_request_selected_tip.go index 1d06b0e6d..ded5951e7 100644 --- a/protocol/flows/ibd/selectedtip/handle_request_selected_tip.go +++ b/protocol/flows/ibd/selectedtip/handle_request_selected_tip.go @@ -2,8 +2,8 @@ package selectedtip import ( "github.com/kaspanet/kaspad/blockdag" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/netadapter/router" - "github.com/kaspanet/kaspad/wire" "github.com/pkg/errors" ) @@ -46,16 +46,16 @@ func (flow *handleRequestSelectedTipFlow) receiveGetSelectedTip() error { if err != nil { return err } - _, ok := message.(*wire.MsgRequestSelectedTip) + _, ok := message.(*domainmessage.MsgRequestSelectedTip) if !ok { return errors.Errorf("received unexpected message type. "+ - "expected: %s, got: %s", wire.CmdRequestSelectedTip, message.Command()) + "expected: %s, got: %s", domainmessage.CmdRequestSelectedTip, message.Command()) } return nil } func (flow *handleRequestSelectedTipFlow) sendSelectedTipHash() error { - msgSelectedTip := wire.NewMsgSelectedTip(flow.DAG().SelectedTipHash()) + msgSelectedTip := domainmessage.NewMsgSelectedTip(flow.DAG().SelectedTipHash()) return flow.outgoingRoute.Enqueue(msgSelectedTip) } diff --git a/protocol/flows/ibd/selectedtip/request_selected_tip.go b/protocol/flows/ibd/selectedtip/request_selected_tip.go index bce810c76..d55b4074b 100644 --- a/protocol/flows/ibd/selectedtip/request_selected_tip.go +++ b/protocol/flows/ibd/selectedtip/request_selected_tip.go @@ -2,11 +2,11 @@ package selectedtip import ( "github.com/kaspanet/kaspad/blockdag" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/netadapter/router" "github.com/kaspanet/kaspad/protocol/common" peerpkg "github.com/kaspanet/kaspad/protocol/peer" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) // RequestSelectedTipContext is the interface for the context needed for the RequestSelectedTip flow. @@ -64,7 +64,7 @@ func (flow *requestSelectedTipFlow) runSelectedTipRequest() error { } func (flow *requestSelectedTipFlow) requestSelectedTip() error { - msgGetSelectedTip := wire.NewMsgRequestSelectedTip() + msgGetSelectedTip := domainmessage.NewMsgRequestSelectedTip() return flow.outgoingRoute.Enqueue(msgGetSelectedTip) } @@ -73,7 +73,7 @@ func (flow *requestSelectedTipFlow) receiveSelectedTip() (selectedTipHash *dagha if err != nil { return nil, err } - msgSelectedTip := message.(*wire.MsgSelectedTip) + msgSelectedTip := message.(*domainmessage.MsgSelectedTip) return msgSelectedTip.SelectedTipHash, nil } diff --git a/protocol/flows/ping/receive.go b/protocol/flows/ping/receive.go index 63863b3dc..89c2e2d24 100644 --- a/protocol/flows/ping/receive.go +++ b/protocol/flows/ping/receive.go @@ -1,8 +1,8 @@ package ping import ( + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/netadapter/router" - "github.com/kaspanet/kaspad/wire" ) // ReceivePingsContext is the interface for the context needed for the ReceivePings flow. @@ -31,9 +31,9 @@ func (flow *receivePingsFlow) start() error { if err != nil { return err } - pingMessage := message.(*wire.MsgPing) + pingMessage := message.(*domainmessage.MsgPing) - pongMessage := wire.NewMsgPong(pingMessage.Nonce) + pongMessage := domainmessage.NewMsgPong(pingMessage.Nonce) err = flow.outgoingRoute.Enqueue(pongMessage) if err != nil { return err diff --git a/protocol/flows/ping/send.go b/protocol/flows/ping/send.go index fe4257205..6f8bc25dd 100644 --- a/protocol/flows/ping/send.go +++ b/protocol/flows/ping/send.go @@ -3,12 +3,12 @@ package ping import ( "time" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/netadapter/router" "github.com/kaspanet/kaspad/protocol/common" peerpkg "github.com/kaspanet/kaspad/protocol/peer" "github.com/kaspanet/kaspad/protocol/protocolerrors" "github.com/kaspanet/kaspad/util/random" - "github.com/kaspanet/kaspad/wire" ) // SendPingsContext is the interface for the context needed for the SendPings flow. @@ -46,7 +46,7 @@ func (flow *sendPingsFlow) start() error { } flow.peer.SetPingPending(nonce) - pingMessage := wire.NewMsgPing(nonce) + pingMessage := domainmessage.NewMsgPing(nonce) err = flow.outgoingRoute.Enqueue(pingMessage) if err != nil { return err @@ -56,7 +56,7 @@ func (flow *sendPingsFlow) start() error { if err != nil { return err } - pongMessage := message.(*wire.MsgPong) + pongMessage := message.(*domainmessage.MsgPong) if pongMessage.Nonce != pingMessage.Nonce { return protocolerrors.New(true, "nonce mismatch between ping and pong") } diff --git a/protocol/flows/relaytransactions/handle_relayed_transactions.go b/protocol/flows/relaytransactions/handle_relayed_transactions.go index 4a9dbeb63..b3595799b 100644 --- a/protocol/flows/relaytransactions/handle_relayed_transactions.go +++ b/protocol/flows/relaytransactions/handle_relayed_transactions.go @@ -2,6 +2,7 @@ package relaytransactions import ( "github.com/kaspanet/kaspad/blockdag" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/mempool" "github.com/kaspanet/kaspad/netadapter" "github.com/kaspanet/kaspad/netadapter/router" @@ -9,7 +10,6 @@ import ( "github.com/kaspanet/kaspad/protocol/protocolerrors" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" "github.com/pkg/errors" ) @@ -20,23 +20,23 @@ type TransactionsRelayContext interface { DAG() *blockdag.BlockDAG SharedRequestedTransactions() *SharedRequestedTransactions TxPool() *mempool.TxPool - Broadcast(message wire.Message) error + Broadcast(message domainmessage.Message) error } type handleRelayedTransactionsFlow struct { TransactionsRelayContext incomingRoute, outgoingRoute *router.Route - invsQueue []*wire.MsgInvTransaction + invsQueue []*domainmessage.MsgInvTransaction } -// HandleRelayedTransactions listens to wire.MsgInvTransaction messages, requests their corresponding transactions if they +// HandleRelayedTransactions listens to domainmessage.MsgInvTransaction messages, requests their corresponding transactions if they // are missing, adds them to the mempool and propagates them to the rest of the network. func HandleRelayedTransactions(context TransactionsRelayContext, incomingRoute *router.Route, outgoingRoute *router.Route) error { flow := &handleRelayedTransactionsFlow{ TransactionsRelayContext: context, incomingRoute: incomingRoute, outgoingRoute: outgoingRoute, - invsQueue: make([]*wire.MsgInvTransaction, 0), + invsQueue: make([]*domainmessage.MsgInvTransaction, 0), } return flow.start() } @@ -61,7 +61,7 @@ func (flow *handleRelayedTransactionsFlow) start() error { } func (flow *handleRelayedTransactionsFlow) requestInvTransactions( - inv *wire.MsgInvTransaction) (requestedIDs []*daghash.TxID, err error) { + inv *domainmessage.MsgInvTransaction) (requestedIDs []*daghash.TxID, err error) { idsToRequest := make([]*daghash.TxID, 0, len(inv.TxIDs)) for _, txID := range inv.TxIDs { @@ -79,7 +79,7 @@ func (flow *handleRelayedTransactionsFlow) requestInvTransactions( return idsToRequest, nil } - msgGetTransactions := wire.NewMsgRequestTransactions(idsToRequest) + msgGetTransactions := domainmessage.NewMsgRequestTransactions(idsToRequest) err = flow.outgoingRoute.Enqueue(msgGetTransactions) if err != nil { flow.SharedRequestedTransactions().removeMany(idsToRequest) @@ -103,7 +103,7 @@ func (flow *handleRelayedTransactionsFlow) isKnownTransaction(txID *daghash.TxID // checked because the vast majority of transactions consist of // two outputs where one is some form of "pay-to-somebody-else" // and the other is a change output. - prevOut := wire.Outpoint{TxID: *txID} + prevOut := domainmessage.Outpoint{TxID: *txID} for i := uint32(0); i < 2; i++ { prevOut.Index = i _, ok := flow.DAG().GetUTXOEntry(prevOut) @@ -114,9 +114,9 @@ func (flow *handleRelayedTransactionsFlow) isKnownTransaction(txID *daghash.TxID return false } -func (flow *handleRelayedTransactionsFlow) readInv() (*wire.MsgInvTransaction, error) { +func (flow *handleRelayedTransactionsFlow) readInv() (*domainmessage.MsgInvTransaction, error) { if len(flow.invsQueue) > 0 { - var inv *wire.MsgInvTransaction + var inv *domainmessage.MsgInvTransaction inv, flow.invsQueue = flow.invsQueue[0], flow.invsQueue[1:] return inv, nil } @@ -126,7 +126,7 @@ func (flow *handleRelayedTransactionsFlow) readInv() (*wire.MsgInvTransaction, e return nil, err } - inv, ok := msg.(*wire.MsgInvTransaction) + inv, ok := msg.(*domainmessage.MsgInvTransaction) if !ok { return nil, protocolerrors.Errorf(true, "unexpected %s message in the block relay flow while "+ "expecting an inv message", msg.Command()) @@ -141,7 +141,7 @@ func (flow *handleRelayedTransactionsFlow) broadcastAcceptedTransactions(accepte for i, tx := range acceptedTxs { idsToBroadcast[i] = tx.Tx.ID() } - inv := wire.NewMsgInvTransaction(idsToBroadcast) + inv := domainmessage.NewMsgInvTransaction(idsToBroadcast) return flow.Broadcast(inv) } @@ -150,7 +150,7 @@ func (flow *handleRelayedTransactionsFlow) broadcastAcceptedTransactions(accepte // // and populates invsQueue with any inv messages that meanwhile arrive. func (flow *handleRelayedTransactionsFlow) readMsgTxOrNotFound() ( - msgTx *wire.MsgTx, msgNotFound *wire.MsgTransactionNotFound, err error) { + msgTx *domainmessage.MsgTx, msgNotFound *domainmessage.MsgTransactionNotFound, err error) { for { message, err := flow.incomingRoute.DequeueWithTimeout(common.DefaultTimeout) @@ -159,11 +159,11 @@ func (flow *handleRelayedTransactionsFlow) readMsgTxOrNotFound() ( } switch message := message.(type) { - case *wire.MsgInvTransaction: + case *domainmessage.MsgInvTransaction: flow.invsQueue = append(flow.invsQueue, message) - case *wire.MsgTx: + case *domainmessage.MsgTx: return message, nil, nil - case *wire.MsgTransactionNotFound: + case *domainmessage.MsgTransactionNotFound: return nil, message, nil default: return nil, nil, errors.Errorf("unexpected message %s", message.Command()) diff --git a/protocol/flows/relaytransactions/handle_requested_transactions.go b/protocol/flows/relaytransactions/handle_requested_transactions.go index 5b785abf7..abb31a033 100644 --- a/protocol/flows/relaytransactions/handle_requested_transactions.go +++ b/protocol/flows/relaytransactions/handle_requested_transactions.go @@ -1,8 +1,8 @@ package relaytransactions import ( + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/netadapter/router" - "github.com/kaspanet/kaspad/wire" ) type handleRequestedTransactionsFlow struct { @@ -10,7 +10,7 @@ type handleRequestedTransactionsFlow struct { incomingRoute, outgoingRoute *router.Route } -// HandleRequestedTransactions listens to wire.MsgRequestTransactions messages, responding with the requested +// HandleRequestedTransactions listens to domainmessage.MsgRequestTransactions messages, responding with the requested // transactions if those are in the mempool. // Missing transactions would be ignored func HandleRequestedTransactions(context TransactionsRelayContext, incomingRoute *router.Route, outgoingRoute *router.Route) error { @@ -33,7 +33,7 @@ func (flow *handleRequestedTransactionsFlow) start() error { tx, ok := flow.TxPool().FetchTransaction(transactionID) if !ok { - msgTransactionNotFound := wire.NewMsgTransactionNotFound(transactionID) + msgTransactionNotFound := domainmessage.NewMsgTransactionNotFound(transactionID) err := flow.outgoingRoute.Enqueue(msgTransactionNotFound) if err != nil { return err @@ -49,11 +49,11 @@ func (flow *handleRequestedTransactionsFlow) start() error { } } -func (flow *handleRequestedTransactionsFlow) readRequestTransactions() (*wire.MsgRequestTransactions, error) { +func (flow *handleRequestedTransactionsFlow) readRequestTransactions() (*domainmessage.MsgRequestTransactions, error) { msg, err := flow.incomingRoute.Dequeue() if err != nil { return nil, err } - return msg.(*wire.MsgRequestTransactions), nil + return msg.(*domainmessage.MsgRequestTransactions), nil } diff --git a/protocol/peer/peer.go b/protocol/peer/peer.go index 3c3f41564..66d63874d 100644 --- a/protocol/peer/peer.go +++ b/protocol/peer/peer.go @@ -6,12 +6,12 @@ import ( "sync/atomic" "time" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/netadapter/id" "github.com/kaspanet/kaspad/util/daghash" mathUtil "github.com/kaspanet/kaspad/util/math" "github.com/kaspanet/kaspad/util/mstime" "github.com/kaspanet/kaspad/util/subnetworkid" - "github.com/kaspanet/kaspad/wire" ) // Peer holds data about a peer. @@ -22,7 +22,7 @@ type Peer struct { selectedTipHash *daghash.Hash userAgent string - services wire.ServiceFlag + services domainmessage.ServiceFlag advertisedProtocolVerion uint32 // protocol version advertised by remote protocolVersion uint32 // negotiated protocol version disableRelayTx bool @@ -109,7 +109,7 @@ func (p *Peer) IsOutbound() bool { } // UpdateFieldsFromMsgVersion updates the peer with the data from the version message. -func (p *Peer) UpdateFieldsFromMsgVersion(msg *wire.MsgVersion) { +func (p *Peer) UpdateFieldsFromMsgVersion(msg *domainmessage.MsgVersion) { // Negotiate the protocol version. p.advertisedProtocolVerion = msg.ProtocolVersion p.protocolVersion = mathUtil.MinUint32(p.protocolVersion, p.advertisedProtocolVerion) diff --git a/protocol/protocol.go b/protocol/protocol.go index 20542c73f..45923f55b 100644 --- a/protocol/protocol.go +++ b/protocol/protocol.go @@ -4,6 +4,7 @@ import ( "sync/atomic" "github.com/kaspanet/kaspad/addressmanager" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/netadapter" routerpkg "github.com/kaspanet/kaspad/netadapter/router" "github.com/kaspanet/kaspad/protocol/flows/addressexchange" @@ -15,7 +16,6 @@ import ( "github.com/kaspanet/kaspad/protocol/flows/relaytransactions" peerpkg "github.com/kaspanet/kaspad/protocol/peer" "github.com/kaspanet/kaspad/protocol/protocolerrors" - "github.com/kaspanet/kaspad/wire" "github.com/pkg/errors" ) @@ -109,13 +109,13 @@ func (m *Manager) registerAddressFlows(router *routerpkg.Router, isStopping *uin outgoingRoute := router.OutgoingRoute() return []*flow{ - m.registerOneTimeFlow("SendAddresses", router, []wire.MessageCommand{wire.CmdRequestAddresses}, isStopping, errChan, + m.registerOneTimeFlow("SendAddresses", router, []domainmessage.MessageCommand{domainmessage.CmdRequestAddresses}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return addressexchange.SendAddresses(m.context, incomingRoute, outgoingRoute) }, ), - m.registerOneTimeFlow("ReceiveAddresses", router, []wire.MessageCommand{wire.CmdAddresses}, isStopping, errChan, + m.registerOneTimeFlow("ReceiveAddresses", router, []domainmessage.MessageCommand{domainmessage.CmdAddresses}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return addressexchange.ReceiveAddresses(m.context, incomingRoute, outgoingRoute, peer) }, @@ -127,14 +127,14 @@ func (m *Manager) registerBlockRelayFlows(router *routerpkg.Router, isStopping * outgoingRoute := router.OutgoingRoute() return []*flow{ - m.registerFlow("HandleRelayInvs", router, []wire.MessageCommand{wire.CmdInvRelayBlock, wire.CmdBlock}, isStopping, errChan, + m.registerFlow("HandleRelayInvs", router, []domainmessage.MessageCommand{domainmessage.CmdInvRelayBlock, domainmessage.CmdBlock}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return blockrelay.HandleRelayInvs(m.context, incomingRoute, outgoingRoute, peer) }, ), - m.registerFlow("HandleRelayBlockRequests", router, []wire.MessageCommand{wire.CmdRequestRelayBlocks}, isStopping, errChan, + m.registerFlow("HandleRelayBlockRequests", router, []domainmessage.MessageCommand{domainmessage.CmdRequestRelayBlocks}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return blockrelay.HandleRelayBlockRequests(m.context, incomingRoute, outgoingRoute, peer) }, @@ -146,13 +146,13 @@ func (m *Manager) registerPingFlows(router *routerpkg.Router, isStopping *uint32 outgoingRoute := router.OutgoingRoute() return []*flow{ - m.registerFlow("ReceivePings", router, []wire.MessageCommand{wire.CmdPing}, isStopping, errChan, + m.registerFlow("ReceivePings", router, []domainmessage.MessageCommand{domainmessage.CmdPing}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return ping.ReceivePings(m.context, incomingRoute, outgoingRoute) }, ), - m.registerFlow("SendPings", router, []wire.MessageCommand{wire.CmdPong}, isStopping, errChan, + m.registerFlow("SendPings", router, []domainmessage.MessageCommand{domainmessage.CmdPong}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return ping.SendPings(m.context, incomingRoute, outgoingRoute, peer) }, @@ -164,32 +164,32 @@ func (m *Manager) registerIBDFlows(router *routerpkg.Router, isStopping *uint32, outgoingRoute := router.OutgoingRoute() return []*flow{ - m.registerFlow("HandleIBD", router, []wire.MessageCommand{wire.CmdBlockLocator, wire.CmdIBDBlock, - wire.CmdDoneIBDBlocks}, isStopping, errChan, + m.registerFlow("HandleIBD", router, []domainmessage.MessageCommand{domainmessage.CmdBlockLocator, domainmessage.CmdIBDBlock, + domainmessage.CmdDoneIBDBlocks}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return ibd.HandleIBD(m.context, incomingRoute, outgoingRoute, peer) }, ), - m.registerFlow("RequestSelectedTip", router, []wire.MessageCommand{wire.CmdSelectedTip}, isStopping, errChan, + m.registerFlow("RequestSelectedTip", router, []domainmessage.MessageCommand{domainmessage.CmdSelectedTip}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return selectedtip.RequestSelectedTip(m.context, incomingRoute, outgoingRoute, peer) }, ), - m.registerFlow("HandleRequestSelectedTip", router, []wire.MessageCommand{wire.CmdRequestSelectedTip}, isStopping, errChan, + m.registerFlow("HandleRequestSelectedTip", router, []domainmessage.MessageCommand{domainmessage.CmdRequestSelectedTip}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return selectedtip.HandleRequestSelectedTip(m.context, incomingRoute, outgoingRoute) }, ), - m.registerFlow("HandleRequestBlockLocator", router, []wire.MessageCommand{wire.CmdRequestBlockLocator}, isStopping, errChan, + m.registerFlow("HandleRequestBlockLocator", router, []domainmessage.MessageCommand{domainmessage.CmdRequestBlockLocator}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return ibd.HandleRequestBlockLocator(m.context, incomingRoute, outgoingRoute) }, ), - m.registerFlow("HandleRequestIBDBlocks", router, []wire.MessageCommand{wire.CmdRequestIBDBlocks, wire.CmdRequestNextIBDBlocks}, isStopping, errChan, + m.registerFlow("HandleRequestIBDBlocks", router, []domainmessage.MessageCommand{domainmessage.CmdRequestIBDBlocks, domainmessage.CmdRequestNextIBDBlocks}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return ibd.HandleRequestIBDBlocks(m.context, incomingRoute, outgoingRoute) }, @@ -202,13 +202,13 @@ func (m *Manager) registerTransactionRelayFlow(router *routerpkg.Router, isStopp return []*flow{ m.registerFlow("HandleRelayedTransactions", router, - []wire.MessageCommand{wire.CmdInvTransaction, wire.CmdTx, wire.CmdTransactionNotFound}, isStopping, errChan, + []domainmessage.MessageCommand{domainmessage.CmdInvTransaction, domainmessage.CmdTx, domainmessage.CmdTransactionNotFound}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return relaytransactions.HandleRelayedTransactions(m.context, incomingRoute, outgoingRoute) }, ), m.registerFlow("HandleRequestTransactions", router, - []wire.MessageCommand{wire.CmdRequestTransactions}, isStopping, errChan, + []domainmessage.MessageCommand{domainmessage.CmdRequestTransactions}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return relaytransactions.HandleRequestedTransactions(m.context, incomingRoute, outgoingRoute) }, @@ -216,7 +216,7 @@ func (m *Manager) registerTransactionRelayFlow(router *routerpkg.Router, isStopp } } -func (m *Manager) registerFlow(name string, router *routerpkg.Router, messageTypes []wire.MessageCommand, isStopping *uint32, +func (m *Manager) registerFlow(name string, router *routerpkg.Router, messageTypes []domainmessage.MessageCommand, isStopping *uint32, errChan chan error, initializeFunc flowInitializeFunc) *flow { route, err := router.AddIncomingRoute(messageTypes) @@ -236,7 +236,7 @@ func (m *Manager) registerFlow(name string, router *routerpkg.Router, messageTyp } } -func (m *Manager) registerOneTimeFlow(name string, router *routerpkg.Router, messageTypes []wire.MessageCommand, +func (m *Manager) registerOneTimeFlow(name string, router *routerpkg.Router, messageTypes []domainmessage.MessageCommand, isStopping *uint32, stopChan chan error, initializeFunc flowInitializeFunc) *flow { route, err := router.AddIncomingRoute(messageTypes) @@ -265,12 +265,12 @@ func (m *Manager) registerOneTimeFlow(name string, router *routerpkg.Router, mes func registerHandshakeRoutes(router *routerpkg.Router) ( receiveVersionRoute *routerpkg.Route, sendVersionRoute *routerpkg.Route) { - receiveVersionRoute, err := router.AddIncomingRoute([]wire.MessageCommand{wire.CmdVersion}) + receiveVersionRoute, err := router.AddIncomingRoute([]domainmessage.MessageCommand{domainmessage.CmdVersion}) if err != nil { panic(err) } - sendVersionRoute, err = router.AddIncomingRoute([]wire.MessageCommand{wire.CmdVerAck}) + sendVersionRoute, err = router.AddIncomingRoute([]domainmessage.MessageCommand{domainmessage.CmdVerAck}) if err != nil { panic(err) } @@ -279,7 +279,7 @@ func registerHandshakeRoutes(router *routerpkg.Router) ( } func removeHandshakeRoutes(router *routerpkg.Router) { - err := router.RemoveRoute([]wire.MessageCommand{wire.CmdVersion, wire.CmdVerAck}) + err := router.RemoveRoute([]domainmessage.MessageCommand{domainmessage.CmdVersion, domainmessage.CmdVerAck}) if err != nil { panic(err) } diff --git a/rpc/client/dag.go b/rpc/client/dag.go index 32d09858d..72e2ff67d 100644 --- a/rpc/client/dag.go +++ b/rpc/client/dag.go @@ -13,9 +13,9 @@ import ( "github.com/pkg/errors" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/rpc/model" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) // FutureGetSelectedTipHashResult is a future promise to deliver the result of a @@ -61,7 +61,7 @@ type FutureGetBlockResult chan *response // Receive waits for the response promised by the future and returns the raw // block requested from the server given its hash. -func (r FutureGetBlockResult) Receive() (*wire.MsgBlock, error) { +func (r FutureGetBlockResult) Receive() (*domainmessage.MsgBlock, error) { res, err := receiveFuture(r) if err != nil { return nil, err @@ -81,7 +81,7 @@ func (r FutureGetBlockResult) Receive() (*wire.MsgBlock, error) { } // Deserialize the block and return it. - var msgBlock wire.MsgBlock + var msgBlock domainmessage.MsgBlock err = msgBlock.Deserialize(bytes.NewReader(serializedBlock)) if err != nil { return nil, err @@ -108,7 +108,7 @@ func (c *Client) GetBlockAsync(blockHash *daghash.Hash, subnetworkID *string) Fu // // See GetBlockVerbose to retrieve a data structure with information about the // block instead. -func (c *Client) GetBlock(blockHash *daghash.Hash, subnetworkID *string) (*wire.MsgBlock, error) { +func (c *Client) GetBlock(blockHash *daghash.Hash, subnetworkID *string) (*domainmessage.MsgBlock, error) { return c.GetBlockAsync(blockHash, subnetworkID).Receive() } @@ -391,7 +391,7 @@ type FutureGetBlockHeaderResult chan *response // Receive waits for the response promised by the future and returns the // blockheader requested from the server given its hash. -func (r FutureGetBlockHeaderResult) Receive() (*wire.BlockHeader, error) { +func (r FutureGetBlockHeaderResult) Receive() (*domainmessage.BlockHeader, error) { res, err := receiveFuture(r) if err != nil { return nil, err @@ -410,7 +410,7 @@ func (r FutureGetBlockHeaderResult) Receive() (*wire.BlockHeader, error) { } // Deserialize the blockheader and return it. - var bh wire.BlockHeader + var bh domainmessage.BlockHeader err = bh.Deserialize(bytes.NewReader(serializedBH)) if err != nil { return nil, err @@ -438,7 +438,7 @@ func (c *Client) GetBlockHeaderAsync(blockHash *daghash.Hash) FutureGetBlockHead // // See GetBlockHeaderVerbose to retrieve a data structure with information about the // block instead. -func (c *Client) GetBlockHeader(blockHash *daghash.Hash) (*wire.BlockHeader, error) { +func (c *Client) GetBlockHeader(blockHash *daghash.Hash) (*domainmessage.BlockHeader, error) { return c.GetBlockHeaderAsync(blockHash).Receive() } diff --git a/rpc/client/examples/websockets/main.go b/rpc/client/examples/websockets/main.go index 1dcd30251..6b225bb77 100644 --- a/rpc/client/examples/websockets/main.go +++ b/rpc/client/examples/websockets/main.go @@ -10,9 +10,9 @@ import ( "path/filepath" "time" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/rpc/client" "github.com/kaspanet/kaspad/util" - "github.com/kaspanet/kaspad/wire" ) func main() { @@ -21,7 +21,7 @@ func main() { // for notifications. See the documentation of the rpcclient // NotificationHandlers type for more details about each handler. ntfnHandlers := client.NotificationHandlers{ - OnFilteredBlockAdded: func(blueScore uint64, header *wire.BlockHeader, txns []*util.Tx) { + OnFilteredBlockAdded: func(blueScore uint64, header *domainmessage.BlockHeader, txns []*util.Tx) { log.Printf("Block added: %s (%d) %s", header.BlockHash(), blueScore, header.Timestamp) }, diff --git a/rpc/client/infrastructure.go b/rpc/client/infrastructure.go index c5b8b7e3a..a23a7058e 100644 --- a/rpc/client/infrastructure.go +++ b/rpc/client/infrastructure.go @@ -1086,7 +1086,7 @@ type ConnConfig struct { // DisableTLS specifies whether transport layer security should be // disabled. It is recommended to always use TLS if the RPC server // supports it as otherwise your username and password is sent across - // the wire in cleartext. + // the domainmessage in cleartext. DisableTLS bool // Certificates are the bytes for a PEM-encoded certificate chain used diff --git a/rpc/client/mining.go b/rpc/client/mining.go index a063875aa..793cab76d 100644 --- a/rpc/client/mining.go +++ b/rpc/client/mining.go @@ -10,10 +10,10 @@ import ( "strconv" "strings" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/rpc/model" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" "github.com/pkg/errors" ) @@ -141,13 +141,13 @@ func ConvertGetBlockTemplateResultToBlock(template *model.GetBlockTemplateResult return nil, errors.Wrapf(err, "error parsing utxoCommitment '%s'", template.UTXOCommitment) } // parse rest of block - msgBlock := wire.NewMsgBlock( - wire.NewBlockHeader(template.Version, parentHashes, hashMerkleRoot, + msgBlock := domainmessage.NewMsgBlock( + domainmessage.NewBlockHeader(template.Version, parentHashes, hashMerkleRoot, acceptedIDMerkleRoot, utxoCommitment, bits, 0)) for i, txResult := range template.Transactions { reader := hex.NewDecoder(strings.NewReader(txResult.Data)) - tx := &wire.MsgTx{} + tx := &domainmessage.MsgTx{} if err := tx.KaspaDecode(reader, 0); err != nil { return nil, errors.Wrapf(err, "error decoding tx #%d", i) } diff --git a/rpc/client/net.go b/rpc/client/net.go index 9f5ffad5c..52544b81d 100644 --- a/rpc/client/net.go +++ b/rpc/client/net.go @@ -9,9 +9,9 @@ import ( "encoding/hex" "encoding/json" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/pointers" - "github.com/kaspanet/kaspad/wire" "github.com/kaspanet/kaspad/rpc/model" ) @@ -273,7 +273,7 @@ type FutureGetSelectedTipResult chan *response // Receive waits for the response promised by the future and returns the // selected tip block. -func (r FutureGetSelectedTipResult) Receive() (*wire.MsgBlock, error) { +func (r FutureGetSelectedTipResult) Receive() (*domainmessage.MsgBlock, error) { res, err := receiveFuture(r) if err != nil { return nil, err @@ -293,7 +293,7 @@ func (r FutureGetSelectedTipResult) Receive() (*wire.MsgBlock, error) { } // Deserialize the block and return it. - var msgBlock wire.MsgBlock + var msgBlock domainmessage.MsgBlock err = msgBlock.Deserialize(bytes.NewReader(serializedBlock)) if err != nil { return nil, err @@ -353,7 +353,7 @@ type FutureGetCurrentNetResult chan *response // Receive waits for the response promised by the future and returns the network // the server is running on. -func (r FutureGetCurrentNetResult) Receive() (wire.KaspaNet, error) { +func (r FutureGetCurrentNetResult) Receive() (domainmessage.KaspaNet, error) { res, err := receiveFuture(r) if err != nil { return 0, err @@ -366,7 +366,7 @@ func (r FutureGetCurrentNetResult) Receive() (wire.KaspaNet, error) { return 0, err } - return wire.KaspaNet(net), nil + return domainmessage.KaspaNet(net), nil } // GetCurrentNetAsync returns an instance of a type that can be used to get the @@ -380,7 +380,7 @@ func (c *Client) GetCurrentNetAsync() FutureGetCurrentNetResult { } // GetCurrentNet returns the network the server is running on. -func (c *Client) GetCurrentNet() (wire.KaspaNet, error) { +func (c *Client) GetCurrentNet() (domainmessage.KaspaNet, error) { return c.GetCurrentNetAsync().Receive() } @@ -390,7 +390,7 @@ type FutureGetHeadersResult chan *response // Receive waits for the response promised by the future and returns the // getheaders result. -func (r FutureGetHeadersResult) Receive() ([]wire.BlockHeader, error) { +func (r FutureGetHeadersResult) Receive() ([]domainmessage.BlockHeader, error) { res, err := receiveFuture(r) if err != nil { return nil, err @@ -403,8 +403,8 @@ func (r FutureGetHeadersResult) Receive() ([]wire.BlockHeader, error) { return nil, err } - // Deserialize the []string into []wire.BlockHeader. - headers := make([]wire.BlockHeader, len(result)) + // Deserialize the []string into []domainmessage.BlockHeader. + headers := make([]domainmessage.BlockHeader, len(result)) for i, headerHex := range result { serialized, err := hex.DecodeString(headerHex) if err != nil { @@ -432,7 +432,7 @@ func (c *Client) GetTopHeadersAsync(highHash *daghash.Hash) FutureGetHeadersResu } // GetTopHeaders sends a getTopHeaders rpc command to the server. -func (c *Client) GetTopHeaders(highHash *daghash.Hash) ([]wire.BlockHeader, error) { +func (c *Client) GetTopHeaders(highHash *daghash.Hash) ([]domainmessage.BlockHeader, error) { return c.GetTopHeadersAsync(highHash).Receive() } @@ -453,10 +453,10 @@ func (c *Client) GetHeadersAsync(lowHash, highHash *daghash.Hash) FutureGetHeade return c.sendCmd(cmd) } -// GetHeaders mimics the wire protocol getheaders and headers messages by +// GetHeaders mimics the domainmessage protocol getheaders and headers messages by // returning all headers in the DAG after the first known block in the // locators, up until a block hash matches highHash. -func (c *Client) GetHeaders(lowHash, highHash *daghash.Hash) ([]wire.BlockHeader, error) { +func (c *Client) GetHeaders(lowHash, highHash *daghash.Hash) ([]domainmessage.BlockHeader, error) { return c.GetHeadersAsync(lowHash, highHash).Receive() } diff --git a/rpc/client/notify.go b/rpc/client/notify.go index bc483cf51..aa86b5698 100644 --- a/rpc/client/notify.go +++ b/rpc/client/notify.go @@ -13,10 +13,10 @@ import ( "github.com/kaspanet/kaspad/util/mstime" "github.com/pkg/errors" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/rpc/model" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) var ( @@ -88,7 +88,7 @@ type NotificationHandlers struct { // NotifyBlocks has been made to register for the notification and the // function is non-nil. Its parameters differ from OnBlockAdded: it // receives the block's blueScore, header, and relevant transactions. - OnFilteredBlockAdded func(blueScore uint64, header *wire.BlockHeader, + OnFilteredBlockAdded func(blueScore uint64, header *domainmessage.BlockHeader, txs []*util.Tx) // OnChainChanged is invoked when the selected parent chain of the @@ -316,7 +316,7 @@ func parseChainChangedParams(params []json.RawMessage) (removedChainBlockHashes // parseFilteredBlockAddedParams parses out the parameters included in a // filteredblockadded notification. func parseFilteredBlockAddedParams(params []json.RawMessage) (uint64, - *wire.BlockHeader, []*util.Tx, error) { + *domainmessage.BlockHeader, []*util.Tx, error) { if len(params) < 3 { return 0, nil, nil, wrongNumParams(len(params)) @@ -336,7 +336,7 @@ func parseFilteredBlockAddedParams(params []json.RawMessage) (uint64, } // Deserialize block header from slice of bytes. - var blockHeader wire.BlockHeader + var blockHeader domainmessage.BlockHeader err = blockHeader.Deserialize(bytes.NewReader(blockHeaderBytes)) if err != nil { return 0, nil, nil, err @@ -593,7 +593,7 @@ func (r FutureLoadTxFilterResult) Receive() error { // // See LoadTxFilter for the blocking version and more details. func (c *Client) LoadTxFilterAsync(reload bool, addresses []util.Address, - outpoints []wire.Outpoint) FutureLoadTxFilterResult { + outpoints []domainmessage.Outpoint) FutureLoadTxFilterResult { addrStrs := make([]string, len(addresses)) for i, a := range addresses { @@ -614,6 +614,6 @@ func (c *Client) LoadTxFilterAsync(reload bool, addresses []util.Address, // LoadTxFilter loads, reloads, or adds data to a websocket client's transaction // filter. The filter is consistently updated based on inspected transactions // during mempool acceptance, block acceptance, and for all rescanned blocks. -func (c *Client) LoadTxFilter(reload bool, addresses []util.Address, outpoints []wire.Outpoint) error { +func (c *Client) LoadTxFilter(reload bool, addresses []util.Address, outpoints []domainmessage.Outpoint) error { return c.LoadTxFilterAsync(reload, addresses, outpoints).Receive() } diff --git a/rpc/client/rawtransactions.go b/rpc/client/rawtransactions.go index 0ceaef015..e3e407964 100644 --- a/rpc/client/rawtransactions.go +++ b/rpc/client/rawtransactions.go @@ -8,9 +8,9 @@ import ( "bytes" "encoding/hex" "encoding/json" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/rpc/model" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) // FutureSendRawTransactionResult is a future promise to deliver the result @@ -41,7 +41,7 @@ func (r FutureSendRawTransactionResult) Receive() (*daghash.TxID, error) { // the returned instance. // // See SendRawTransaction for the blocking version and more details. -func (c *Client) SendRawTransactionAsync(tx *wire.MsgTx, allowHighFees bool) FutureSendRawTransactionResult { +func (c *Client) SendRawTransactionAsync(tx *domainmessage.MsgTx, allowHighFees bool) FutureSendRawTransactionResult { txHex := "" if tx != nil { // Serialize the transaction and convert to hex string. @@ -58,6 +58,6 @@ func (c *Client) SendRawTransactionAsync(tx *wire.MsgTx, allowHighFees bool) Fut // SendRawTransaction submits the encoded transaction to the server which will // then relay it to the network. -func (c *Client) SendRawTransaction(tx *wire.MsgTx, allowHighFees bool) (*daghash.TxID, error) { +func (c *Client) SendRawTransaction(tx *domainmessage.MsgTx, allowHighFees bool) (*daghash.TxID, error) { return c.SendRawTransactionAsync(tx, allowHighFees).Receive() } diff --git a/rpc/common.go b/rpc/common.go index 9f7113dc4..48f8115e6 100644 --- a/rpc/common.go +++ b/rpc/common.go @@ -5,12 +5,12 @@ import ( "encoding/hex" "fmt" "github.com/kaspanet/kaspad/dagconfig" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/rpc/model" "github.com/kaspanet/kaspad/txscript" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/pointers" - "github.com/kaspanet/kaspad/wire" "math/big" "strconv" ) @@ -55,9 +55,9 @@ func rpcNoTxInfoError(txID *daghash.TxID) *model.RPCError { txID)) } -// msgTxToHex serializes a transaction to the wire protocol encoding using the -// latest protocol version and returns a hex-encoded string of the result. -func msgTxToHex(msgTx *wire.MsgTx) (string, error) { +// msgTxToHex serializes a transaction using the latest protocol version and +// returns a hex-encoded string of the result. +func msgTxToHex(msgTx *domainmessage.MsgTx) (string, error) { var buf bytes.Buffer if err := msgTx.KaspaEncode(&buf, maxProtocolVersion); err != nil { context := fmt.Sprintf("Failed to encode msg of type %T", msgTx) @@ -69,7 +69,7 @@ func msgTxToHex(msgTx *wire.MsgTx) (string, error) { // createVinList returns a slice of JSON objects for the inputs of the passed // transaction. -func createVinList(mtx *wire.MsgTx) []model.Vin { +func createVinList(mtx *domainmessage.MsgTx) []model.Vin { vinList := make([]model.Vin, len(mtx.TxIn)) for i, txIn := range mtx.TxIn { // The disassembled string will contain [error] inline @@ -92,7 +92,7 @@ func createVinList(mtx *wire.MsgTx) []model.Vin { // createVoutList returns a slice of JSON objects for the outputs of the passed // transaction. -func createVoutList(mtx *wire.MsgTx, dagParams *dagconfig.Params, filterAddrMap map[string]struct{}) []model.Vout { +func createVoutList(mtx *domainmessage.MsgTx, dagParams *dagconfig.Params, filterAddrMap map[string]struct{}) []model.Vout { voutList := make([]model.Vout, 0, len(mtx.TxOut)) for i, v := range mtx.TxOut { // The disassembled string will contain [error] inline if the @@ -139,8 +139,8 @@ func createVoutList(mtx *wire.MsgTx, dagParams *dagconfig.Params, filterAddrMap // createTxRawResult converts the passed transaction and associated parameters // to a raw transaction JSON object. -func createTxRawResult(dagParams *dagconfig.Params, mtx *wire.MsgTx, - txID string, blkHeader *wire.BlockHeader, blkHash string, +func createTxRawResult(dagParams *dagconfig.Params, mtx *domainmessage.MsgTx, + txID string, blkHeader *domainmessage.BlockHeader, blkHash string, acceptingBlock *daghash.Hash, isInMempool bool) (*model.TxRawResult, error) { mtxHex, err := msgTxToHex(mtx) diff --git a/rpc/handle_get_block_template.go b/rpc/handle_get_block_template.go index 43ec6e4fd..51b5240c1 100644 --- a/rpc/handle_get_block_template.go +++ b/rpc/handle_get_block_template.go @@ -12,13 +12,13 @@ import ( "github.com/kaspanet/kaspad/util/mstime" "github.com/kaspanet/kaspad/blockdag" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/mining" "github.com/kaspanet/kaspad/rpc/model" "github.com/kaspanet/kaspad/txscript" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/random" - "github.com/kaspanet/kaspad/wire" "github.com/pkg/errors" ) @@ -285,7 +285,7 @@ func handleGetBlockTemplateProposal(s *Server, request *model.TemplateRequest) ( "hexadecimal string (not %q)", hexData), } } - var msgBlock wire.MsgBlock + var msgBlock domainmessage.MsgBlock if err := msgBlock.Deserialize(bytes.NewReader(dataBytes)); err != nil { return nil, &model.RPCError{ Code: model.ErrRPCDeserialization, @@ -534,7 +534,7 @@ func (state *gbtWorkState) updateBlockTemplate(s *Server, payAddr util.Address) // changed or the transactions in the memory pool have been updated and // it has been at least gbtRegenerateSecond since the last template was // generated. - var msgBlock *wire.MsgBlock + var msgBlock *domainmessage.MsgBlock var targetDifficulty string tipHashes := s.dag.TipHashes() template := state.template @@ -711,7 +711,7 @@ func (state *gbtWorkState) blockTemplateResult(s *Server) (*model.GetBlockTempla CurTime: header.Timestamp.UnixMilliseconds(), Height: template.Height, ParentHashes: daghash.Strings(header.ParentHashes), - MassLimit: wire.MaxMassPerBlock, + MassLimit: domainmessage.MaxMassPerBlock, Transactions: transactions, HashMerkleRoot: header.HashMerkleRoot.String(), AcceptedIDMerkleRoot: header.AcceptedIDMerkleRoot.String(), diff --git a/rpc/handle_get_tx_out.go b/rpc/handle_get_tx_out.go index e5ee96121..29b560fdb 100644 --- a/rpc/handle_get_tx_out.go +++ b/rpc/handle_get_tx_out.go @@ -4,12 +4,12 @@ import ( "encoding/hex" "fmt" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/rpc/model" "github.com/kaspanet/kaspad/txscript" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/pointers" - "github.com/kaspanet/kaspad/wire" ) // handleGetTxOut handles getTxOut commands. @@ -64,7 +64,7 @@ func handleGetTxOut(s *Server, cmd interface{}, closeChan <-chan struct{}) (inte isCoinbase = mtx.IsCoinBase() isInMempool = true } else { - out := wire.Outpoint{TxID: *txID, Index: c.Vout} + out := domainmessage.Outpoint{TxID: *txID, Index: c.Vout} entry, ok := s.dag.GetUTXOEntry(out) if !ok { return nil, rpcNoTxInfoError(txID) diff --git a/rpc/handle_load_tx_filter.go b/rpc/handle_load_tx_filter.go index 6eae3276f..ae711e3c4 100644 --- a/rpc/handle_load_tx_filter.go +++ b/rpc/handle_load_tx_filter.go @@ -1,9 +1,9 @@ package rpc import ( + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/rpc/model" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) // handleLoadTxFilter implements the loadTxFilter command extension for @@ -13,7 +13,7 @@ import ( func handleLoadTxFilter(wsc *wsClient, icmd interface{}) (interface{}, error) { cmd := icmd.(*model.LoadTxFilterCmd) - outpoints := make([]wire.Outpoint, len(cmd.Outpoints)) + outpoints := make([]domainmessage.Outpoint, len(cmd.Outpoints)) for i := range cmd.Outpoints { txID, err := daghash.NewTxIDFromStr(cmd.Outpoints[i].TxID) if err != nil { @@ -22,7 +22,7 @@ func handleLoadTxFilter(wsc *wsClient, icmd interface{}) (interface{}, error) { Message: err.Error(), } } - outpoints[i] = wire.Outpoint{ + outpoints[i] = domainmessage.Outpoint{ TxID: *txID, Index: cmd.Outpoints[i].Index, } diff --git a/rpc/handle_rescan_block_filter.go b/rpc/handle_rescan_block_filter.go index 1a86b46bc..f093bf4ee 100644 --- a/rpc/handle_rescan_block_filter.go +++ b/rpc/handle_rescan_block_filter.go @@ -2,9 +2,9 @@ package rpc import ( "github.com/kaspanet/kaspad/dagconfig" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/txscript" "github.com/kaspanet/kaspad/util" - "github.com/kaspanet/kaspad/wire" ) // rescanBlockFilter rescans a block for any relevant transactions for the @@ -51,7 +51,7 @@ func rescanBlockFilter(filter *wsClientFilter, block *util.Block, params *dagcon continue } - op := wire.Outpoint{ + op := domainmessage.Outpoint{ TxID: *tx.ID(), Index: uint32(i), } diff --git a/rpc/handle_send_raw_transaction.go b/rpc/handle_send_raw_transaction.go index 9d2a389c7..0c250a29f 100644 --- a/rpc/handle_send_raw_transaction.go +++ b/rpc/handle_send_raw_transaction.go @@ -3,10 +3,10 @@ package rpc import ( "bytes" "encoding/hex" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/mempool" "github.com/kaspanet/kaspad/rpc/model" "github.com/kaspanet/kaspad/util" - "github.com/kaspanet/kaspad/wire" "github.com/pkg/errors" ) @@ -19,7 +19,7 @@ func handleSendRawTransaction(s *Server, cmd interface{}, closeChan <-chan struc if err != nil { return nil, rpcDecodeHexError(hexStr) } - var msgTx wire.MsgTx + var msgTx domainmessage.MsgTx err = msgTx.Deserialize(bytes.NewReader(serializedTx)) if err != nil { return nil, &model.RPCError{ diff --git a/rpc/model/doc.go b/rpc/model/doc.go index f0a7d877f..3408992a4 100644 --- a/rpc/model/doc.go +++ b/rpc/model/doc.go @@ -4,7 +4,7 @@ Package model provides primitives for working with the kaspa JSON-RPC API. Overview When communicating via the JSON-RPC protocol, all of the commands need to be -marshalled to and from the the wire in the appropriate format. This package +marshalled to and from the the domainmessage in the appropriate format. This package provides data structures and primitives to ease this process. In addition, it also provides some additional features such as custom command @@ -17,7 +17,7 @@ provide some intuition into what the marshalling and unmarshalling that is discussed below is doing under the hood. As defined by the JSON-RPC spec, there are effectively two forms of messages on -the wire: +the domainmessage: - Request Objects {"jsonrpc":"1.0","id":"SOMEID","method":"SOMEMETHOD","params":[SOMEPARAMS]} @@ -51,7 +51,7 @@ package map into the required parts of the protocol To simplify the marshalling of the requests and responses, the MarshalCommand and MarshalResponse functions are provided. They return the raw bytes ready to be -sent across the wire. +sent across the domainmessage. Unmarshalling a received Request object is a two step process: 1) Unmarshal the raw bytes into a Request struct instance via json.Unmarshal @@ -119,7 +119,7 @@ There are 2 distinct type of errors supported by this package: - General errors related to marshalling or unmarshalling or improper use of the package (type Error) - - RPC errors which are intended to be returned across the wire as a part of + - RPC errors which are intended to be returned across the domainmessage as a part of the JSON-RPC response (type RPCError) The first category of errors (type Error) typically indicates a programmer error diff --git a/rpc/model/error.go b/rpc/model/error.go index 0d9eb9f49..40240cc7c 100644 --- a/rpc/model/error.go +++ b/rpc/model/error.go @@ -92,7 +92,7 @@ func (e ErrorCode) String() string { // Error identifies a general error. This differs from an RPCError in that this // error typically is used more by the consumers of the package as opposed to -// RPCErrors which are intended to be returned to the client across the wire via +// RPCErrors which are intended to be returned to the client across the domainmessage via // a JSON-RPC Response. The caller can use type assertions to determine the // specific error and access the ErrorCode field. type Error struct { diff --git a/rpc/model/example_test.go b/rpc/model/example_test.go index 6b23fc1ec..02fe3759f 100644 --- a/rpc/model/example_test.go +++ b/rpc/model/example_test.go @@ -35,7 +35,7 @@ func ExampleMarshalCommand() { } // Display the marshalled command. Ordinarily this would be sent across - // the wire to the RPC server, but for this example, just display it. + // the domainmessage to the RPC server, but for this example, just display it. fmt.Printf("%s\n", marshalledBytes) // Output: @@ -45,11 +45,11 @@ func ExampleMarshalCommand() { // This example demonstrates how to unmarshal a JSON-RPC request and then // unmarshal the concrete request into a concrete command. func ExampleUnmarshalCommand() { - // Ordinarily this would be read from the wire, but for this example, + // Ordinarily this would be read from the domainmessage, but for this example, // it is hard coded here for clarity. data := []byte(`{"jsonrpc":"1.0","method":"getBlock","params":["000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f",false],"id":1}`) - // Unmarshal the raw bytes from the wire into a JSON-RPC request. + // Unmarshal the raw bytes from the domainmessage into a JSON-RPC request. var request model.Request if err := json.Unmarshal(data, &request); err != nil { fmt.Println(err) @@ -108,7 +108,7 @@ func ExampleMarshalResponse() { } // Display the marshalled response. Ordinarily this would be sent - // across the wire to the RPC client, but for this example, just display + // across the domainmessage to the RPC client, but for this example, just display // it. fmt.Printf("%s\n", marshalledBytes) @@ -119,12 +119,12 @@ func ExampleMarshalResponse() { // This example demonstrates how to unmarshal a JSON-RPC response and then // unmarshal the result field in the response to a concrete type. func Example_unmarshalResponse() { - // Ordinarily this would be read from the wire, but for this example, + // Ordinarily this would be read from the domainmessage, but for this example, // it is hard coded here for clarity. This is an example response to a // getblockheight request. data := []byte(`{"result":350001,"error":null,"id":1}`) - // Unmarshal the raw bytes from the wire into a JSON-RPC response. + // Unmarshal the raw bytes from the domainmessage into a JSON-RPC response. var response model.Response if err := json.Unmarshal(data, &response); err != nil { fmt.Println("Malformed JSON-RPC response:", err) diff --git a/rpc/model/jsonrpc.go b/rpc/model/jsonrpc.go index 6c3e964f1..07600fd7f 100644 --- a/rpc/model/jsonrpc.go +++ b/rpc/model/jsonrpc.go @@ -120,7 +120,7 @@ type Response struct { // caller wants to construct raw responses for some reason. // // Typically callers will instead want to create the fully marshalled JSON-RPC -// response to send over the wire with the MarshalResponse function. +// response to send over the domainmessage with the MarshalResponse function. func NewResponse(id interface{}, marshalledResult []byte, rpcErr *RPCError) (*Response, error) { if !IsValidIDType(id) { str := fmt.Sprintf("the id of type '%T' is invalid", id) diff --git a/rpc/rpcserverhelp.go b/rpc/rpcserverhelp.go index 5f9bf2446..eef01a306 100644 --- a/rpc/rpcserverhelp.go +++ b/rpc/rpcserverhelp.go @@ -330,13 +330,13 @@ var helpDescsEnUS = map[string]string{ // GetTopHeadersCmd help. "getTopHeaders--synopsis": "Returns the top block headers starting with the provided high hash (not inclusive)", "getTopHeaders-highHash": "Block hash to start including block headers from; if not found, it'll start from the virtual.", - "getTopHeaders--result0": "Serialized block headers of all located blocks, limited to some arbitrary maximum number of hashes (currently 2000, which matches the wire protocol headers message, but this is not guaranteed)", + "getTopHeaders--result0": "Serialized block headers of all located blocks, limited to some arbitrary maximum number of hashes (currently 2000, which matches the domainmessage protocol headers message, but this is not guaranteed)", // GetHeadersCmd help. "getHeaders--synopsis": "Returns block headers starting with the first known block hash from the request", "getHeaders-lowHash": "Block hash to start including headers from; if not found, it'll start from the genesis block.", "getHeaders-highHash": "Block hash to stop including block headers for; if not found, all headers to the latest known block are returned.", - "getHeaders--result0": "Serialized block headers of all located blocks, limited to some arbitrary maximum number of hashes (currently 2000, which matches the wire protocol headers message, but this is not guaranteed)", + "getHeaders--result0": "Serialized block headers of all located blocks, limited to some arbitrary maximum number of hashes (currently 2000, which matches the domainmessage protocol headers message, but this is not guaranteed)", // GetInfoCmd help. "getInfo--synopsis": "Returns a JSON object containing various state info.", diff --git a/rpc/rpcwebsocket.go b/rpc/rpcwebsocket.go index 6e7d2a898..03bd70700 100644 --- a/rpc/rpcwebsocket.go +++ b/rpc/rpcwebsocket.go @@ -26,11 +26,11 @@ import ( "github.com/btcsuite/websocket" "github.com/kaspanet/kaspad/dagconfig" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/rpc/model" "github.com/kaspanet/kaspad/txscript" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) const ( @@ -268,21 +268,21 @@ type wsClientFilter struct { otherAddresses map[string]struct{} // Outpoints of unspent outputs. - unspent map[wire.Outpoint]struct{} + unspent map[domainmessage.Outpoint]struct{} } // newWSClientFilter creates a new, empty wsClientFilter struct to be used // for a websocket client. // // NOTE: This extension was ported from github.com/decred/dcrd -func newWSClientFilter(addresses []string, unspentOutpoints []wire.Outpoint, params *dagconfig.Params) *wsClientFilter { +func newWSClientFilter(addresses []string, unspentOutpoints []domainmessage.Outpoint, params *dagconfig.Params) *wsClientFilter { filter := &wsClientFilter{ pubKeyHashes: map[[ripemd160.Size]byte]struct{}{}, scriptHashes: map[[ripemd160.Size]byte]struct{}{}, compressedPubKeys: map[[33]byte]struct{}{}, uncompressedPubKeys: map[[65]byte]struct{}{}, otherAddresses: map[string]struct{}{}, - unspent: make(map[wire.Outpoint]struct{}, len(unspentOutpoints)), + unspent: make(map[domainmessage.Outpoint]struct{}, len(unspentOutpoints)), } for _, s := range addresses { @@ -348,7 +348,7 @@ func (f *wsClientFilter) existsAddress(a util.Address) bool { // addUnspentOutpoint adds an outpoint to the wsClientFilter. // // NOTE: This extension was ported from github.com/decred/dcrd -func (f *wsClientFilter) addUnspentOutpoint(op *wire.Outpoint) { +func (f *wsClientFilter) addUnspentOutpoint(op *domainmessage.Outpoint) { f.unspent[*op] = struct{}{} } @@ -356,12 +356,12 @@ func (f *wsClientFilter) addUnspentOutpoint(op *wire.Outpoint) { // the wsClientFilter. // // NOTE: This extension was ported from github.com/decred/dcrd -func (f *wsClientFilter) existsUnspentOutpointNoLock(op *wire.Outpoint) bool { +func (f *wsClientFilter) existsUnspentOutpointNoLock(op *domainmessage.Outpoint) bool { _, ok := f.unspent[*op] return ok } -func (f *wsClientFilter) existsUnspentOutpoint(op *wire.Outpoint) bool { +func (f *wsClientFilter) existsUnspentOutpoint(op *domainmessage.Outpoint) bool { f.mu.Lock() defer f.mu.Unlock() return f.existsUnspentOutpointNoLock(op) @@ -602,7 +602,7 @@ func (m *wsNotificationManager) subscribedClients(tx *util.Tx, defer filter.mu.Unlock() if filter.existsAddress(addr) { subscribed[quitChan] = struct{}{} - op := wire.Outpoint{ + op := domainmessage.Outpoint{ TxID: *tx.ID(), Index: uint32(i), } @@ -755,7 +755,7 @@ func (m *wsNotificationManager) notifyForNewTx(clients map[chan struct{}]*wsClie } // txHexString returns the serialized transaction encoded in hexadecimal. -func txHexString(tx *wire.MsgTx) string { +func txHexString(tx *domainmessage.MsgTx) string { buf := bytes.NewBuffer(make([]byte, 0, tx.SerializeSize())) // Ignore Serialize's error, as writing to a bytes.buffer cannot fail. tx.Serialize(buf) diff --git a/txscript/engine.go b/txscript/engine.go index 23a77bb88..e8ed42c44 100644 --- a/txscript/engine.go +++ b/txscript/engine.go @@ -6,8 +6,8 @@ package txscript import ( "fmt" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/logger" - "github.com/kaspanet/kaspad/wire" ) // ScriptFlags is a bitmask defining additional operations or tests that will be @@ -43,7 +43,7 @@ type Engine struct { scriptOff int dstack stack // data stack astack stack // alt stack - tx wire.MsgTx + tx domainmessage.MsgTx txIdx int condStack []int numOps int @@ -434,7 +434,7 @@ func (vm *Engine) SetAltStack(data [][]byte) { // NewEngine returns a new script engine for the provided public key script, // transaction, and input index. The flags modify the behavior of the script // engine according to the description provided by each flag. -func NewEngine(scriptPubKey []byte, tx *wire.MsgTx, txIdx int, flags ScriptFlags, +func NewEngine(scriptPubKey []byte, tx *domainmessage.MsgTx, txIdx int, flags ScriptFlags, sigCache *SigCache) (*Engine, error) { // The provided transaction input index must refer to a valid input. diff --git a/txscript/engine_test.go b/txscript/engine_test.go index a60a8c30d..b6a59582c 100644 --- a/txscript/engine_test.go +++ b/txscript/engine_test.go @@ -7,8 +7,8 @@ package txscript import ( "testing" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) // TestBadPC sets the pc to a deliberately bad result then confirms that Step() @@ -24,9 +24,9 @@ func TestBadPC(t *testing.T) { } // tx with almost empty scripts. - txIns := []*wire.TxIn{ + txIns := []*domainmessage.TxIn{ { - PreviousOutpoint: wire.Outpoint{ + PreviousOutpoint: domainmessage.Outpoint{ TxID: daghash.TxID([32]byte{ 0xc9, 0x97, 0xa5, 0xe5, 0x6e, 0x10, 0x41, 0x02, @@ -43,11 +43,11 @@ func TestBadPC(t *testing.T) { Sequence: 4294967295, }, } - txOuts := []*wire.TxOut{{ + txOuts := []*domainmessage.TxOut{{ Value: 1000000000, ScriptPubKey: nil, }} - tx := wire.NewNativeMsgTx(1, txIns, txOuts) + tx := domainmessage.NewNativeMsgTx(1, txIns, txOuts) scriptPubKey := mustParseShortForm("NOP") for _, test := range tests { @@ -90,8 +90,8 @@ func TestCheckErrorCondition(t *testing.T) { for i, test := range tests { func() { - txIns := []*wire.TxIn{{ - PreviousOutpoint: wire.Outpoint{ + txIns := []*domainmessage.TxIn{{ + PreviousOutpoint: domainmessage.Outpoint{ TxID: daghash.TxID([32]byte{ 0xc9, 0x97, 0xa5, 0xe5, 0x6e, 0x10, 0x41, 0x02, @@ -107,11 +107,11 @@ func TestCheckErrorCondition(t *testing.T) { SignatureScript: nil, Sequence: 4294967295, }} - txOuts := []*wire.TxOut{{ + txOuts := []*domainmessage.TxOut{{ Value: 1000000000, ScriptPubKey: nil, }} - tx := wire.NewNativeMsgTx(1, txIns, txOuts) + tx := domainmessage.NewNativeMsgTx(1, txIns, txOuts) scriptPubKey := mustParseShortForm(test.script) @@ -209,8 +209,8 @@ func TestDisasmPC(t *testing.T) { t.Parallel() // tx with almost empty scripts. - txIns := []*wire.TxIn{{ - PreviousOutpoint: wire.Outpoint{ + txIns := []*domainmessage.TxIn{{ + PreviousOutpoint: domainmessage.Outpoint{ TxID: daghash.TxID([32]byte{ 0xc9, 0x97, 0xa5, 0xe5, 0x6e, 0x10, 0x41, 0x02, @@ -226,11 +226,11 @@ func TestDisasmPC(t *testing.T) { SignatureScript: mustParseShortForm("OP_2"), Sequence: 4294967295, }} - txOuts := []*wire.TxOut{{ + txOuts := []*domainmessage.TxOut{{ Value: 1000000000, ScriptPubKey: nil, }} - tx := wire.NewNativeMsgTx(1, txIns, txOuts) + tx := domainmessage.NewNativeMsgTx(1, txIns, txOuts) scriptPubKey := mustParseShortForm("OP_DROP NOP TRUE") @@ -269,8 +269,8 @@ func TestDisasmScript(t *testing.T) { t.Parallel() // tx with almost empty scripts. - txIns := []*wire.TxIn{{ - PreviousOutpoint: wire.Outpoint{ + txIns := []*domainmessage.TxIn{{ + PreviousOutpoint: domainmessage.Outpoint{ TxID: daghash.TxID([32]byte{ 0xc9, 0x97, 0xa5, 0xe5, 0x6e, 0x10, 0x41, 0x02, @@ -286,11 +286,11 @@ func TestDisasmScript(t *testing.T) { SignatureScript: mustParseShortForm("OP_2"), Sequence: 4294967295, }} - txOuts := []*wire.TxOut{{ + txOuts := []*domainmessage.TxOut{{ Value: 1000000000, ScriptPubKey: nil, }} - tx := wire.NewNativeMsgTx(1, txIns, txOuts) + tx := domainmessage.NewNativeMsgTx(1, txIns, txOuts) scriptPubKey := mustParseShortForm("OP_DROP NOP TRUE") vm, err := NewEngine(scriptPubKey, tx, 0, 0, nil) diff --git a/txscript/opcode.go b/txscript/opcode.go index 3821aade2..d55efb09f 100644 --- a/txscript/opcode.go +++ b/txscript/opcode.go @@ -15,8 +15,8 @@ import ( "golang.org/x/crypto/ripemd160" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) // An opcode defines the information related to a txscript opcode. opfunc, if @@ -1148,7 +1148,7 @@ func opcodeCheckLockTimeVerify(op *parsedOpcode, vm *Engine) error { // The lock time feature can also be disabled, thereby bypassing // OP_CHECKLOCKTIMEVERIFY, if every transaction input has been finalized by - // setting its sequence to the maximum value (wire.MaxTxInSequenceNum). This + // setting its sequence to the maximum value (domainmessage.MaxTxInSequenceNum). This // condition would result in the transaction being allowed into the blockDAG // making the opcode ineffective. // @@ -1160,7 +1160,7 @@ func opcodeCheckLockTimeVerify(op *parsedOpcode, vm *Engine) error { // NOTE: This implies that even if the transaction is not finalized due to // another input being unlocked, the opcode execution will still fail when the // input being used by the opcode is locked. - if vm.tx.TxIn[vm.txIdx].Sequence == wire.MaxTxInSequenceNum { + if vm.tx.TxIn[vm.txIdx].Sequence == domainmessage.MaxTxInSequenceNum { return scriptError(ErrUnsatisfiedLockTime, "transaction input is finalized") } @@ -1204,7 +1204,7 @@ func opcodeCheckSequenceVerify(op *parsedOpcode, vm *Engine) error { // To provide for future soft-fork extensibility, if the // operand has the disabled lock-time flag set, // CHECKSEQUENCEVERIFY behaves as a NOP. - if sequence&uint64(wire.SequenceLockTimeDisabled) != 0 { + if sequence&uint64(domainmessage.SequenceLockTimeDisabled) != 0 { return nil } @@ -1213,17 +1213,17 @@ func opcodeCheckSequenceVerify(op *parsedOpcode, vm *Engine) error { // number does not have this bit set prevents using this property // to get around a CHECKSEQUENCEVERIFY check. txSequence := vm.tx.TxIn[vm.txIdx].Sequence - if txSequence&wire.SequenceLockTimeDisabled != 0 { + if txSequence&domainmessage.SequenceLockTimeDisabled != 0 { str := fmt.Sprintf("transaction sequence has sequence "+ "locktime disabled bit set: 0x%x", txSequence) return scriptError(ErrUnsatisfiedLockTime, str) } // Mask off non-consensus bits before doing comparisons. - lockTimeMask := uint64(wire.SequenceLockTimeIsSeconds | - wire.SequenceLockTimeMask) + lockTimeMask := uint64(domainmessage.SequenceLockTimeIsSeconds | + domainmessage.SequenceLockTimeMask) return verifyLockTime(txSequence&lockTimeMask, - wire.SequenceLockTimeIsSeconds, sequence&lockTimeMask) + domainmessage.SequenceLockTimeIsSeconds, sequence&lockTimeMask) } // opcodeToAltStack removes the top item from the main data stack and pushes it diff --git a/txscript/reference_test.go b/txscript/reference_test.go index f22e374fc..1ebf00dda 100644 --- a/txscript/reference_test.go +++ b/txscript/reference_test.go @@ -15,8 +15,8 @@ import ( "strings" "testing" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) // scriptTestName returns a descriptive test name for the given reference script @@ -210,17 +210,17 @@ func parseExpectedResult(expected string) ([]ErrorCode, error) { // createSpendTx generates a basic spending transaction given the passed // signature and public key scripts. -func createSpendingTx(sigScript, scriptPubKey []byte) *wire.MsgTx { +func createSpendingTx(sigScript, scriptPubKey []byte) *domainmessage.MsgTx { - outpoint := wire.NewOutpoint(&daghash.TxID{}, ^uint32(0)) - txIn := wire.NewTxIn(outpoint, []byte{Op0, Op0}) - txOut := wire.NewTxOut(0, scriptPubKey) - coinbaseTx := wire.NewNativeMsgTx(wire.TxVersion, []*wire.TxIn{txIn}, []*wire.TxOut{txOut}) + outpoint := domainmessage.NewOutpoint(&daghash.TxID{}, ^uint32(0)) + txIn := domainmessage.NewTxIn(outpoint, []byte{Op0, Op0}) + txOut := domainmessage.NewTxOut(0, scriptPubKey) + coinbaseTx := domainmessage.NewNativeMsgTx(domainmessage.TxVersion, []*domainmessage.TxIn{txIn}, []*domainmessage.TxOut{txOut}) - outpoint = wire.NewOutpoint(coinbaseTx.TxID(), 0) - txIn = wire.NewTxIn(outpoint, sigScript) - txOut = wire.NewTxOut(0, nil) - spendingTx := wire.NewNativeMsgTx(wire.TxVersion, []*wire.TxIn{txIn}, []*wire.TxOut{txOut}) + outpoint = domainmessage.NewOutpoint(coinbaseTx.TxID(), 0) + txIn = domainmessage.NewTxIn(outpoint, sigScript) + txOut = domainmessage.NewTxOut(0, nil) + spendingTx := domainmessage.NewNativeMsgTx(domainmessage.TxVersion, []*domainmessage.TxIn{txIn}, []*domainmessage.TxOut{txOut}) return spendingTx } diff --git a/txscript/script.go b/txscript/script.go index f28a60dd8..bc1d44840 100644 --- a/txscript/script.go +++ b/txscript/script.go @@ -10,8 +10,8 @@ import ( "fmt" "github.com/pkg/errors" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) // SigHashType represents hash type bits at the end of a signature. @@ -252,29 +252,29 @@ func canonicalPush(pop parsedOpcode) bool { // calculating the signature hash. It is used over the Copy method on the // transaction itself since that is a deep copy and therefore does more work and // allocates much more space than needed. -func shallowCopyTx(tx *wire.MsgTx) wire.MsgTx { +func shallowCopyTx(tx *domainmessage.MsgTx) domainmessage.MsgTx { // As an additional memory optimization, use contiguous backing arrays // for the copied inputs and outputs and point the final slice of // pointers into the contiguous arrays. This avoids a lot of small // allocations. - // Specifically avoid using wire.NewMsgTx() to prevent correcting errors by + // Specifically avoid using domainmessage.NewMsgTx() to prevent correcting errors by // auto-generating various fields. - txCopy := wire.MsgTx{ + txCopy := domainmessage.MsgTx{ Version: tx.Version, - TxIn: make([]*wire.TxIn, len(tx.TxIn)), - TxOut: make([]*wire.TxOut, len(tx.TxOut)), + TxIn: make([]*domainmessage.TxIn, len(tx.TxIn)), + TxOut: make([]*domainmessage.TxOut, len(tx.TxOut)), LockTime: tx.LockTime, SubnetworkID: tx.SubnetworkID, Gas: tx.Gas, PayloadHash: tx.PayloadHash, Payload: tx.Payload, } - txIns := make([]wire.TxIn, len(tx.TxIn)) + txIns := make([]domainmessage.TxIn, len(tx.TxIn)) for i, oldTxIn := range tx.TxIn { txIns[i] = *oldTxIn txCopy.TxIn[i] = &txIns[i] } - txOuts := make([]wire.TxOut, len(tx.TxOut)) + txOuts := make([]domainmessage.TxOut, len(tx.TxOut)) for i, oldTxOut := range tx.TxOut { txOuts[i] = *oldTxOut txCopy.TxOut[i] = &txOuts[i] @@ -285,7 +285,7 @@ func shallowCopyTx(tx *wire.MsgTx) wire.MsgTx { // CalcSignatureHash will, given a script and hash type for the current script // engine instance, calculate the signature hash to be used for signing and // verification. -func CalcSignatureHash(script []byte, hashType SigHashType, tx *wire.MsgTx, idx int) (*daghash.Hash, error) { +func CalcSignatureHash(script []byte, hashType SigHashType, tx *domainmessage.MsgTx, idx int) (*daghash.Hash, error) { parsedScript, err := parseScript(script) if err != nil { return nil, errors.Errorf("cannot parse output script: %s", err) @@ -296,7 +296,7 @@ func CalcSignatureHash(script []byte, hashType SigHashType, tx *wire.MsgTx, idx // calcSignatureHash will, given a script and hash type for the current script // engine instance, calculate the signature hash to be used for signing and // verification. -func calcSignatureHash(script []parsedOpcode, hashType SigHashType, tx *wire.MsgTx, idx int) (*daghash.Hash, error) { +func calcSignatureHash(script []parsedOpcode, hashType SigHashType, tx *domainmessage.MsgTx, idx int) (*daghash.Hash, error) { // The SigHashSingle signature type signs only the corresponding input // and output (the output with the same index number as the input). // diff --git a/txscript/sign.go b/txscript/sign.go index cfd8f63d8..f5e451f10 100644 --- a/txscript/sign.go +++ b/txscript/sign.go @@ -9,13 +9,13 @@ import ( "github.com/pkg/errors" "github.com/kaspanet/kaspad/dagconfig" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util" - "github.com/kaspanet/kaspad/wire" ) // RawTxInSignature returns the serialized Schnorr signature for the input idx of // the given transaction, with hashType appended to it. -func RawTxInSignature(tx *wire.MsgTx, idx int, script []byte, +func RawTxInSignature(tx *domainmessage.MsgTx, idx int, script []byte, hashType SigHashType, key *secp256k1.PrivateKey) ([]byte, error) { hash, err := CalcSignatureHash(script, hashType, tx, idx) @@ -39,7 +39,7 @@ func RawTxInSignature(tx *wire.MsgTx, idx int, script []byte, // as the idx'th input. privKey is serialized in either a compressed or // uncompressed format based on compress. This format must match the same format // used to generate the payment address, or the script validation will fail. -func SignatureScript(tx *wire.MsgTx, idx int, script []byte, hashType SigHashType, privKey *secp256k1.PrivateKey, compress bool) ([]byte, error) { +func SignatureScript(tx *domainmessage.MsgTx, idx int, script []byte, hashType SigHashType, privKey *secp256k1.PrivateKey, compress bool) ([]byte, error) { sig, err := RawTxInSignature(tx, idx, script, hashType, privKey) if err != nil { return nil, err @@ -62,7 +62,7 @@ func SignatureScript(tx *wire.MsgTx, idx int, script []byte, hashType SigHashTyp return NewScriptBuilder().AddData(sig).AddData(pkData).Script() } -func sign(dagParams *dagconfig.Params, tx *wire.MsgTx, idx int, +func sign(dagParams *dagconfig.Params, tx *domainmessage.MsgTx, idx int, script []byte, hashType SigHashType, kdb KeyDB, sdb ScriptDB) ([]byte, ScriptClass, util.Address, error) { @@ -105,7 +105,7 @@ func sign(dagParams *dagconfig.Params, tx *wire.MsgTx, idx int, // The return value is the best effort merging of the two scripts. Calling this // function with addresses, class and nrequired that do not match scriptPubKey is // an error and results in undefined behaviour. -func mergeScripts(dagParams *dagconfig.Params, tx *wire.MsgTx, idx int, +func mergeScripts(dagParams *dagconfig.Params, tx *domainmessage.MsgTx, idx int, class ScriptClass, sigScript, prevScript []byte) ([]byte, error) { // TODO: the scripthash and multisig paths here are overly @@ -199,7 +199,7 @@ func (sc ScriptClosure) GetScript(address util.Address) ([]byte, error) { // getScript. If previousScript is provided then the results in previousScript // will be merged in a type-dependent manner with the newly generated. // signature script. -func SignTxOutput(dagParams *dagconfig.Params, tx *wire.MsgTx, idx int, +func SignTxOutput(dagParams *dagconfig.Params, tx *domainmessage.MsgTx, idx int, scriptPubKey []byte, hashType SigHashType, kdb KeyDB, sdb ScriptDB, previousScript []byte) ([]byte, error) { diff --git a/txscript/sign_test.go b/txscript/sign_test.go index b75975685..b9f3e058e 100644 --- a/txscript/sign_test.go +++ b/txscript/sign_test.go @@ -11,9 +11,9 @@ import ( "testing" "github.com/kaspanet/kaspad/dagconfig" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) type addressToKey struct { @@ -53,7 +53,7 @@ func mkGetScript(scripts map[string][]byte) ScriptDB { }) } -func checkScripts(msg string, tx *wire.MsgTx, idx int, sigScript, scriptPubKey []byte) error { +func checkScripts(msg string, tx *domainmessage.MsgTx, idx int, sigScript, scriptPubKey []byte) error { tx.TxIn[idx].SignatureScript = sigScript var flags ScriptFlags vm, err := NewEngine(scriptPubKey, tx, idx, @@ -72,7 +72,7 @@ func checkScripts(msg string, tx *wire.MsgTx, idx int, sigScript, scriptPubKey [ return nil } -func signAndCheck(msg string, tx *wire.MsgTx, idx int, scriptPubKey []byte, +func signAndCheck(msg string, tx *domainmessage.MsgTx, idx int, scriptPubKey []byte, hashType SigHashType, kdb KeyDB, sdb ScriptDB, previousScript []byte) error { @@ -99,30 +99,30 @@ func TestSignTxOutput(t *testing.T) { SigHashNone | SigHashAnyOneCanPay, SigHashSingle | SigHashAnyOneCanPay, } - txIns := []*wire.TxIn{ + txIns := []*domainmessage.TxIn{ { - PreviousOutpoint: wire.Outpoint{ + PreviousOutpoint: domainmessage.Outpoint{ TxID: daghash.TxID{}, Index: 0, }, Sequence: 4294967295, }, { - PreviousOutpoint: wire.Outpoint{ + PreviousOutpoint: domainmessage.Outpoint{ TxID: daghash.TxID{}, Index: 1, }, Sequence: 4294967295, }, { - PreviousOutpoint: wire.Outpoint{ + PreviousOutpoint: domainmessage.Outpoint{ TxID: daghash.TxID{}, Index: 2, }, Sequence: 4294967295, }, } - txOuts := []*wire.TxOut{ + txOuts := []*domainmessage.TxOut{ { Value: 1, }, @@ -133,7 +133,7 @@ func TestSignTxOutput(t *testing.T) { Value: 3, }, } - tx := wire.NewNativeMsgTx(1, txIns, txOuts) + tx := domainmessage.NewNativeMsgTx(1, txIns, txOuts) // Pay to Pubkey Hash (uncompressed) for _, hashType := range hashTypes { @@ -703,7 +703,7 @@ func TestSignTxOutput(t *testing.T) { } type tstInput struct { - txout *wire.TxOut + txout *domainmessage.TxOut sigscriptGenerates bool inputValidates bool indexOutOfRange bool @@ -717,7 +717,7 @@ type tstSigScript struct { scriptAtWrongIndex bool } -var coinbaseOutpoint = &wire.Outpoint{ +var coinbaseOutpoint = &domainmessage.Outpoint{ Index: (1 << 32) - 1, } @@ -748,7 +748,7 @@ var sigScriptTests = []tstSigScript{ name: "one input uncompressed", inputs: []tstInput{ { - txout: wire.NewTxOut(coinbaseVal, uncompressedScriptPubKey), + txout: domainmessage.NewTxOut(coinbaseVal, uncompressedScriptPubKey), sigscriptGenerates: true, inputValidates: true, indexOutOfRange: false, @@ -762,13 +762,13 @@ var sigScriptTests = []tstSigScript{ name: "two inputs uncompressed", inputs: []tstInput{ { - txout: wire.NewTxOut(coinbaseVal, uncompressedScriptPubKey), + txout: domainmessage.NewTxOut(coinbaseVal, uncompressedScriptPubKey), sigscriptGenerates: true, inputValidates: true, indexOutOfRange: false, }, { - txout: wire.NewTxOut(coinbaseVal+fee, uncompressedScriptPubKey), + txout: domainmessage.NewTxOut(coinbaseVal+fee, uncompressedScriptPubKey), sigscriptGenerates: true, inputValidates: true, indexOutOfRange: false, @@ -782,7 +782,7 @@ var sigScriptTests = []tstSigScript{ name: "one input compressed", inputs: []tstInput{ { - txout: wire.NewTxOut(coinbaseVal, compressedScriptPubKey), + txout: domainmessage.NewTxOut(coinbaseVal, compressedScriptPubKey), sigscriptGenerates: true, inputValidates: true, indexOutOfRange: false, @@ -796,13 +796,13 @@ var sigScriptTests = []tstSigScript{ name: "two inputs compressed", inputs: []tstInput{ { - txout: wire.NewTxOut(coinbaseVal, compressedScriptPubKey), + txout: domainmessage.NewTxOut(coinbaseVal, compressedScriptPubKey), sigscriptGenerates: true, inputValidates: true, indexOutOfRange: false, }, { - txout: wire.NewTxOut(coinbaseVal+fee, compressedScriptPubKey), + txout: domainmessage.NewTxOut(coinbaseVal+fee, compressedScriptPubKey), sigscriptGenerates: true, inputValidates: true, indexOutOfRange: false, @@ -816,7 +816,7 @@ var sigScriptTests = []tstSigScript{ name: "hashType SigHashNone", inputs: []tstInput{ { - txout: wire.NewTxOut(coinbaseVal, uncompressedScriptPubKey), + txout: domainmessage.NewTxOut(coinbaseVal, uncompressedScriptPubKey), sigscriptGenerates: true, inputValidates: true, indexOutOfRange: false, @@ -830,7 +830,7 @@ var sigScriptTests = []tstSigScript{ name: "hashType SigHashSingle", inputs: []tstInput{ { - txout: wire.NewTxOut(coinbaseVal, uncompressedScriptPubKey), + txout: domainmessage.NewTxOut(coinbaseVal, uncompressedScriptPubKey), sigscriptGenerates: true, inputValidates: true, indexOutOfRange: false, @@ -844,7 +844,7 @@ var sigScriptTests = []tstSigScript{ name: "hashType SigHashAll | SigHashAnyoneCanPay", inputs: []tstInput{ { - txout: wire.NewTxOut(coinbaseVal, uncompressedScriptPubKey), + txout: domainmessage.NewTxOut(coinbaseVal, uncompressedScriptPubKey), sigscriptGenerates: true, inputValidates: true, indexOutOfRange: false, @@ -858,7 +858,7 @@ var sigScriptTests = []tstSigScript{ name: "hashType SigHashAnyoneCanPay", inputs: []tstInput{ { - txout: wire.NewTxOut(coinbaseVal, uncompressedScriptPubKey), + txout: domainmessage.NewTxOut(coinbaseVal, uncompressedScriptPubKey), sigscriptGenerates: true, inputValidates: false, indexOutOfRange: false, @@ -872,7 +872,7 @@ var sigScriptTests = []tstSigScript{ name: "hashType non-exist", inputs: []tstInput{ { - txout: wire.NewTxOut(coinbaseVal, uncompressedScriptPubKey), + txout: domainmessage.NewTxOut(coinbaseVal, uncompressedScriptPubKey), sigscriptGenerates: true, inputValidates: false, indexOutOfRange: false, @@ -886,7 +886,7 @@ var sigScriptTests = []tstSigScript{ name: "invalid compression", inputs: []tstInput{ { - txout: wire.NewTxOut(coinbaseVal, uncompressedScriptPubKey), + txout: domainmessage.NewTxOut(coinbaseVal, uncompressedScriptPubKey), sigscriptGenerates: true, inputValidates: false, indexOutOfRange: false, @@ -900,7 +900,7 @@ var sigScriptTests = []tstSigScript{ name: "short ScriptPubKey", inputs: []tstInput{ { - txout: wire.NewTxOut(coinbaseVal, shortScriptPubKey), + txout: domainmessage.NewTxOut(coinbaseVal, shortScriptPubKey), sigscriptGenerates: false, indexOutOfRange: false, }, @@ -913,13 +913,13 @@ var sigScriptTests = []tstSigScript{ name: "valid script at wrong index", inputs: []tstInput{ { - txout: wire.NewTxOut(coinbaseVal, uncompressedScriptPubKey), + txout: domainmessage.NewTxOut(coinbaseVal, uncompressedScriptPubKey), sigscriptGenerates: true, inputValidates: true, indexOutOfRange: false, }, { - txout: wire.NewTxOut(coinbaseVal+fee, uncompressedScriptPubKey), + txout: domainmessage.NewTxOut(coinbaseVal+fee, uncompressedScriptPubKey), sigscriptGenerates: true, inputValidates: true, indexOutOfRange: false, @@ -933,13 +933,13 @@ var sigScriptTests = []tstSigScript{ name: "index out of range", inputs: []tstInput{ { - txout: wire.NewTxOut(coinbaseVal, uncompressedScriptPubKey), + txout: domainmessage.NewTxOut(coinbaseVal, uncompressedScriptPubKey), sigscriptGenerates: true, inputValidates: true, indexOutOfRange: false, }, { - txout: wire.NewTxOut(coinbaseVal+fee, uncompressedScriptPubKey), + txout: domainmessage.NewTxOut(coinbaseVal+fee, uncompressedScriptPubKey), sigscriptGenerates: true, inputValidates: true, indexOutOfRange: false, @@ -963,13 +963,13 @@ func TestSignatureScript(t *testing.T) { nexttest: for i := range sigScriptTests { - txOuts := []*wire.TxOut{wire.NewTxOut(500, []byte{OpReturn})} + txOuts := []*domainmessage.TxOut{domainmessage.NewTxOut(500, []byte{OpReturn})} - txIns := []*wire.TxIn{} + txIns := []*domainmessage.TxIn{} for range sigScriptTests[i].inputs { - txIns = append(txIns, wire.NewTxIn(coinbaseOutpoint, nil)) + txIns = append(txIns, domainmessage.NewTxIn(coinbaseOutpoint, nil)) } - tx := wire.NewNativeMsgTx(wire.TxVersion, txIns, txOuts) + tx := domainmessage.NewNativeMsgTx(domainmessage.TxVersion, txIns, txOuts) var script []byte var err error diff --git a/util/block.go b/util/block.go index e98b3f857..34ddcd2a2 100644 --- a/util/block.go +++ b/util/block.go @@ -11,8 +11,8 @@ import ( "github.com/kaspanet/kaspad/util/mstime" "io" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) // OutOfRangeError describes an error due to accessing an element that is out @@ -35,7 +35,7 @@ func (e OutOfRangeError) Error() string { // repeat the relatively expensive hashing operations. type Block struct { // Underlying MsgBlock - msgBlock *wire.MsgBlock + msgBlock *domainmessage.MsgBlock // Serialized bytes for the block. This is used only internally, and .Hash() should be used anywhere. serializedBlock []byte @@ -53,14 +53,14 @@ type Block struct { blueScore *uint64 } -// MsgBlock returns the underlying wire.MsgBlock for the Block. -func (b *Block) MsgBlock() *wire.MsgBlock { +// MsgBlock returns the underlying domainmessage.MsgBlock for the Block. +func (b *Block) MsgBlock() *domainmessage.MsgBlock { // Return the cached block. return b.msgBlock } // Bytes returns the serialized bytes for the Block. This is equivalent to -// calling Serialize on the underlying wire.MsgBlock, however it caches the +// calling Serialize on the underlying domainmessage.MsgBlock, however it caches the // result so subsequent calls are more efficient. func (b *Block) Bytes() ([]byte, error) { // Return the cached serialized bytes if it has already been generated. @@ -82,7 +82,7 @@ func (b *Block) Bytes() ([]byte, error) { } // Hash returns the block identifier hash for the Block. This is equivalent to -// calling BlockHash on the underlying wire.MsgBlock, however it caches the +// calling BlockHash on the underlying domainmessage.MsgBlock, however it caches the // result so subsequent calls are more efficient. func (b *Block) Hash() *daghash.Hash { // Return the cached block hash if it has already been generated. @@ -99,8 +99,8 @@ func (b *Block) Hash() *daghash.Hash { // Tx returns a wrapped transaction (util.Tx) for the transaction at the // specified index in the Block. The supplied index is 0 based. That is to // say, the first transaction in the block is txNum 0. This is nearly -// equivalent to accessing the raw transaction (wire.MsgTx) from the -// underlying wire.MsgBlock, however the wrapped transaction has some helpful +// equivalent to accessing the raw transaction (domainmessage.MsgTx) from the +// underlying domainmessage.MsgBlock, however the wrapped transaction has some helpful // properties such as caching the hash so subsequent calls are more efficient. func (b *Block) Tx(txNum int) (*Tx, error) { // Ensure the requested transaction is in range. @@ -130,7 +130,7 @@ func (b *Block) Tx(txNum int) (*Tx, error) { // Transactions returns a slice of wrapped transactions (util.Tx) for all // transactions in the Block. This is nearly equivalent to accessing the raw -// transactions (wire.MsgTx) in the underlying wire.MsgBlock, however it +// transactions (domainmessage.MsgTx) in the underlying domainmessage.MsgBlock, however it // instead provides easy access to wrapped versions (util.Tx) of them. func (b *Block) Transactions() []*Tx { // Return transactions if they have ALL already been generated. This @@ -162,7 +162,7 @@ func (b *Block) Transactions() []*Tx { // TxHash returns the hash for the requested transaction number in the Block. // The supplied index is 0 based. That is to say, the first transaction in the // block is txNum 0. This is equivalent to calling TxHash on the underlying -// wire.MsgTx, however it caches the result so subsequent calls are more +// domainmessage.MsgTx, however it caches the result so subsequent calls are more // efficient. func (b *Block) TxHash(txNum int) (*daghash.Hash, error) { // Attempt to get a wrapped transaction for the specified index. It @@ -181,14 +181,14 @@ func (b *Block) TxHash(txNum int) (*daghash.Hash, error) { // TxLoc returns the offsets and lengths of each transaction in a raw block. // It is used to allow fast indexing into transactions within the raw byte // stream. -func (b *Block) TxLoc() ([]wire.TxLoc, error) { +func (b *Block) TxLoc() ([]domainmessage.TxLoc, error) { rawMsg, err := b.Bytes() if err != nil { return nil, err } rbuf := bytes.NewBuffer(rawMsg) - var mblock wire.MsgBlock + var mblock domainmessage.MsgBlock txLocs, err := mblock.DeserializeTxLoc(rbuf) if err != nil { return nil, err @@ -224,8 +224,8 @@ func (b *Block) BlueScore() (uint64, error) { } // NewBlock returns a new instance of a kaspa block given an underlying -// wire.MsgBlock. See Block. -func NewBlock(msgBlock *wire.MsgBlock) *Block { +// domainmessage.MsgBlock. See Block. +func NewBlock(msgBlock *domainmessage.MsgBlock) *Block { return &Block{ msgBlock: msgBlock, } @@ -247,7 +247,7 @@ func NewBlockFromBytes(serializedBlock []byte) (*Block, error) { // Reader to deserialize the block. See Block. func NewBlockFromReader(r io.Reader) (*Block, error) { // Deserialize the bytes into a MsgBlock. - var msgBlock wire.MsgBlock + var msgBlock domainmessage.MsgBlock err := msgBlock.Deserialize(r) if err != nil { return nil, err @@ -260,8 +260,8 @@ func NewBlockFromReader(r io.Reader) (*Block, error) { } // NewBlockFromBlockAndBytes returns a new instance of a kaspa block given -// an underlying wire.MsgBlock and the serialized bytes for it. See Block. -func NewBlockFromBlockAndBytes(msgBlock *wire.MsgBlock, serializedBlock []byte) *Block { +// an underlying domainmessage.MsgBlock and the serialized bytes for it. See Block. +func NewBlockFromBlockAndBytes(msgBlock *domainmessage.MsgBlock, serializedBlock []byte) *Block { return &Block{ msgBlock: msgBlock, serializedBlock: serializedBlock, diff --git a/util/block_test.go b/util/block_test.go index 9a3b752a1..7fd559051 100644 --- a/util/block_test.go +++ b/util/block_test.go @@ -7,11 +7,11 @@ package util_test import ( "bytes" "github.com/davecgh/go-spew/spew" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/mstime" "github.com/kaspanet/kaspad/util/subnetworkid" - "github.com/kaspanet/kaspad/wire" "github.com/pkg/errors" "io" "math" @@ -138,7 +138,7 @@ func TestBlock(t *testing.T) { } // Transaction offsets and length for the transaction in Block100000. - wantTxLocs := []wire.TxLoc{ + wantTxLocs := []domainmessage.TxLoc{ {TxStart: 186, TxLen: 163}, {TxStart: 349, TxLen: 287}, {TxStart: 636, TxLen: 285}, @@ -296,8 +296,8 @@ func TestBlockErrors(t *testing.T) { // Block100000 defines block 100,000 of the block DAG. It is used to // test Block operations. -var Block100000 = wire.MsgBlock{ - Header: wire.BlockHeader{ +var Block100000 = domainmessage.MsgBlock{ + Header: domainmessage.BlockHeader{ Version: 1, ParentHashes: []*daghash.Hash{ { @@ -334,12 +334,12 @@ var Block100000 = wire.MsgBlock{ Bits: 0x1e00ffff, // 503382015 Nonce: 0x000ae53f, // 714047 }, - Transactions: []*wire.MsgTx{ + Transactions: []*domainmessage.MsgTx{ { Version: 1, - TxIn: []*wire.TxIn{ + TxIn: []*domainmessage.TxIn{ { - PreviousOutpoint: wire.Outpoint{ + PreviousOutpoint: domainmessage.Outpoint{ TxID: daghash.TxID{}, Index: 0xffffffff, }, @@ -349,7 +349,7 @@ var Block100000 = wire.MsgBlock{ Sequence: math.MaxUint64, }, }, - TxOut: []*wire.TxOut{ + TxOut: []*domainmessage.TxOut{ { Value: 0x12a05f200, // 5000000000 ScriptPubKey: []byte{ @@ -372,9 +372,9 @@ var Block100000 = wire.MsgBlock{ }, { Version: 1, - TxIn: []*wire.TxIn{ + TxIn: []*domainmessage.TxIn{ { - PreviousOutpoint: wire.Outpoint{ + PreviousOutpoint: domainmessage.Outpoint{ TxID: daghash.TxID([32]byte{ 0x03, 0x2e, 0x38, 0xe9, 0xc0, 0xa8, 0x4c, 0x60, 0x46, 0xd6, 0x87, 0xd1, 0x05, 0x56, 0xdc, 0xac, @@ -409,7 +409,7 @@ var Block100000 = wire.MsgBlock{ Sequence: math.MaxUint64, }, }, - TxOut: []*wire.TxOut{ + TxOut: []*domainmessage.TxOut{ { Value: 0x2123e300, // 556000000 ScriptPubKey: []byte{ @@ -442,9 +442,9 @@ var Block100000 = wire.MsgBlock{ }, { Version: 1, - TxIn: []*wire.TxIn{ + TxIn: []*domainmessage.TxIn{ { - PreviousOutpoint: wire.Outpoint{ + PreviousOutpoint: domainmessage.Outpoint{ TxID: daghash.TxID([32]byte{ 0xc3, 0x3e, 0xbf, 0xf2, 0xa7, 0x09, 0xf1, 0x3d, 0x9f, 0x9a, 0x75, 0x69, 0xab, 0x16, 0xa3, 0x27, @@ -478,7 +478,7 @@ var Block100000 = wire.MsgBlock{ Sequence: math.MaxUint64, }, }, - TxOut: []*wire.TxOut{ + TxOut: []*domainmessage.TxOut{ { Value: 0xf4240, // 1000000 ScriptPubKey: []byte{ @@ -511,9 +511,9 @@ var Block100000 = wire.MsgBlock{ }, { Version: 1, - TxIn: []*wire.TxIn{ + TxIn: []*domainmessage.TxIn{ { - PreviousOutpoint: wire.Outpoint{ + PreviousOutpoint: domainmessage.Outpoint{ TxID: daghash.TxID([32]byte{ 0x0b, 0x60, 0x72, 0xb3, 0x86, 0xd4, 0xa7, 0x73, 0x23, 0x52, 0x37, 0xf6, 0x4c, 0x11, 0x26, 0xac, @@ -548,7 +548,7 @@ var Block100000 = wire.MsgBlock{ Sequence: math.MaxUint64, }, }, - TxOut: []*wire.TxOut{ + TxOut: []*domainmessage.TxOut{ { Value: 0xf4240, // 1000000 ScriptPubKey: []byte{ diff --git a/util/coinbasepayload/coinbasepayload.go b/util/coinbasepayload/coinbasepayload.go index adaa0e1f1..62c261872 100644 --- a/util/coinbasepayload/coinbasepayload.go +++ b/util/coinbasepayload/coinbasepayload.go @@ -3,8 +3,8 @@ package coinbasepayload import ( "bytes" "encoding/binary" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util/binaryserializer" - "github.com/kaspanet/kaspad/wire" "github.com/pkg/errors" ) @@ -17,7 +17,7 @@ func SerializeCoinbasePayload(blueScore uint64, scriptPubKey []byte, extraData [ if err != nil { return nil, err } - err = wire.WriteVarInt(w, uint64(len(scriptPubKey))) + err = domainmessage.WriteVarInt(w, uint64(len(scriptPubKey))) if err != nil { return nil, err } @@ -36,13 +36,13 @@ func SerializeCoinbasePayload(blueScore uint64, scriptPubKey []byte, extraData [ var ErrIncorrectScriptPubKeyLen = errors.New("incorrect script pub key length") // DeserializeCoinbasePayload deserializes the coinbase payload to its component (scriptPubKey and extra data). -func DeserializeCoinbasePayload(tx *wire.MsgTx) (blueScore uint64, scriptPubKey []byte, extraData []byte, err error) { +func DeserializeCoinbasePayload(tx *domainmessage.MsgTx) (blueScore uint64, scriptPubKey []byte, extraData []byte, err error) { r := bytes.NewReader(tx.Payload) blueScore, err = binaryserializer.Uint64(r, byteOrder) if err != nil { return 0, nil, nil, err } - scriptPubKeyLen, err := wire.ReadVarInt(r) + scriptPubKeyLen, err := domainmessage.ReadVarInt(r) if err != nil { return 0, nil, nil, err } diff --git a/util/doc.go b/util/doc.go index 27fc03bf0..f923f1937 100644 --- a/util/doc.go +++ b/util/doc.go @@ -4,14 +4,14 @@ Package util provides kaspa-specific convenience functions and types. Block Overview A Block defines a kaspa block that provides easier and more efficient -manipulation of raw wire protocol blocks. It also memoizes hashes for the +manipulation of raw blocks. It also memoizes hashes for the block and its transactions on their first access so subsequent accesses don't have to repeat the relatively expensive hashing operations. Tx Overview A Tx defines a kaspa transaction that provides more efficient manipulation of -raw wire protocol transactions. It memoizes the hash for the transaction on its +raw transactions. It memoizes the hash for the transaction on its first access so subsequent accesses don't have to repeat the relatively expensive hashing operations. diff --git a/util/testtools/testtools.go b/util/testtools/testtools.go index df81a6f72..f06a9ebb8 100644 --- a/util/testtools/testtools.go +++ b/util/testtools/testtools.go @@ -11,15 +11,15 @@ import ( "github.com/kaspanet/kaspad/blockdag" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/txscript" "github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util/subnetworkid" - "github.com/kaspanet/kaspad/wire" ) // RegisterSubnetworkForTest is used to register network on DAG with specified gas limit func RegisterSubnetworkForTest(dag *blockdag.BlockDAG, params *dagconfig.Params, gasLimit uint64) (*subnetworkid.SubnetworkID, error) { - buildNextBlock := func(parentHashes []*daghash.Hash, txs []*wire.MsgTx) (*util.Block, error) { + buildNextBlock := func(parentHashes []*daghash.Hash, txs []*domainmessage.MsgTx) (*util.Block, error) { msgBlock, err := mining.PrepareBlockForTest(dag, parentHashes, txs, false) if err != nil { return nil, err @@ -46,7 +46,7 @@ func RegisterSubnetworkForTest(dag *blockdag.BlockDAG, params *dagconfig.Params, } // Create a block in order to fund later transactions - fundsBlock, err := buildNextBlock(dag.TipHashes(), []*wire.MsgTx{}) + fundsBlock, err := buildNextBlock(dag.TipHashes(), []*domainmessage.MsgTx{}) if err != nil { return nil, errors.Errorf("could not build funds block: %s", err) } @@ -63,9 +63,9 @@ func RegisterSubnetworkForTest(dag *blockdag.BlockDAG, params *dagconfig.Params, if err != nil { return nil, errors.Errorf("Failed to build signature script: %s", err) } - txIn := &wire.TxIn{ - PreviousOutpoint: *wire.NewOutpoint(fundsBlockCbTx.TxID(), 0), - Sequence: wire.MaxTxInSequenceNum, + txIn := &domainmessage.TxIn{ + PreviousOutpoint: *domainmessage.NewOutpoint(fundsBlockCbTx.TxID(), 0), + Sequence: domainmessage.MaxTxInSequenceNum, SignatureScript: signatureScript, } @@ -73,14 +73,14 @@ func RegisterSubnetworkForTest(dag *blockdag.BlockDAG, params *dagconfig.Params, if err != nil { return nil, err } - txOut := &wire.TxOut{ + txOut := &domainmessage.TxOut{ ScriptPubKey: scriptPubKey, Value: fundsBlockCbTx.TxOut[0].Value, } - registryTx := wire.NewRegistryMsgTx(1, []*wire.TxIn{txIn}, []*wire.TxOut{txOut}, gasLimit) + registryTx := domainmessage.NewRegistryMsgTx(1, []*domainmessage.TxIn{txIn}, []*domainmessage.TxOut{txOut}, gasLimit) // Add it to the DAG - registryBlock, err := buildNextBlock([]*daghash.Hash{fundsBlock.Hash()}, []*wire.MsgTx{registryTx}) + registryBlock, err := buildNextBlock([]*daghash.Hash{fundsBlock.Hash()}, []*domainmessage.MsgTx{registryTx}) if err != nil { return nil, errors.Errorf("could not build registry block: %s", err) } diff --git a/util/tx.go b/util/tx.go index 2f67f9bed..ce9c405fa 100644 --- a/util/tx.go +++ b/util/tx.go @@ -8,8 +8,8 @@ import ( "bytes" "io" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) // TxIndexUnknown is the value returned for a transaction index that is unknown. @@ -22,20 +22,20 @@ const TxIndexUnknown = -1 // transaction on its first access so subsequent accesses don't have to repeat // the relatively expensive hashing operations. type Tx struct { - msgTx *wire.MsgTx // Underlying MsgTx - txHash *daghash.Hash // Cached transaction hash - txID *daghash.TxID // Cached transaction ID - txIndex int // Position within a block or TxIndexUnknown + msgTx *domainmessage.MsgTx // Underlying MsgTx + txHash *daghash.Hash // Cached transaction hash + txID *daghash.TxID // Cached transaction ID + txIndex int // Position within a block or TxIndexUnknown } -// MsgTx returns the underlying wire.MsgTx for the transaction. -func (t *Tx) MsgTx() *wire.MsgTx { +// MsgTx returns the underlying domainmessage.MsgTx for the transaction. +func (t *Tx) MsgTx() *domainmessage.MsgTx { // Return the cached transaction. return t.msgTx } // Hash returns the hash of the transaction. This is equivalent to -// calling TxHash on the underlying wire.MsgTx, however it caches the +// calling TxHash on the underlying domainmessage.MsgTx, however it caches the // result so subsequent calls are more efficient. func (t *Tx) Hash() *daghash.Hash { // Return the cached hash if it has already been generated. @@ -50,7 +50,7 @@ func (t *Tx) Hash() *daghash.Hash { } // ID returns the id of the transaction. This is equivalent to -// calling TxID on the underlying wire.MsgTx, however it caches the +// calling TxID on the underlying domainmessage.MsgTx, however it caches the // result so subsequent calls are more efficient. func (t *Tx) ID() *daghash.TxID { // Return the cached hash if it has already been generated. @@ -85,8 +85,8 @@ func (t *Tx) IsCoinBase() bool { } // NewTx returns a new instance of a kaspa transaction given an underlying -// wire.MsgTx. See Tx. -func NewTx(msgTx *wire.MsgTx) *Tx { +// domainmessage.MsgTx. See Tx. +func NewTx(msgTx *domainmessage.MsgTx) *Tx { return &Tx{ msgTx: msgTx, txIndex: TxIndexUnknown, @@ -104,7 +104,7 @@ func NewTxFromBytes(serializedTx []byte) (*Tx, error) { // Reader to deserialize the transaction. See Tx. func NewTxFromReader(r io.Reader) (*Tx, error) { // Deserialize the bytes into a MsgTx. - var msgTx wire.MsgTx + var msgTx domainmessage.MsgTx err := msgTx.Deserialize(r) if err != nil { return nil, err diff --git a/util/txsort/txsort.go b/util/txsort/txsort.go index e20bab531..c7271da72 100644 --- a/util/txsort/txsort.go +++ b/util/txsort/txsort.go @@ -11,8 +11,8 @@ import ( "bytes" "sort" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util/daghash" - "github.com/kaspanet/kaspad/wire" ) // InPlaceSort modifies the passed transaction inputs and outputs to be sorted @@ -27,7 +27,7 @@ import ( // The function should only be used if the caller is creating the transaction or // is otherwise 100% positive mutating will not cause adverse affects due to // other dependencies. -func InPlaceSort(tx *wire.MsgTx) { +func InPlaceSort(tx *domainmessage.MsgTx) { sort.Sort(sortableInputSlice(tx.TxIn)) sort.Sort(sortableOutputSlice(tx.TxOut)) } @@ -35,7 +35,7 @@ func InPlaceSort(tx *wire.MsgTx) { // Sort returns a new transaction with the inputs and outputs sorted based on // BIP 69. The passed transaction is not modified and the new transaction // might have a different hash if any sorting was done. -func Sort(tx *wire.MsgTx) *wire.MsgTx { +func Sort(tx *domainmessage.MsgTx) *domainmessage.MsgTx { txCopy := tx.Copy() sort.Sort(sortableInputSlice(txCopy.TxIn)) sort.Sort(sortableOutputSlice(txCopy.TxOut)) @@ -44,7 +44,7 @@ func Sort(tx *wire.MsgTx) *wire.MsgTx { // IsSorted checks whether tx has inputs and outputs sorted according to BIP // 69. -func IsSorted(tx *wire.MsgTx) bool { +func IsSorted(tx *domainmessage.MsgTx) bool { if !sort.IsSorted(sortableInputSlice(tx.TxIn)) { return false } @@ -54,8 +54,8 @@ func IsSorted(tx *wire.MsgTx) bool { return true } -type sortableInputSlice []*wire.TxIn -type sortableOutputSlice []*wire.TxOut +type sortableInputSlice []*domainmessage.TxIn +type sortableOutputSlice []*domainmessage.TxOut // For SortableInputSlice and SortableOutputSlice, three functions are needed // to make it sortable with sort.Sort() -- Len, Less, and Swap diff --git a/util/txsort/txsort_test.go b/util/txsort/txsort_test.go index b5efb4563..864424854 100644 --- a/util/txsort/txsort_test.go +++ b/util/txsort/txsort_test.go @@ -11,8 +11,8 @@ import ( "path/filepath" "testing" + "github.com/kaspanet/kaspad/domainmessage" "github.com/kaspanet/kaspad/util/txsort" - "github.com/kaspanet/kaspad/wire" ) // TestSort ensures the transaction sorting works according to the BIP. @@ -76,7 +76,7 @@ func TestSort(t *testing.T) { test.name, err) continue } - var tx wire.MsgTx + var tx domainmessage.MsgTx err = tx.Deserialize(bytes.NewReader(txBytes)) if err != nil { t.Errorf("Deserialize (%s): unexpected error %v", diff --git a/wire/invvect.go b/wire/invvect.go deleted file mode 100644 index 3b8d0063a..000000000 --- a/wire/invvect.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (c) 2013-2016 The btcsuite developers -// Use of this source code is governed by an ISC -// license that can be found in the LICENSE file. - -package wire - -import ( - "fmt" - "io" - - "github.com/kaspanet/kaspad/util/daghash" -) - -const ( - // MaxInvPerMsg is the maximum number of inventory vectors that can be in a - // single kaspa inv message. - MaxInvPerMsg = 1 << 17 - - // MaxSyncBlockInvPerGetDataMsg is the maximum number of sync block inventory - // vectors that can be in a single getData message. - MaxSyncBlockInvPerGetDataMsg = 50 - - // MaxInvPerGetDataMsg is the maximum number of inventory vectors that can - // be in a single getData message. - MaxInvPerGetDataMsg = MaxInvPerMsg - - // Maximum payload size for an inventory vector. - maxInvVectPayload = 4 + daghash.HashSize -) - -// InvType represents the allowed types of inventory vectors. See InvVect. -type InvType uint32 - -// These constants define the various supported inventory vector types. -const ( - InvTypeError InvType = 0 - InvTypeTx InvType = 1 - InvTypeBlock InvType = 2 - InvTypeFilteredBlock InvType = 3 - InvTypeSyncBlock InvType = 4 - InvTypeMissingAncestor InvType = 5 -) - -// Map of service flags back to their constant names for pretty printing. -var ivStrings = map[InvType]string{ - InvTypeError: "ERROR", - InvTypeTx: "MSG_TX", - InvTypeBlock: "MSG_BLOCK", - InvTypeFilteredBlock: "MSG_FILTERED_BLOCK", - InvTypeSyncBlock: "MSG_SYNC_BLOCK", - InvTypeMissingAncestor: "MSG_MISSING_ANCESTOR", -} - -// String returns the InvType in human-readable form. -func (invtype InvType) String() string { - if s, ok := ivStrings[invtype]; ok { - return s - } - - return fmt.Sprintf("Unknown InvType (%d)", uint32(invtype)) -} - -// InvVect defines a kaspa inventory vector which is used to describe data, -// as specified by the Type field, that a peer wants, has, or does not have to -// another peer. -type InvVect struct { - Type InvType // Type of data - Hash *daghash.Hash // Hash of the data -} - -// NewInvVect returns a new InvVect using the provided type and hash. -func NewInvVect(typ InvType, hash *daghash.Hash) *InvVect { - return &InvVect{ - Type: typ, - Hash: hash, - } -} - -// readInvVect reads an encoded InvVect from r depending on the protocol -// version. -func readInvVect(r io.Reader, pver uint32, iv *InvVect) error { - iv.Hash = &daghash.Hash{} - return readElements(r, &iv.Type, iv.Hash) -} - -// writeInvVect serializes an InvVect to w depending on the protocol version. -func writeInvVect(w io.Writer, pver uint32, iv *InvVect) error { - return writeElements(w, iv.Type, iv.Hash) -} - -func (iv *InvVect) String() string { - return fmt.Sprintf("{%s:%s}", iv.Type, iv.Hash) -} - -// IsBlockOrSyncBlock returns true if the inv type is InvTypeBlock or InvTypeSyncBlock -func (iv *InvVect) IsBlockOrSyncBlock() bool { - return iv.Type == InvTypeBlock || iv.Type == InvTypeSyncBlock -} diff --git a/wire/invvect_test.go b/wire/invvect_test.go deleted file mode 100644 index a71beae52..000000000 --- a/wire/invvect_test.go +++ /dev/null @@ -1,173 +0,0 @@ -// Copyright (c) 2013-2016 The btcsuite developers -// Use of this source code is governed by an ISC -// license that can be found in the LICENSE file. - -package wire - -import ( - "bytes" - "reflect" - "testing" - - "github.com/davecgh/go-spew/spew" - "github.com/kaspanet/kaspad/util/daghash" -) - -// TestInvVectStringer tests the stringized output for inventory vector types. -func TestInvTypeStringer(t *testing.T) { - tests := []struct { - in InvType - want string - }{ - {InvTypeError, "ERROR"}, - {InvTypeTx, "MSG_TX"}, - {InvTypeBlock, "MSG_BLOCK"}, - {0xffffffff, "Unknown InvType (4294967295)"}, - } - - t.Logf("Running %d tests", len(tests)) - for i, test := range tests { - result := test.in.String() - if result != test.want { - t.Errorf("String #%d\n got: %s want: %s", i, result, - test.want) - continue - } - } - -} - -// TestInvVect tests the InvVect API. -func TestInvVect(t *testing.T) { - ivType := InvTypeBlock - hash := daghash.Hash{} - - // Ensure we get the same payload and signature back out. - iv := NewInvVect(ivType, &hash) - if iv.Type != ivType { - t.Errorf("NewInvVect: wrong type - got %v, want %v", - iv.Type, ivType) - } - if !iv.Hash.IsEqual(&hash) { - t.Errorf("NewInvVect: wrong hash - got %v, want %v", - spew.Sdump(iv.Hash), spew.Sdump(hash)) - } - -} - -// TestInvVectWire tests the InvVect wire encode and decode for various -// protocol versions and supported inventory vector types. -func TestInvVectWire(t *testing.T) { - // Block 203707 hash. - hashStr := "3264bc2ac36a60840790ba1d475d01367e7c723da941069e9dc" - baseHash, err := daghash.NewHashFromStr(hashStr) - if err != nil { - t.Errorf("NewHashFromStr: %v", err) - } - - // errInvVect is an inventory vector with an error. - errInvVect := InvVect{ - Type: InvTypeError, - Hash: &daghash.Hash{}, - } - - // errInvVectEncoded is the wire encoded bytes of errInvVect. - errInvVectEncoded := []byte{ - 0x00, 0x00, 0x00, 0x00, // InvTypeError - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // No hash - } - - // txInvVect is an inventory vector representing a transaction. - txInvVect := InvVect{ - Type: InvTypeTx, - Hash: baseHash, - } - - // txInvVectEncoded is the wire encoded bytes of txInvVect. - txInvVectEncoded := []byte{ - 0x01, 0x00, 0x00, 0x00, // InvTypeTx - 0xdc, 0xe9, 0x69, 0x10, 0x94, 0xda, 0x23, 0xc7, - 0xe7, 0x67, 0x13, 0xd0, 0x75, 0xd4, 0xa1, 0x0b, - 0x79, 0x40, 0x08, 0xa6, 0x36, 0xac, 0xc2, 0x4b, - 0x26, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Block 203707 hash - } - - // blockInvVect is an inventory vector representing a block. - blockInvVect := InvVect{ - Type: InvTypeBlock, - Hash: baseHash, - } - - // blockInvVectEncoded is the wire encoded bytes of blockInvVect. - blockInvVectEncoded := []byte{ - 0x02, 0x00, 0x00, 0x00, // InvTypeBlock - 0xdc, 0xe9, 0x69, 0x10, 0x94, 0xda, 0x23, 0xc7, - 0xe7, 0x67, 0x13, 0xd0, 0x75, 0xd4, 0xa1, 0x0b, - 0x79, 0x40, 0x08, 0xa6, 0x36, 0xac, 0xc2, 0x4b, - 0x26, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Block 203707 hash - } - - tests := []struct { - in InvVect // NetAddress to encode - out InvVect // Expected decoded NetAddress - buf []byte // Wire encoding - pver uint32 // Protocol version for wire encoding - }{ - // Latest protocol version error inventory vector. - { - errInvVect, - errInvVect, - errInvVectEncoded, - ProtocolVersion, - }, - - // Latest protocol version tx inventory vector. - { - txInvVect, - txInvVect, - txInvVectEncoded, - ProtocolVersion, - }, - - // Latest protocol version block inventory vector. - { - blockInvVect, - blockInvVect, - blockInvVectEncoded, - ProtocolVersion, - }, - } - - t.Logf("Running %d tests", len(tests)) - for i, test := range tests { - // Encode to wire format. - var buf bytes.Buffer - err := writeInvVect(&buf, test.pver, &test.in) - if err != nil { - t.Errorf("writeInvVect #%d error %v", i, err) - continue - } - if !bytes.Equal(buf.Bytes(), test.buf) { - t.Errorf("writeInvVect #%d\n got: %s want: %s", i, - spew.Sdump(buf.Bytes()), spew.Sdump(test.buf)) - continue - } - - // Decode the message from wire format. - var iv InvVect - rbuf := bytes.NewReader(test.buf) - err = readInvVect(rbuf, test.pver, &iv) - if err != nil { - t.Errorf("readInvVect #%d error %v", i, err) - continue - } - if !reflect.DeepEqual(iv, test.out) { - t.Errorf("readInvVect #%d\n got: %s want: %s", i, - spew.Sdump(iv), spew.Sdump(test.out)) - continue - } - } -}