Compare commits

...

33 Commits

Author SHA1 Message Date
Ori Newman
53706c2f9f bignet debug 2020-09-02 15:43:00 +03:00
Ori Newman
917fa11706 bignet debug 2020-09-02 14:53:38 +03:00
Ori Newman
a32a9011c7 [NOD-1305] Close client connection on disconnect (#909) 2020-08-31 15:57:11 +03:00
stasatdaglabs
5da957f16e Update to version 0.6.8 2020-08-30 11:31:43 +03:00
Ori Newman
505d264603 [NOD-1322] Fix compilation on windows (#905) 2020-08-27 18:04:54 +03:00
Ori Newman
883361fea3 [NOD-1323] Always save new block reachability data (#906) 2020-08-27 18:03:50 +03:00
stasatdaglabs
13a6872a45 Update to version 0.6.7 2020-08-26 12:13:43 +03:00
Elichai Turkel
c82a951a24 [NOD-1316] Refactor TestGHOSTDAG to enable arbitrary DAGs (#899)
* Add VirtualBlueHashes to BlockDAG

* Refactor TestGHOSTDAG to read DAGs from json files

* Added a new DAG for the ghostdag test suite

* Pass BehaviorFlags to delayed blocks
2020-08-25 14:00:43 +03:00
Ori Newman
bbb9dfa4cd [NOD-1318] Check if relay block is known before requesting it (#900) 2020-08-25 09:18:03 +03:00
stasatdaglabs
86d51fa1cb [NOD-1307] Fix duplicate connections (#897)
* [NOD-1307] Lock peersMutex in methods that don't.

* [NOD-1307] Fix duplicate connections.

* [NOD-1307] Use RLock instead of Lock.

* [NOD-1307] Simplify IsEqual.
2020-08-24 16:11:32 +03:00
Ori Newman
8dd7b95423 [NOD-1308] Don't call wg.done() on handshake if flow failed (#896) 2020-08-24 14:03:58 +03:00
stasatdaglabs
b668d98942 [NOD-1095] Fix data races in gRPCConnection.stream. (#895) 2020-08-24 12:56:19 +03:00
stasatdaglabs
e9602cc777 [NOD-1304] Fix nil deference originating in HandleHandshake. (#894) 2020-08-24 11:45:33 +03:00
stasatdaglabs
5fd164bf66 [NOD-1095] RLock the dagLock in SelectedTipHeader. (#893) 2020-08-24 11:31:12 +03:00
Ori Newman
83e7c9e8e4 [NOD-1303] Fix concurent access to UTXO set from RPC (#892) 2020-08-23 18:54:03 +03:00
Ori Newman
a6b8eea369 [NOD-1301] Add MsgReject to protowire mapping (#891) 2020-08-23 18:29:41 +03:00
stasatdaglabs
15b545ee2b [NOD-592] Remove TODOs and XXXs from the codebase (#890)
* [NOD-592] Remove TODOs related to fake nonces.

* [NOD-592] Remove irrelevant TODOs from handleRescanBlocks and parseTxAcceptedVerboseNtfnParams.

* [NOD-592] Fix TODO in handleGetTxOut.

* [NOD-592] Remove irrelevant TODO from updateAddress.

* [NOD-592] Move StandardVerifyFlags to a separate file.

* [NOD-592] Remove TODOs in sign.go.

* [NOD-592] Remove TODO in scriptval_test.go.

* [NOD-592] Remove TODO in reachabilitystore.go.

* [NOD-592] Remove XXXs.

* [NOD-592] Fix a comment.

* [NOD-557] Move AddAddressByIP out of AddressManager since it's used only for tests..

* [NOD-557] Remove rescan blocks.

* [NOD-592] Fix handleGetTxOut.
2020-08-23 17:17:06 +03:00
stasatdaglabs
667b2d46e9 [NOD-557] Remove RegTest (#889)
* [NOD-557] Remove regTest network.

* [NOD-557] Remove remaining references to regTest.

* [NOD-557] Move newHashFromStr from params.go to params_test.go.

* [NOD-557] Rename test to network in register_test.go.

* [NOD-557] Replaced removed tests in TestDecodeAddressErrorConditions.
2020-08-23 15:38:27 +03:00
stasatdaglabs
53ab906ea8 [NOD-1279] Handle ruleErrors properly in processIBDBlock. (#887) 2020-08-23 13:42:21 +03:00
stasatdaglabs
5d20772f94 [NOD-1293] Fix kaspad sending 127.0.0.1 in its msgVersion (#886)
* [NOD-1293] Use addressManager's GetBestLocalAddress.

* [NOD-1293] Copy the initListeners function from the old p2p to the address manager.

* [NOD-1293] Remove debug logs.

* [NOD-1293] Remove unused import.

* [NOD-1293] Fix a comment.
2020-08-23 13:11:48 +03:00
stasatdaglabs
d4728bd9b6 Update to version 0.6.6 2020-08-23 11:22:13 +03:00
Ori Newman
4dbd64478c [NOD-1294] In TestTxRelay return after tx is found in the mempool (#885) 2020-08-20 19:05:53 +03:00
stasatdaglabs
7756baf9a9 [NOD-1290] Add blocklogger.LogBlock to IBD. (#884) 2020-08-20 12:29:11 +03:00
Ori Newman
c331293a2e [NOD-1289] Check if connection exists before establishing another one with the same address (#883) 2020-08-20 11:50:29 +03:00
Ori Newman
fcae491e6d [NOD-1286] Close router from netConnection.Disconnect (#881)
* [NOD-1286] Close router from netConnection.Disconnect

* [NOD-1286] Close router in grpc errors as well

* [NOD-1286] Fix typo

* [NOD-1286] Rename isConnected->isRouterClosed
2020-08-19 17:28:01 +03:00
stasatdaglabs
5a4cafe342 Update to version 0.6.5 2020-08-19 15:00:12 +03:00
Ori Newman
8dae378bd9 [NOD-1285] Fix deadlock on connection manager (#880) 2020-08-19 13:24:20 +03:00
stasatdaglabs
8dd409dc1c [NOD-1223] Rename executables package back to cmd. (#879) 2020-08-19 11:45:11 +03:00
Ori Newman
74110a2e49 [NOD-1282] Remove peer after disconnect (#878) 2020-08-19 11:10:10 +03:00
Ori Newman
ce876a7c44 Merge remote-tracking branch 'origin/v0.6.3-dev' into v0.6.4-dev 2020-08-18 19:03:52 +03:00
stasatdaglabs
d14809694f [NOD-1223] Reorganize directory structure (#874)
* [NOD-1223] Delete unused files/packages.

* [NOD-1223] Move signal and limits to the os package.

* [NOD-1223] Put database and dbaccess into the db package.

* [NOD-1223] Fold the logs package into the logger package.

* [NOD-1223] Rename domainmessage to appmessage.

* [NOD-1223] Rename to/from DomainMessage to AppMessage.

* [NOD-1223] Move appmessage to the app packge.

* [NOD-1223] Move protocol to the app packge.

* [NOD-1223] Move the network package to the infrastructure packge.

* [NOD-1223] Rename cmd to executables.

* [NOD-1223] Fix go.doc in the logger package.
2020-08-18 10:26:39 +03:00
stasatdaglabs
450ff81f86 [NOD-1275] Fix onNewBlock not being called from RPC submitBlock (#873)
* [NOD-1275] Fix onNewBlock not being called from from RPC submitBlock.

* [NOD-1275] Rename tx to txID.
2020-08-17 15:24:00 +03:00
Ori Newman
8cac582f6d Update to version 0.6.4 2020-08-16 17:30:09 +03:00
438 changed files with 3319 additions and 3106 deletions

View File

@@ -40,10 +40,8 @@ recommended that `GOPATH` is set to a directory in your home directory such as
```bash ```bash
$ git clone https://github.com/kaspanet/kaspad $GOPATH/src/github.com/kaspanet/kaspad $ git clone https://github.com/kaspanet/kaspad $GOPATH/src/github.com/kaspanet/kaspad
$ cd $GOPATH/src/github.com/kaspanet/kaspad $ cd $GOPATH/src/github.com/kaspanet/kaspad
$ ./test.sh
$ go install . ./cmd/... $ go install . ./cmd/...
``` ```
`./test.sh` tests can be skipped, but some things might not run correctly on your system if tests fail.
- Kaspad (and utilities) should now be installed in `$GOPATH/bin`. If you did - Kaspad (and utilities) should now be installed in `$GOPATH/bin`. If you did
not already add the bin directory to your system path during Go installation, not already add the bin directory to your system path during Go installation,

View File

@@ -4,24 +4,24 @@ import (
"fmt" "fmt"
"sync/atomic" "sync/atomic"
"github.com/kaspanet/kaspad/network/addressmanager" "github.com/kaspanet/kaspad/infrastructure/network/addressmanager"
"github.com/kaspanet/kaspad/network/netadapter/id" "github.com/kaspanet/kaspad/infrastructure/network/netadapter/id"
"github.com/kaspanet/kaspad/app/appmessage"
"github.com/kaspanet/kaspad/app/protocol"
"github.com/kaspanet/kaspad/domain/blockdag" "github.com/kaspanet/kaspad/domain/blockdag"
"github.com/kaspanet/kaspad/domain/blockdag/indexers" "github.com/kaspanet/kaspad/domain/blockdag/indexers"
"github.com/kaspanet/kaspad/domain/mempool" "github.com/kaspanet/kaspad/domain/mempool"
"github.com/kaspanet/kaspad/domain/mining" "github.com/kaspanet/kaspad/domain/mining"
"github.com/kaspanet/kaspad/domain/txscript" "github.com/kaspanet/kaspad/domain/txscript"
"github.com/kaspanet/kaspad/infrastructure/config" "github.com/kaspanet/kaspad/infrastructure/config"
"github.com/kaspanet/kaspad/infrastructure/dbaccess" "github.com/kaspanet/kaspad/infrastructure/db/dbaccess"
"github.com/kaspanet/kaspad/infrastructure/signal" "github.com/kaspanet/kaspad/infrastructure/network/connmanager"
"github.com/kaspanet/kaspad/network/connmanager" "github.com/kaspanet/kaspad/infrastructure/network/dnsseed"
"github.com/kaspanet/kaspad/network/dnsseed" "github.com/kaspanet/kaspad/infrastructure/network/netadapter"
"github.com/kaspanet/kaspad/network/domainmessage" "github.com/kaspanet/kaspad/infrastructure/network/rpc"
"github.com/kaspanet/kaspad/network/netadapter" "github.com/kaspanet/kaspad/infrastructure/os/signal"
"github.com/kaspanet/kaspad/network/protocol"
"github.com/kaspanet/kaspad/network/rpc"
"github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util"
"github.com/kaspanet/kaspad/util/panics" "github.com/kaspanet/kaspad/util/panics"
) )
@@ -114,13 +114,14 @@ func New(cfg *config.Config, databaseContext *dbaccess.DatabaseContext, interrup
if err != nil { if err != nil {
return nil, err return nil, err
} }
addressManager := addressmanager.New(cfg, databaseContext) addressManager, err := addressmanager.New(cfg, databaseContext)
if err != nil {
return nil, err
}
connectionManager, err := connmanager.New(cfg, netAdapter, addressManager) connectionManager, err := connmanager.New(cfg, netAdapter, addressManager)
if err != nil { if err != nil {
return nil, err return nil, err
} }
protocolManager, err := protocol.NewManager(cfg, dag, netAdapter, addressManager, txMempool, connectionManager) protocolManager, err := protocol.NewManager(cfg, dag, netAdapter, addressManager, txMempool, connectionManager)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -143,8 +144,8 @@ func New(cfg *config.Config, databaseContext *dbaccess.DatabaseContext, interrup
func (a *App) maybeSeedFromDNS() { func (a *App) maybeSeedFromDNS() {
if !a.cfg.DisableDNSSeed { if !a.cfg.DisableDNSSeed {
dnsseed.SeedFromDNS(a.cfg.NetParams(), a.cfg.DNSSeed, domainmessage.SFNodeNetwork, false, nil, dnsseed.SeedFromDNS(a.cfg.NetParams(), a.cfg.DNSSeed, appmessage.SFNodeNetwork, false, nil,
a.cfg.Lookup, func(addresses []*domainmessage.NetAddress) { a.cfg.Lookup, func(addresses []*appmessage.NetAddress) {
// Kaspad uses a lookup of the dns seeder here. Since seeder returns // 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 // 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. // source. So we'll take first returned address as source.

View File

@@ -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 // Reads and validates the next kaspa message from conn using the
// protocol version pver and the kaspa network kaspanet. The returns // protocol version pver and the kaspa network kaspanet. The returns
// are a domainmessage.Message, a []byte which contains the unmarshalled // are a appmessage.Message, a []byte which contains the unmarshalled
// raw payload, and a possible error. // raw payload, and a possible error.
msg, rawPayload, err := wire.ReadMessage(conn, pver, kaspanet) msg, rawPayload, err := wire.ReadMessage(conn, pver, kaspanet)
if err != nil { if err != nil {

View File

@@ -1,4 +1,4 @@
package domainmessage package appmessage
import "time" import "time"

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"bytes" "bytes"
@@ -16,7 +16,7 @@ import (
) )
// genesisCoinbaseTx is the coinbase transaction for the genesis blocks for // genesisCoinbaseTx is the coinbase transaction for the genesis blocks for
// the main network, regression test network, and test network. // the main network and test network.
var genesisCoinbaseTxIns = []*TxIn{ var genesisCoinbaseTxIns = []*TxIn{
{ {
PreviousOutpoint: Outpoint{ PreviousOutpoint: Outpoint{
@@ -352,7 +352,7 @@ func BenchmarkReadBlockHeader(b *testing.B) {
0x3a, 0x9f, 0xb8, 0xaa, 0x4b, 0x1e, 0x5e, 0x4a, // MerkleRoot 0x3a, 0x9f, 0xb8, 0xaa, 0x4b, 0x1e, 0x5e, 0x4a, // MerkleRoot
0x29, 0xab, 0x5f, 0x49, 0x00, 0x00, 0x00, 0x00, // Timestamp 0x29, 0xab, 0x5f, 0x49, 0x00, 0x00, 0x00, 0x00, // Timestamp
0xff, 0xff, 0x00, 0x1d, // Bits 0xff, 0xff, 0x00, 0x1d, // Bits
0xf3, 0xe0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, // Fake Nonce. TODO: (Ori) Replace to a real nonce 0xf3, 0xe0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, // Fake Nonce
0x00, // TxnCount Varint 0x00, // TxnCount Varint
} }
r := bytes.NewReader(buf) r := bytes.NewReader(buf)

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"fmt" "fmt"
@@ -88,7 +88,7 @@ func (h *BlockHeader) IsGenesis() bool {
// KaspaDecode decodes r using the kaspa protocol encoding into the receiver. // KaspaDecode decodes r using the kaspa protocol encoding into the receiver.
// This is part of the Message interface implementation. // This is part of the Message interface implementation.
// See Deserialize for decoding block headers stored to disk, such as in a // See Deserialize for decoding block headers stored to disk, such as in a
// database, as opposed to decoding block headers from the domainmessage. // database, as opposed to decoding block headers from the appmessage.
func (h *BlockHeader) KaspaDecode(r io.Reader, pver uint32) error { func (h *BlockHeader) KaspaDecode(r io.Reader, pver uint32) error {
return readBlockHeader(r, pver, h) return readBlockHeader(r, pver, h)
} }
@@ -96,7 +96,7 @@ func (h *BlockHeader) KaspaDecode(r io.Reader, pver uint32) error {
// KaspaEncode encodes the receiver to w using the kaspa protocol encoding. // KaspaEncode encodes the receiver to w using the kaspa protocol encoding.
// This is part of the Message interface implementation. // This is part of the Message interface implementation.
// See Serialize for encoding block headers to be stored to disk, such as in a // See Serialize for encoding block headers to be stored to disk, such as in a
// database, as opposed to encoding block headers for the domainmessage. // database, as opposed to encoding block headers for the appmessage.
func (h *BlockHeader) KaspaEncode(w io.Writer, pver uint32) error { func (h *BlockHeader) KaspaEncode(w io.Writer, pver uint32) error {
return writeBlockHeader(w, pver, h) return writeBlockHeader(w, pver, h)
} }
@@ -105,7 +105,7 @@ func (h *BlockHeader) KaspaEncode(w io.Writer, pver uint32) error {
// that is suitable for long-term storage such as a database while respecting // that is suitable for long-term storage such as a database while respecting
// the Version field. // the Version field.
func (h *BlockHeader) Deserialize(r io.Reader) error { func (h *BlockHeader) Deserialize(r io.Reader) error {
// At the current time, there is no difference between the domainmessage encoding // At the current time, there is no difference between the appmessage encoding
// at protocol version 0 and the stable long-term storage format. As // at protocol version 0 and the stable long-term storage format. As
// a result, make use of readBlockHeader. // a result, make use of readBlockHeader.
return readBlockHeader(r, 0, h) return readBlockHeader(r, 0, h)
@@ -115,7 +115,7 @@ func (h *BlockHeader) Deserialize(r io.Reader) error {
// that is suitable for long-term storage such as a database while respecting // that is suitable for long-term storage such as a database while respecting
// the Version field. // the Version field.
func (h *BlockHeader) Serialize(w io.Writer) error { func (h *BlockHeader) Serialize(w io.Writer) error {
// At the current time, there is no difference between the domainmessage encoding // At the current time, there is no difference between the appmessage encoding
// at protocol version 0 and the stable long-term storage format. As // at protocol version 0 and the stable long-term storage format. As
// a result, make use of writeBlockHeader. // a result, make use of writeBlockHeader.
return writeBlockHeader(w, 0, h) return writeBlockHeader(w, 0, h)
@@ -149,7 +149,7 @@ func NewBlockHeader(version int32, parentHashes []*daghash.Hash, hashMerkleRoot
// readBlockHeader reads a kaspa block header from r. See Deserialize for // 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 block headers stored to disk, such as in a database, as opposed to
// decoding from the domainmessage. // decoding from the appmessage.
func readBlockHeader(r io.Reader, pver uint32, bh *BlockHeader) error { func readBlockHeader(r io.Reader, pver uint32, bh *BlockHeader) error {
var numParentBlocks byte var numParentBlocks byte
err := readElements(r, &bh.Version, &numParentBlocks) err := readElements(r, &bh.Version, &numParentBlocks)
@@ -175,7 +175,7 @@ func readBlockHeader(r io.Reader, pver uint32, bh *BlockHeader) error {
// writeBlockHeader writes a kaspa block header to w. See Serialize for // 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 // encoding block headers to be stored to disk, such as in a database, as
// opposed to encoding for the domainmessage. // opposed to encoding for the appmessage.
func writeBlockHeader(w io.Writer, pver uint32, bh *BlockHeader) error { func writeBlockHeader(w io.Writer, pver uint32, bh *BlockHeader) error {
timestamp := bh.Timestamp.UnixMilliseconds() timestamp := bh.Timestamp.UnixMilliseconds()
if err := writeElements(w, bh.Version, bh.NumParentBlocks()); err != nil { if err := writeElements(w, bh.Version, bh.NumParentBlocks()); err != nil {

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"bytes" "bytes"
@@ -47,7 +47,7 @@ func TestBlockHeader(t *testing.T) {
} }
} }
// TestBlockHeaderEncoding tests the BlockHeader domainmessage encode and decode for various // TestBlockHeaderEncoding tests the BlockHeader appmessage encode and decode for various
// protocol versions. // protocol versions.
func TestBlockHeaderEncoding(t *testing.T) { func TestBlockHeaderEncoding(t *testing.T) {
nonce := uint64(123123) // 0x000000000001e0f3 nonce := uint64(123123) // 0x000000000001e0f3
@@ -66,7 +66,7 @@ func TestBlockHeaderEncoding(t *testing.T) {
Nonce: nonce, Nonce: nonce,
} }
// baseBlockHdrEncoded is the domainmessage encoded bytes of baseBlockHdr. // baseBlockHdrEncoded is the appmessage encoded bytes of baseBlockHdr.
baseBlockHdrEncoded := []byte{ baseBlockHdrEncoded := []byte{
0x01, 0x00, 0x00, 0x00, // Version 1 0x01, 0x00, 0x00, 0x00, // Version 1
0x02, // NumParentBlocks 0x02, // NumParentBlocks
@@ -92,14 +92,14 @@ func TestBlockHeaderEncoding(t *testing.T) {
0x65, 0x9C, 0x79, 0x3C, 0xE3, 0x70, 0xD9, 0x5F, 0x65, 0x9C, 0x79, 0x3C, 0xE3, 0x70, 0xD9, 0x5F,
0x99, 0x0f, 0xed, 0x15, 0x73, 0x01, 0x00, 0x00, // Timestamp 0x99, 0x0f, 0xed, 0x15, 0x73, 0x01, 0x00, 0x00, // Timestamp
0xff, 0xff, 0x00, 0x1d, // Bits 0xff, 0xff, 0x00, 0x1d, // Bits
0xf3, 0xe0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, // Fake Nonce. TODO: (Ori) Replace to a real nonce 0xf3, 0xe0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, // Fake Nonce
} }
tests := []struct { tests := []struct {
in *BlockHeader // Data to encode in *BlockHeader // Data to encode
out *BlockHeader // Expected decoded data out *BlockHeader // Expected decoded data
buf []byte // Encoded data buf []byte // Encoded data
pver uint32 // Protocol version for domainmessage encoding pver uint32 // Protocol version for appmessage encoding
}{ }{
// Latest protocol version. // Latest protocol version.
{ {
@@ -112,7 +112,7 @@ func TestBlockHeaderEncoding(t *testing.T) {
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
// Encode to domainmessage format. // Encode to appmessage format.
var buf bytes.Buffer var buf bytes.Buffer
err := writeBlockHeader(&buf, test.pver, test.in) err := writeBlockHeader(&buf, test.pver, test.in)
if err != nil { if err != nil {
@@ -137,7 +137,7 @@ func TestBlockHeaderEncoding(t *testing.T) {
continue continue
} }
// Decode the block header from domainmessage format. // Decode the block header from appmessage format.
var bh BlockHeader var bh BlockHeader
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
err = readBlockHeader(rbuf, test.pver, &bh) err = readBlockHeader(rbuf, test.pver, &bh)
@@ -182,7 +182,7 @@ func TestBlockHeaderSerialize(t *testing.T) {
Nonce: nonce, Nonce: nonce,
} }
// baseBlockHdrEncoded is the domainmessage encoded bytes of baseBlockHdr. // baseBlockHdrEncoded is the appmessage encoded bytes of baseBlockHdr.
baseBlockHdrEncoded := []byte{ baseBlockHdrEncoded := []byte{
0x01, 0x00, 0x00, 0x00, // Version 1 0x01, 0x00, 0x00, 0x00, // Version 1
0x02, // NumParentBlocks 0x02, // NumParentBlocks
@@ -208,7 +208,7 @@ func TestBlockHeaderSerialize(t *testing.T) {
0x65, 0x9C, 0x79, 0x3C, 0xE3, 0x70, 0xD9, 0x5F, 0x65, 0x9C, 0x79, 0x3C, 0xE3, 0x70, 0xD9, 0x5F,
0x99, 0x0f, 0xed, 0x15, 0x73, 0x01, 0x00, 0x00, // Timestamp 0x99, 0x0f, 0xed, 0x15, 0x73, 0x01, 0x00, 0x00, // Timestamp
0xff, 0xff, 0x00, 0x1d, // Bits 0xff, 0xff, 0x00, 0x1d, // Bits
0xf3, 0xe0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, // Fake Nonce. TODO: (Ori) Replace to a real nonce 0xf3, 0xe0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, // Fake Nonce
} }
tests := []struct { tests := []struct {

View File

@@ -2,12 +2,12 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"github.com/kaspanet/kaspad/network/netadapter/id" "github.com/kaspanet/kaspad/infrastructure/network/netadapter/id"
"github.com/kaspanet/kaspad/util/binaryserializer" "github.com/kaspanet/kaspad/util/binaryserializer"
"github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/daghash"
"github.com/kaspanet/kaspad/util/mstime" "github.com/kaspanet/kaspad/util/mstime"

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"bytes" "bytes"
@@ -57,7 +57,7 @@ var exampleUTXOCommitment = &daghash.Hash{
0x65, 0x9C, 0x79, 0x3C, 0xE3, 0x70, 0xD9, 0x5F, 0x65, 0x9C, 0x79, 0x3C, 0xE3, 0x70, 0xD9, 0x5F,
} }
// TestElementEncoding tests domainmessage encode and decode for various element types. This // TestElementEncoding tests appmessage encode and decode for various element types. This
// is mainly to test the "fast" paths in readElement and writeElement which use // is mainly to test the "fast" paths in readElement and writeElement which use
// type assertions to avoid reflection when possible. // type assertions to avoid reflection when possible.
func TestElementEncoding(t *testing.T) { func TestElementEncoding(t *testing.T) {
@@ -129,7 +129,7 @@ func TestElementEncoding(t *testing.T) {
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
// Write to domainmessage format. // Write to appmessage format.
var buf bytes.Buffer var buf bytes.Buffer
err := WriteElement(&buf, test.in) err := WriteElement(&buf, test.in)
if err != nil { if err != nil {
@@ -142,7 +142,7 @@ func TestElementEncoding(t *testing.T) {
continue continue
} }
// Read from domainmessage format. // Read from appmessage format.
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
val := test.in val := test.in
if reflect.ValueOf(test.in).Kind() != reflect.Ptr { if reflect.ValueOf(test.in).Kind() != reflect.Ptr {
@@ -165,7 +165,7 @@ func TestElementEncoding(t *testing.T) {
} }
} }
// TestElementEncodingErrors performs negative tests against domainmessage encode and decode // TestElementEncodingErrors performs negative tests against appmessage encode and decode
// of various element types to confirm error paths work correctly. // of various element types to confirm error paths work correctly.
func TestElementEncodingErrors(t *testing.T) { func TestElementEncodingErrors(t *testing.T) {
type writeElementReflect int32 type writeElementReflect int32
@@ -209,7 +209,7 @@ func TestElementEncodingErrors(t *testing.T) {
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
// Encode to domainmessage format. // Encode to appmessage format.
w := newFixedWriter(test.max) w := newFixedWriter(test.max)
err := WriteElement(w, test.in) err := WriteElement(w, test.in)
if !errors.Is(err, test.writeErr) { if !errors.Is(err, test.writeErr) {
@@ -218,7 +218,7 @@ func TestElementEncodingErrors(t *testing.T) {
continue continue
} }
// Decode from domainmessage format. // Decode from appmessage format.
r := newFixedReader(test.max, nil) r := newFixedReader(test.max, nil)
val := test.in val := test.in
if reflect.ValueOf(test.in).Kind() != reflect.Ptr { if reflect.ValueOf(test.in).Kind() != reflect.Ptr {
@@ -233,7 +233,7 @@ func TestElementEncodingErrors(t *testing.T) {
} }
} }
// TestVarIntEncoding tests domainmessage encode and decode for variable length integers. // TestVarIntEncoding tests appmessage encode and decode for variable length integers.
func TestVarIntEncoding(t *testing.T) { func TestVarIntEncoding(t *testing.T) {
tests := []struct { tests := []struct {
value uint64 // Value to encode value uint64 // Value to encode
@@ -266,7 +266,7 @@ func TestVarIntEncoding(t *testing.T) {
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
// Encode to domainmessage format. // Encode to appmessage format.
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
err := WriteVarInt(buf, test.value) err := WriteVarInt(buf, test.value)
if err != nil { if err != nil {
@@ -279,7 +279,7 @@ func TestVarIntEncoding(t *testing.T) {
continue continue
} }
// Decode from domainmessage format. // Decode from appmessage format.
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
val, err := ReadVarInt(rbuf) val, err := ReadVarInt(rbuf)
if err != nil { if err != nil {
@@ -294,7 +294,7 @@ func TestVarIntEncoding(t *testing.T) {
} }
} }
// TestVarIntEncodingErrors performs negative tests against domainmessage encode and decode // TestVarIntEncodingErrors performs negative tests against appmessage encode and decode
// of variable length integers to confirm error paths work correctly. // of variable length integers to confirm error paths work correctly.
func TestVarIntEncodingErrors(t *testing.T) { func TestVarIntEncodingErrors(t *testing.T) {
tests := []struct { tests := []struct {
@@ -319,7 +319,7 @@ func TestVarIntEncodingErrors(t *testing.T) {
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
// Encode to domainmessage format. // Encode to appmessage format.
w := newFixedWriter(test.max) w := newFixedWriter(test.max)
err := WriteVarInt(w, test.in) err := WriteVarInt(w, test.in)
if !errors.Is(err, test.writeErr) { if !errors.Is(err, test.writeErr) {
@@ -328,7 +328,7 @@ func TestVarIntEncodingErrors(t *testing.T) {
continue continue
} }
// Decode from domainmessage format. // Decode from appmessage format.
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
_, err = ReadVarInt(r) _, err = ReadVarInt(r)
if !errors.Is(err, test.readErr) { if !errors.Is(err, test.readErr) {
@@ -347,7 +347,7 @@ func TestVarIntNonCanonical(t *testing.T) {
tests := []struct { tests := []struct {
name string // Test name for easier identification name string // Test name for easier identification
in []byte // Value to decode in []byte // Value to decode
pver uint32 // Protocol version for domainmessage encoding pver uint32 // Protocol version for appmessage encoding
}{ }{
{ {
"0 encoded with 3 bytes", []byte{0xfd, 0x00, 0x00}, "0 encoded with 3 bytes", []byte{0xfd, 0x00, 0x00},
@@ -379,7 +379,7 @@ func TestVarIntNonCanonical(t *testing.T) {
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
// Decode from domainmessage format. // Decode from appmessage format.
rbuf := bytes.NewReader(test.in) rbuf := bytes.NewReader(test.in)
val, err := ReadVarInt(rbuf) val, err := ReadVarInt(rbuf)
if msgErr := &(MessageError{}); !errors.As(err, &msgErr) { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
@@ -430,7 +430,7 @@ func TestVarIntSerializeSize(t *testing.T) {
} }
} }
// TestVarStringEncoding tests domainmessage encode and decode for variable length strings. // TestVarStringEncoding tests appmessage encode and decode for variable length strings.
func TestVarStringEncoding(t *testing.T) { func TestVarStringEncoding(t *testing.T) {
pver := ProtocolVersion pver := ProtocolVersion
@@ -441,7 +441,7 @@ func TestVarStringEncoding(t *testing.T) {
in string // String to encode in string // String to encode
out string // String to decoded value out string // String to decoded value
buf []byte // Encoded value buf []byte // Encoded value
pver uint32 // Protocol version for domainmessage encoding pver uint32 // Protocol version for appmessage encoding
}{ }{
// Latest protocol version. // Latest protocol version.
// Empty string // Empty string
@@ -454,7 +454,7 @@ func TestVarStringEncoding(t *testing.T) {
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
// Encode to domainmessage format. // Encode to appmessage format.
var buf bytes.Buffer var buf bytes.Buffer
err := WriteVarString(&buf, test.in) err := WriteVarString(&buf, test.in)
if err != nil { if err != nil {
@@ -467,7 +467,7 @@ func TestVarStringEncoding(t *testing.T) {
continue continue
} }
// Decode from domainmessage format. // Decode from appmessage format.
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
val, err := ReadVarString(rbuf, test.pver) val, err := ReadVarString(rbuf, test.pver)
if err != nil { if err != nil {
@@ -482,7 +482,7 @@ func TestVarStringEncoding(t *testing.T) {
} }
} }
// TestVarStringEncodingErrors performs negative tests against domainmessage encode and // TestVarStringEncodingErrors performs negative tests against appmessage encode and
// decode of variable length strings to confirm error paths work correctly. // decode of variable length strings to confirm error paths work correctly.
func TestVarStringEncodingErrors(t *testing.T) { func TestVarStringEncodingErrors(t *testing.T) {
pver := ProtocolVersion pver := ProtocolVersion
@@ -493,7 +493,7 @@ func TestVarStringEncodingErrors(t *testing.T) {
tests := []struct { tests := []struct {
in string // Value to encode in string // Value to encode
buf []byte // Encoded value buf []byte // Encoded value
pver uint32 // Protocol version for domainmessage encoding pver uint32 // Protocol version for appmessage encoding
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error writeErr error // Expected write error
readErr error // Expected read error readErr error // Expected read error
@@ -509,7 +509,7 @@ func TestVarStringEncodingErrors(t *testing.T) {
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
// Encode to domainmessage format. // Encode to appmessage format.
w := newFixedWriter(test.max) w := newFixedWriter(test.max)
err := WriteVarString(w, test.in) err := WriteVarString(w, test.in)
if !errors.Is(err, test.writeErr) { if !errors.Is(err, test.writeErr) {
@@ -518,7 +518,7 @@ func TestVarStringEncodingErrors(t *testing.T) {
continue continue
} }
// Decode from domainmessage format. // Decode from appmessage format.
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
_, err = ReadVarString(r, test.pver) _, err = ReadVarString(r, test.pver)
if !errors.Is(err, test.readErr) { if !errors.Is(err, test.readErr) {
@@ -538,7 +538,7 @@ func TestVarStringOverflowErrors(t *testing.T) {
tests := []struct { tests := []struct {
buf []byte // Encoded value buf []byte // Encoded value
pver uint32 // Protocol version for domainmessage encoding pver uint32 // Protocol version for appmessage encoding
err error // Expected error err error // Expected error
}{ }{
{[]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, {[]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
@@ -549,7 +549,7 @@ func TestVarStringOverflowErrors(t *testing.T) {
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
// Decode from domainmessage format. // Decode from appmessage format.
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
_, err := ReadVarString(rbuf, test.pver) _, err := ReadVarString(rbuf, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.err) { if reflect.TypeOf(err) != reflect.TypeOf(test.err) {
@@ -561,7 +561,7 @@ func TestVarStringOverflowErrors(t *testing.T) {
} }
// TestVarBytesEncoding tests domainmessage encode and decode for variable length byte array. // TestVarBytesEncoding tests appmessage encode and decode for variable length byte array.
func TestVarBytesEncoding(t *testing.T) { func TestVarBytesEncoding(t *testing.T) {
pver := ProtocolVersion pver := ProtocolVersion
@@ -571,7 +571,7 @@ func TestVarBytesEncoding(t *testing.T) {
tests := []struct { tests := []struct {
in []byte // Byte Array to write in []byte // Byte Array to write
buf []byte // Encoded value buf []byte // Encoded value
pver uint32 // Protocol version for domainmessage encoding pver uint32 // Protocol version for appmessage encoding
}{ }{
// Latest protocol version. // Latest protocol version.
// Empty byte array // Empty byte array
@@ -584,7 +584,7 @@ func TestVarBytesEncoding(t *testing.T) {
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
// Encode to domainmessage format. // Encode to appmessage format.
var buf bytes.Buffer var buf bytes.Buffer
err := WriteVarBytes(&buf, test.pver, test.in) err := WriteVarBytes(&buf, test.pver, test.in)
if err != nil { if err != nil {
@@ -597,7 +597,7 @@ func TestVarBytesEncoding(t *testing.T) {
continue continue
} }
// Decode from domainmessage format. // Decode from appmessage format.
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
val, err := ReadVarBytes(rbuf, test.pver, MaxMessagePayload, val, err := ReadVarBytes(rbuf, test.pver, MaxMessagePayload,
"test payload") "test payload")
@@ -613,7 +613,7 @@ func TestVarBytesEncoding(t *testing.T) {
} }
} }
// TestVarBytesEncodingErrors performs negative tests against domainmessage encode and // TestVarBytesEncodingErrors performs negative tests against appmessage encode and
// decode of variable length byte arrays to confirm error paths work correctly. // decode of variable length byte arrays to confirm error paths work correctly.
func TestVarBytesEncodingErrors(t *testing.T) { func TestVarBytesEncodingErrors(t *testing.T) {
pver := ProtocolVersion pver := ProtocolVersion
@@ -624,7 +624,7 @@ func TestVarBytesEncodingErrors(t *testing.T) {
tests := []struct { tests := []struct {
in []byte // Byte Array to write in []byte // Byte Array to write
buf []byte // Encoded value buf []byte // Encoded value
pver uint32 // Protocol version for domainmessage encoding pver uint32 // Protocol version for appmessage encoding
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error writeErr error // Expected write error
readErr error // Expected read error readErr error // Expected read error
@@ -640,7 +640,7 @@ func TestVarBytesEncodingErrors(t *testing.T) {
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
// Encode to domainmessage format. // Encode to appmessage format.
w := newFixedWriter(test.max) w := newFixedWriter(test.max)
err := WriteVarBytes(w, test.pver, test.in) err := WriteVarBytes(w, test.pver, test.in)
if !errors.Is(err, test.writeErr) { if !errors.Is(err, test.writeErr) {
@@ -649,7 +649,7 @@ func TestVarBytesEncodingErrors(t *testing.T) {
continue continue
} }
// Decode from domainmessage format. // Decode from appmessage format.
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
_, err = ReadVarBytes(r, test.pver, MaxMessagePayload, _, err = ReadVarBytes(r, test.pver, MaxMessagePayload,
"test payload") "test payload")
@@ -670,7 +670,7 @@ func TestVarBytesOverflowErrors(t *testing.T) {
tests := []struct { tests := []struct {
buf []byte // Encoded value buf []byte // Encoded value
pver uint32 // Protocol version for domainmessage encoding pver uint32 // Protocol version for appmessage encoding
err error // Expected error err error // Expected error
}{ }{
{[]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, {[]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
@@ -681,7 +681,7 @@ func TestVarBytesOverflowErrors(t *testing.T) {
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
// Decode from domainmessage format. // Decode from appmessage format.
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
_, err := ReadVarBytes(rbuf, test.pver, MaxMessagePayload, _, err := ReadVarBytes(rbuf, test.pver, MaxMessagePayload,
"test payload") "test payload")

View File

@@ -1,8 +1,8 @@
/* /*
Package domainmessage implements the kaspa domainmessage protocol. Package appmessage implements the kaspa appmessage protocol.
At a high level, this package provides support for marshalling and unmarshalling At a high level, this package provides support for marshalling and unmarshalling
supported kaspa messages to and from the domainmessage. This package does not deal supported kaspa messages to and from the appmessage. This package does not deal
with the specifics of message handling such as what to do when a message is 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. 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 through channels, functions, etc. In addition, concrete implementations of most
of the currently supported kaspa messages are provided. For these supported of the currently supported kaspa messages are provided. For these supported
messages, all of the details of marshalling and unmarshalling to and from the messages, all of the details of marshalling and unmarshalling to and from the
domainmessage using kaspa encoding are handled so the caller doesn't have to concern appmessage using kaspa encoding are handled so the caller doesn't have to concern
themselves with the specifics. themselves with the specifics.
Message Interaction Message Interaction
@@ -55,7 +55,7 @@ Protocol Version
The protocol version should be negotiated with the remote peer at a higher The protocol version should be negotiated with the remote peer at a higher
level than this package via the version (MsgVersion) message exchange, however, level than this package via the version (MsgVersion) message exchange, however,
this package provides the domainmessage.ProtocolVersion constant which indicates the this package provides the appmessage.ProtocolVersion constant which indicates the
latest protocol version this package supports and is typically the value to use latest protocol version this package supports and is typically the value to use
for all outbound connections before a potentially lower protocol version is for all outbound connections before a potentially lower protocol version is
negotiated. negotiated.
@@ -66,11 +66,10 @@ 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 message and which kaspa network the message applies to. This package provides
the following constants: the following constants:
domainmessage.Mainnet appmessage.Mainnet
domainmessage.Testnet (Test network) appmessage.Testnet (Test network)
domainmessage.Regtest (Regression test network) appmessage.Simnet (Simulation test network)
domainmessage.Simnet (Simulation test network) appmessage.Devnet (Development network)
domainmessage.Devnet (Development network)
Determining Message Type Determining Message Type
@@ -82,43 +81,43 @@ switch or type assertion. An example of a type switch follows:
// Assumes msg is already a valid concrete message such as one created // Assumes msg is already a valid concrete message such as one created
// via NewMsgVersion or read via ReadMessage. // via NewMsgVersion or read via ReadMessage.
switch msg := msg.(type) { switch msg := msg.(type) {
case *domainmessage.MsgVersion: case *appmessage.MsgVersion:
// The message is a pointer to a MsgVersion struct. // The message is a pointer to a MsgVersion struct.
fmt.Printf("Protocol version: %d", msg.ProtocolVersion) fmt.Printf("Protocol version: %d", msg.ProtocolVersion)
case *domainmessage.MsgBlock: case *appmessage.MsgBlock:
// The message is a pointer to a MsgBlock struct. // The message is a pointer to a MsgBlock struct.
fmt.Printf("Number of tx in block: %d", msg.Header.TxnCount) fmt.Printf("Number of tx in block: %d", msg.Header.TxnCount)
} }
Reading Messages Reading Messages
In order to unmarshall kaspa messages from the domainmessage, use the ReadMessage In order to unmarshall kaspa messages from the appmessage, use the ReadMessage
function. It accepts any io.Reader, but typically this will be a net.Conn to 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: a remote node running a kaspa peer. Example syntax is:
// Reads and validates the next kaspa message from conn using the // Reads and validates the next kaspa message from conn using the
// protocol version pver and the kaspa network kaspaNet. The returns // protocol version pver and the kaspa network kaspaNet. The returns
// are a domainmessage.Message, a []byte which contains the unmarshalled // are a appmessage.Message, a []byte which contains the unmarshalled
// raw payload, and a possible error. // raw payload, and a possible error.
msg, rawPayload, err := domainmessage.ReadMessage(conn, pver, kaspaNet) msg, rawPayload, err := appmessage.ReadMessage(conn, pver, kaspaNet)
if err != nil { if err != nil {
// Log and handle the error // Log and handle the error
} }
Writing Messages Writing Messages
In order to marshall kaspa messages to the domainmessage, use the WriteMessage In order to marshall kaspa messages to the appmessage, use the WriteMessage
function. It accepts any io.Writer, but typically this will be a net.Conn to 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 a remote node running a kaspa peer. Example syntax to request addresses
from a remote peer is: from a remote peer is:
// Create a new getaddr kaspa message. // Create a new getaddr kaspa message.
msg := domainmessage.NewMsgRequestAddresses() msg := appmessage.NewMsgRequestAddresses()
// Writes a kaspa message msg to conn using the protocol version // Writes a kaspa message msg to conn using the protocol version
// pver, and the kaspa network kaspaNet. The return is a possible // pver, and the kaspa network kaspaNet. The return is a possible
// error. // error.
err := domainmessage.WriteMessage(conn, msg, pver, kaspaNet) err := appmessage.WriteMessage(conn, msg, pver, kaspaNet)
if err != nil { if err != nil {
// Log and handle the error // Log and handle the error
} }
@@ -127,8 +126,8 @@ Errors
Errors returned by this package are either the raw errors provided by underlying 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 calls to read/write from streams such as io.EOF, io.ErrUnexpectedEOF, and
io.ErrShortWrite, or of type domainmessage.MessageError. This allows the caller to io.ErrShortWrite, or of type appmessage.MessageError. This allows the caller to
differentiate between general IO errors and malformed messages through type differentiate between general IO errors and malformed messages through type
assertions. assertions.
*/ */
package domainmessage package appmessage

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"fmt" "fmt"

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import "io" import "io"
@@ -15,7 +15,7 @@ type fakeMessage struct {
forceLenErr bool forceLenErr bool
} }
// KaspaDecode doesn't do anything. It just satisfies the domainmessage.Message // KaspaDecode doesn't do anything. It just satisfies the appmessage.Message
// interface. // interface.
func (msg *fakeMessage) KaspaDecode(r io.Reader, pver uint32) error { func (msg *fakeMessage) KaspaDecode(r io.Reader, pver uint32) error {
return nil 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 // 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 // if the forceEncodeErr flag of the fake message is set. It also satisfies the
// domainmessage.Message interface. // appmessage.Message interface.
func (msg *fakeMessage) KaspaEncode(w io.Writer, pver uint32) error { func (msg *fakeMessage) KaspaEncode(w io.Writer, pver uint32) error {
if msg.forceEncodeErr { if msg.forceEncodeErr {
err := &MessageError{ err := &MessageError{

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"bytes" "bytes"

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"fmt" "fmt"

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"fmt" "fmt"

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"net" "net"

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"bytes" "bytes"
@@ -60,7 +60,7 @@ func (msg *MsgBlock) ClearTransactions() {
// KaspaDecode decodes r using the kaspa protocol encoding into the receiver. // KaspaDecode decodes r using the kaspa protocol encoding into the receiver.
// This is part of the Message interface implementation. // This is part of the Message interface implementation.
// See Deserialize for decoding blocks stored to disk, such as in a database, as // See Deserialize for decoding blocks stored to disk, such as in a database, as
// opposed to decoding blocks from the domainmessage. // opposed to decoding blocks from the appmessage.
func (msg *MsgBlock) KaspaDecode(r io.Reader, pver uint32) error { func (msg *MsgBlock) KaspaDecode(r io.Reader, pver uint32) error {
err := readBlockHeader(r, pver, &msg.Header) err := readBlockHeader(r, pver, &msg.Header)
if err != nil { if err != nil {
@@ -97,14 +97,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 // 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 // suitable for long-term storage such as a database while respecting the
// Version field in the block. This function differs from KaspaDecode in that // Version field in the block. This function differs from KaspaDecode in that
// KaspaDecode decodes from the kaspa domainmessage protocol as it was sent across the // KaspaDecode decodes from the kaspa appmessage protocol as it was sent across the
// network. The domainmessage encoding can technically differ depending on the protocol // network. The appmessage encoding can technically differ depending on the protocol
// version and doesn't even really need to match the format of a stored block at // 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 // 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 // in both instances, but there is a distinct difference and separating the two
// allows the API to be flexible enough to deal with changes. // allows the API to be flexible enough to deal with changes.
func (msg *MsgBlock) Deserialize(r io.Reader) error { func (msg *MsgBlock) Deserialize(r io.Reader) error {
// At the current time, there is no difference between the domainmessage encoding // At the current time, there is no difference between the appmessage encoding
// at protocol version 0 and the stable long-term storage format. As // at protocol version 0 and the stable long-term storage format. As
// a result, make use of KaspaDecode. // a result, make use of KaspaDecode.
return msg.KaspaDecode(r, 0) return msg.KaspaDecode(r, 0)
@@ -117,9 +117,9 @@ func (msg *MsgBlock) Deserialize(r io.Reader) error {
func (msg *MsgBlock) DeserializeTxLoc(r *bytes.Buffer) ([]TxLoc, error) { func (msg *MsgBlock) DeserializeTxLoc(r *bytes.Buffer) ([]TxLoc, error) {
fullLen := r.Len() fullLen := r.Len()
// At the current time, there is no difference between the domainmessage encoding // At the current time, there is no difference between the appmessage encoding
// at protocol version 0 and the stable long-term storage format. As // at protocol version 0 and the stable long-term storage format. As
// a result, make use of existing domainmessage protocol functions. // a result, make use of existing appmessage protocol functions.
err := readBlockHeader(r, 0, &msg.Header) err := readBlockHeader(r, 0, &msg.Header)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -160,7 +160,7 @@ func (msg *MsgBlock) DeserializeTxLoc(r *bytes.Buffer) ([]TxLoc, error) {
// KaspaEncode encodes the receiver to w using the kaspa protocol encoding. // KaspaEncode encodes the receiver to w using the kaspa protocol encoding.
// This is part of the Message interface implementation. // This is part of the Message interface implementation.
// See Serialize for encoding blocks to be stored to disk, such as in a // See Serialize for encoding blocks to be stored to disk, such as in a
// database, as opposed to encoding blocks for the domainmessage. // database, as opposed to encoding blocks for the appmessage.
func (msg *MsgBlock) KaspaEncode(w io.Writer, pver uint32) error { func (msg *MsgBlock) KaspaEncode(w io.Writer, pver uint32) error {
err := writeBlockHeader(w, pver, &msg.Header) err := writeBlockHeader(w, pver, &msg.Header)
if err != nil { if err != nil {
@@ -185,14 +185,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 // 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. // 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 // This function differs from KaspaEncode in that KaspaEncode encodes the block to
// the kaspa domainmessage protocol in order to be sent across the network. The domainmessage // the kaspa appmessage protocol in order to be sent across the network. The appmessage
// encoding can technically differ depending on the protocol version and doesn't // 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 // 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 // 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 // instances, but there is a distinct difference and separating the two allows
// the API to be flexible enough to deal with changes. // the API to be flexible enough to deal with changes.
func (msg *MsgBlock) Serialize(w io.Writer) error { func (msg *MsgBlock) Serialize(w io.Writer) error {
// At the current time, there is no difference between the domainmessage encoding // At the current time, there is no difference between the appmessage encoding
// at protocol version 0 and the stable long-term storage format. As // at protocol version 0 and the stable long-term storage format. As
// a result, make use of KaspaEncode. // a result, make use of KaspaEncode.
return msg.KaspaEncode(w, 0) return msg.KaspaEncode(w, 0)

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"bytes" "bytes"
@@ -144,7 +144,7 @@ func TestConvertToPartial(t *testing.T) {
} }
} }
// TestBlockEncoding tests the MsgBlock domainmessage encode and decode for various numbers // TestBlockEncoding tests the MsgBlock appmessage encode and decode for various numbers
// of transaction inputs and outputs and protocol versions. // of transaction inputs and outputs and protocol versions.
func TestBlockEncoding(t *testing.T) { func TestBlockEncoding(t *testing.T) {
tests := []struct { tests := []struct {
@@ -152,7 +152,7 @@ func TestBlockEncoding(t *testing.T) {
out *MsgBlock // Expected decoded message out *MsgBlock // Expected decoded message
buf []byte // Encoded value buf []byte // Encoded value
txLocs []TxLoc // Expected transaction locations txLocs []TxLoc // Expected transaction locations
pver uint32 // Protocol version for domainmessage encoding pver uint32 // Protocol version for appmessage encoding
}{ }{
// Latest protocol version. // Latest protocol version.
{ {
@@ -166,7 +166,7 @@ func TestBlockEncoding(t *testing.T) {
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
// Encode the message to domainmessage format. // Encode the message to appmessage format.
var buf bytes.Buffer var buf bytes.Buffer
err := test.in.KaspaEncode(&buf, test.pver) err := test.in.KaspaEncode(&buf, test.pver)
if err != nil { if err != nil {
@@ -179,7 +179,7 @@ func TestBlockEncoding(t *testing.T) {
continue continue
} }
// Decode the message from domainmessage format. // Decode the message from appmessage format.
var msg MsgBlock var msg MsgBlock
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
err = msg.KaspaDecode(rbuf, test.pver) err = msg.KaspaDecode(rbuf, test.pver)
@@ -195,7 +195,7 @@ func TestBlockEncoding(t *testing.T) {
} }
} }
// TestBlockEncodingErrors performs negative tests against domainmessage encode and decode // TestBlockEncodingErrors performs negative tests against appmessage encode and decode
// of MsgBlock to confirm error paths work correctly. // of MsgBlock to confirm error paths work correctly.
func TestBlockEncodingErrors(t *testing.T) { func TestBlockEncodingErrors(t *testing.T) {
pver := ProtocolVersion pver := ProtocolVersion
@@ -203,7 +203,7 @@ func TestBlockEncodingErrors(t *testing.T) {
tests := []struct { tests := []struct {
in *MsgBlock // Value to encode in *MsgBlock // Value to encode
buf []byte // Encoded value buf []byte // Encoded value
pver uint32 // Protocol version for domainmessage encoding pver uint32 // Protocol version for appmessage encoding
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error writeErr error // Expected write error
readErr error // Expected read error readErr error // Expected read error
@@ -236,7 +236,7 @@ func TestBlockEncodingErrors(t *testing.T) {
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
// Encode to domainmessage format. // Encode to appmessage format.
w := newFixedWriter(test.max) w := newFixedWriter(test.max)
err := test.in.KaspaEncode(w, test.pver) err := test.in.KaspaEncode(w, test.pver)
if !errors.Is(err, test.writeErr) { if !errors.Is(err, test.writeErr) {
@@ -245,7 +245,7 @@ func TestBlockEncodingErrors(t *testing.T) {
continue continue
} }
// Decode from domainmessage format. // Decode from appmessage format.
var msg MsgBlock var msg MsgBlock
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
err = msg.KaspaDecode(r, test.pver) err = msg.KaspaDecode(r, test.pver)
@@ -324,7 +324,7 @@ func TestBlockSerialize(t *testing.T) {
} }
} }
// TestBlockSerializeErrors performs negative tests against domainmessage encode and // TestBlockSerializeErrors performs negative tests against appmessage encode and
// decode of MsgBlock to confirm error paths work correctly. // decode of MsgBlock to confirm error paths work correctly.
func TestBlockSerializeErrors(t *testing.T) { func TestBlockSerializeErrors(t *testing.T) {
tests := []struct { tests := []struct {
@@ -401,7 +401,7 @@ func TestBlockOverflowErrors(t *testing.T) {
tests := []struct { tests := []struct {
buf []byte // Encoded value buf []byte // Encoded value
pver uint32 // Protocol version for domainmessage encoding pver uint32 // Protocol version for appmessage encoding
err error // Expected error err error // Expected error
}{ }{
// Block that claims to have ~uint64(0) transactions. // Block that claims to have ~uint64(0) transactions.
@@ -431,7 +431,7 @@ func TestBlockOverflowErrors(t *testing.T) {
0x65, 0x9C, 0x79, 0x3C, 0xE3, 0x70, 0xD9, 0x5F, 0x65, 0x9C, 0x79, 0x3C, 0xE3, 0x70, 0xD9, 0x5F,
0x61, 0xbc, 0x66, 0x49, 0x00, 0x00, 0x00, 0x00, // Timestamp 0x61, 0xbc, 0x66, 0x49, 0x00, 0x00, 0x00, 0x00, // Timestamp
0xff, 0xff, 0x00, 0x1d, // Bits 0xff, 0xff, 0x00, 0x1d, // Bits
0x01, 0xe3, 0x62, 0x99, 0x00, 0x00, 0x00, 0x00, // Fake Nonce. TODO: (Ori) Replace to a real nonce 0x01, 0xe3, 0x62, 0x99, 0x00, 0x00, 0x00, 0x00, // Fake Nonce
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, // TxnCount 0xff, // TxnCount
}, pver, &MessageError{}, }, pver, &MessageError{},
@@ -440,7 +440,7 @@ func TestBlockOverflowErrors(t *testing.T) {
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
// Decode from domainmessage format. // Decode from appmessage format.
var msg MsgBlock var msg MsgBlock
r := bytes.NewReader(test.buf) r := bytes.NewReader(test.buf)
err := msg.KaspaDecode(r, test.pver) err := msg.KaspaDecode(r, test.pver)
@@ -450,7 +450,7 @@ func TestBlockOverflowErrors(t *testing.T) {
continue continue
} }
// Deserialize from domainmessage format. // Deserialize from appmessage format.
r = bytes.NewReader(test.buf) r = bytes.NewReader(test.buf)
err = msg.Deserialize(r) err = msg.Deserialize(r)
if reflect.TypeOf(err) != reflect.TypeOf(test.err) { if reflect.TypeOf(err) != reflect.TypeOf(test.err) {
@@ -459,7 +459,7 @@ func TestBlockOverflowErrors(t *testing.T) {
continue continue
} }
// Deserialize with transaction location info from domainmessage format. // Deserialize with transaction location info from appmessage format.
br := bytes.NewBuffer(test.buf) br := bytes.NewBuffer(test.buf)
_, err = msg.DeserializeTxLoc(br) _, err = msg.DeserializeTxLoc(br)
if reflect.TypeOf(err) != reflect.TypeOf(test.err) { if reflect.TypeOf(err) != reflect.TypeOf(test.err) {
@@ -572,7 +572,7 @@ var blockOneBytes = []byte{
0x65, 0x9C, 0x79, 0x3C, 0xE3, 0x70, 0xD9, 0x5F, 0x65, 0x9C, 0x79, 0x3C, 0xE3, 0x70, 0xD9, 0x5F,
0x99, 0x0f, 0xed, 0x15, 0x73, 0x01, 0x00, 0x00, // Timestamp 0x99, 0x0f, 0xed, 0x15, 0x73, 0x01, 0x00, 0x00, // Timestamp
0xff, 0xff, 0x00, 0x1d, // Bits 0xff, 0xff, 0x00, 0x1d, // Bits
0x01, 0xe3, 0x62, 0x99, 0x00, 0x00, 0x00, 0x00, // Fake Nonce. TODO: (Ori) Replace to a real nonce 0x01, 0xe3, 0x62, 0x99, 0x00, 0x00, 0x00, 0x00, // Fake Nonce
0x01, // TxnCount 0x01, // TxnCount
0x01, 0x00, 0x00, 0x00, // Version 0x01, 0x00, 0x00, 0x00, // Version
0x01, // Varint for number of transaction inputs 0x01, // Varint for number of transaction inputs

View File

@@ -1,4 +1,4 @@
package domainmessage package appmessage
import ( import (
"github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/daghash"

View File

@@ -1,4 +1,4 @@
package domainmessage package appmessage
import ( import (
"testing" "testing"

View File

@@ -1,4 +1,4 @@
package domainmessage package appmessage
// MsgDoneIBDBlocks implements the Message interface and represents a kaspa // MsgDoneIBDBlocks implements the Message interface and represents a kaspa
// DoneIBDBlocks message. It is used to notify the IBD syncing peer that the // DoneIBDBlocks message. It is used to notify the IBD syncing peer that the

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
// MsgIBDBlock implements the Message interface and represents a kaspa // MsgIBDBlock implements the Message interface and represents a kaspa
// ibdblock message. It is used to deliver block and transaction information in // ibdblock message. It is used to deliver block and transaction information in

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"bytes" "bytes"
@@ -65,7 +65,7 @@ func TestIBDBlock(t *testing.T) {
} }
} }
// TestIBDBlockEncoding tests the MsgIBDBlock domainmessage encode and decode for various numbers // TestIBDBlockEncoding tests the MsgIBDBlock appmessage encode and decode for various numbers
// of transaction inputs and outputs and protocol versions. // of transaction inputs and outputs and protocol versions.
func TestIBDBlockEncoding(t *testing.T) { func TestIBDBlockEncoding(t *testing.T) {
tests := []struct { tests := []struct {
@@ -73,7 +73,7 @@ func TestIBDBlockEncoding(t *testing.T) {
out *MsgIBDBlock // Expected decoded message out *MsgIBDBlock // Expected decoded message
buf []byte // Encoded value buf []byte // Encoded value
txLocs []TxLoc // Expected transaction locations txLocs []TxLoc // Expected transaction locations
pver uint32 // Protocol version for domainmessage encoding pver uint32 // Protocol version for appmessage encoding
}{ }{
// Latest protocol version. // Latest protocol version.
{ {
@@ -87,7 +87,7 @@ func TestIBDBlockEncoding(t *testing.T) {
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
// Encode the message to domainmessage format. // Encode the message to appmessage format.
var buf bytes.Buffer var buf bytes.Buffer
err := test.in.KaspaEncode(&buf, test.pver) err := test.in.KaspaEncode(&buf, test.pver)
if err != nil { if err != nil {
@@ -100,7 +100,7 @@ func TestIBDBlockEncoding(t *testing.T) {
continue continue
} }
// Decode the message from domainmessage format. // Decode the message from appmessage format.
var msg MsgIBDBlock var msg MsgIBDBlock
msg.MsgBlock = new(MsgBlock) msg.MsgBlock = new(MsgBlock)
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)

View File

@@ -1,4 +1,4 @@
package domainmessage package appmessage
import ( import (
"github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/daghash"

View File

@@ -1,4 +1,4 @@
package domainmessage package appmessage
import ( import (
"github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/daghash"

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
// MsgPing implements the Message interface and represents a kaspa ping // MsgPing implements the Message interface and represents a kaspa ping
// message. // message.

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"testing" "testing"

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
// MsgPong implements the Message interface and represents a kaspa pong // MsgPong implements the Message interface and represents a kaspa pong
// message which is used primarily to confirm that a connection is still valid // message which is used primarily to confirm that a connection is still valid

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"testing" "testing"

View File

@@ -1,4 +1,4 @@
package domainmessage package appmessage
// MsgReject implements the Message interface and represents a kaspa // MsgReject implements the Message interface and represents a kaspa
// Reject message. It is used to notify peers why they are banned. // Reject message. It is used to notify peers why they are banned.

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"github.com/kaspanet/kaspad/util/subnetworkid" "github.com/kaspanet/kaspad/util/subnetworkid"

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"testing" "testing"

View File

@@ -1,4 +1,4 @@
package domainmessage package appmessage
import ( import (
"github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/daghash"

View File

@@ -1,4 +1,4 @@
package domainmessage package appmessage
import ( import (
"testing" "testing"

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/daghash"

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"testing" "testing"

View File

@@ -1,4 +1,4 @@
package domainmessage package appmessage
// MsgRequestNextIBDBlocks implements the Message interface and represents a kaspa // MsgRequestNextIBDBlocks implements the Message interface and represents a kaspa
// RequestNextIBDBlocks message. It is used to notify the IBD syncer peer to send // RequestNextIBDBlocks message. It is used to notify the IBD syncer peer to send

View File

@@ -1,4 +1,4 @@
package domainmessage package appmessage
import ( import (
"github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/daghash"

View File

@@ -1,4 +1,4 @@
package domainmessage package appmessage
// MsgRequestSelectedTip implements the Message interface and represents a kaspa // MsgRequestSelectedTip implements the Message interface and represents a kaspa
// RequestSelectedTip message. It is used to request the selected tip of another peer. // RequestSelectedTip message. It is used to request the selected tip of another peer.

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"testing" "testing"

View File

@@ -1,4 +1,4 @@
package domainmessage package appmessage
import ( import (
"github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/daghash"

View File

@@ -1,4 +1,4 @@
package domainmessage package appmessage
import ( import (
"github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/daghash"

View File

@@ -1,4 +1,4 @@
package domainmessage package appmessage
import ( import (
"github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/daghash"

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/daghash"

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"encoding/binary" "encoding/binary"
@@ -83,7 +83,7 @@ const (
minTxPayload = 10 minTxPayload = 10
// freeListMaxScriptSize is the size of each buffer in the free list // freeListMaxScriptSize is the size of each buffer in the free list
// that is used for deserializing scripts from the domainmessage before they are // that is used for deserializing scripts from the appmessage before they are
// concatenated into a single contiguous buffers. This value was chosen // concatenated into a single contiguous buffers. This value was chosen
// because it is slightly more than twice the size of the vast majority // because it is slightly more than twice the size of the vast majority
// of all "standard" scripts. Larger scripts are still deserialized // of all "standard" scripts. Larger scripts are still deserialized
@@ -406,7 +406,7 @@ func (msg *MsgTx) Copy() *MsgTx {
// KaspaDecode decodes r using the kaspa protocol encoding into the receiver. // KaspaDecode decodes r using the kaspa protocol encoding into the receiver.
// This is part of the Message interface implementation. // This is part of the Message interface implementation.
// See Deserialize for decoding transactions stored to disk, such as in a // See Deserialize for decoding transactions stored to disk, such as in a
// database, as opposed to decoding transactions from the domainmessage. // database, as opposed to decoding transactions from the appmessage.
func (msg *MsgTx) KaspaDecode(r io.Reader, pver uint32) error { func (msg *MsgTx) KaspaDecode(r io.Reader, pver uint32) error {
version, err := binaryserializer.Uint32(r, littleEndian) version, err := binaryserializer.Uint32(r, littleEndian)
if err != nil { if err != nil {
@@ -596,15 +596,15 @@ func (msg *MsgTx) KaspaDecode(r io.Reader, pver uint32) error {
// Deserialize decodes a transaction from r into the receiver using a format // 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 // that is suitable for long-term storage such as a database while respecting
// the Version field in the transaction. This function differs from KaspaDecode // the Version field in the transaction. This function differs from KaspaDecode
// in that KaspaDecode decodes from the kaspa domainmessage protocol as it was sent // in that KaspaDecode decodes from the kaspa appmessage protocol as it was sent
// across the network. The domainmessage encoding can technically differ depending on // across the network. The appmessage encoding can technically differ depending on
// the protocol version and doesn't even really need to match the format of a // 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 // 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 // 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 // difference and separating the two allows the API to be flexible enough to
// deal with changes. // deal with changes.
func (msg *MsgTx) Deserialize(r io.Reader) error { func (msg *MsgTx) Deserialize(r io.Reader) error {
// At the current time, there is no difference between the domainmessage encoding // At the current time, there is no difference between the appmessage encoding
// at protocol version 0 and the stable long-term storage format. As // at protocol version 0 and the stable long-term storage format. As
// a result, make use of KaspaDecode. // a result, make use of KaspaDecode.
return msg.KaspaDecode(r, 0) return msg.KaspaDecode(r, 0)
@@ -613,7 +613,7 @@ func (msg *MsgTx) Deserialize(r io.Reader) error {
// KaspaEncode encodes the receiver to w using the kaspa protocol encoding. // KaspaEncode encodes the receiver to w using the kaspa protocol encoding.
// This is part of the Message interface implementation. // This is part of the Message interface implementation.
// See Serialize for encoding transactions to be stored to disk, such as in a // See Serialize for encoding transactions to be stored to disk, such as in a
// database, as opposed to encoding transactions for the domainmessage. // database, as opposed to encoding transactions for the appmessage.
func (msg *MsgTx) KaspaEncode(w io.Writer, pver uint32) error { func (msg *MsgTx) KaspaEncode(w io.Writer, pver uint32) error {
return msg.encode(w, pver, txEncodingFull) return msg.encode(w, pver, txEncodingFull)
} }
@@ -702,22 +702,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 // 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 // long-term storage such as a database while respecting the Version field in
// the transaction. This function differs from KaspaEncode in that KaspaEncode // the transaction. This function differs from KaspaEncode in that KaspaEncode
// encodes the transaction to the kaspa domainmessage protocol in order to be sent // encodes the transaction to the kaspa appmessage protocol in order to be sent
// across the network. The domainmessage encoding can technically differ depending on // across the network. The appmessage encoding can technically differ depending on
// the protocol version and doesn't even really need to match the format of a // 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 // 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 // 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 // difference and separating the two allows the API to be flexible enough to
// deal with changes. // deal with changes.
func (msg *MsgTx) Serialize(w io.Writer) error { func (msg *MsgTx) Serialize(w io.Writer) error {
// At the current time, there is no difference between the domainmessage encoding // At the current time, there is no difference between the appmessage encoding
// at protocol version 0 and the stable long-term storage format. As // at protocol version 0 and the stable long-term storage format. As
// a result, make use of KaspaEncode. // a result, make use of KaspaEncode.
return msg.KaspaEncode(w, 0) return msg.KaspaEncode(w, 0)
} }
func (msg *MsgTx) serialize(w io.Writer, encodingFlags txEncoding) error { func (msg *MsgTx) serialize(w io.Writer, encodingFlags txEncoding) error {
// At the current time, there is no difference between the domainmessage encoding // At the current time, there is no difference between the appmessage encoding
// at protocol version 0 and the stable long-term storage format. As // at protocol version 0 and the stable long-term storage format. As
// a result, make use of `encode`. // a result, make use of `encode`.
return msg.encode(w, 0, encodingFlags) return msg.encode(w, 0, encodingFlags)

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"bytes" "bytes"
@@ -253,7 +253,7 @@ func TestTxHashAndID(t *testing.T) {
} }
} }
// TestTxEncoding tests the MsgTx domainmessage encode and decode for various numbers // TestTxEncoding tests the MsgTx appmessage encode and decode for various numbers
// of transaction inputs and outputs and protocol versions. // of transaction inputs and outputs and protocol versions.
func TestTxEncoding(t *testing.T) { func TestTxEncoding(t *testing.T) {
// Empty tx message. // Empty tx message.
@@ -272,7 +272,7 @@ func TestTxEncoding(t *testing.T) {
in *MsgTx // Message to encode in *MsgTx // Message to encode
out *MsgTx // Expected decoded message out *MsgTx // Expected decoded message
buf []byte // Encoded value buf []byte // Encoded value
pver uint32 // Protocol version for domainmessage encoding pver uint32 // Protocol version for appmessage encoding
}{ }{
// Latest protocol version with no transactions. // Latest protocol version with no transactions.
{ {
@@ -293,7 +293,7 @@ func TestTxEncoding(t *testing.T) {
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
// Encode the message to domainmessage format. // Encode the message to appmessage format.
var buf bytes.Buffer var buf bytes.Buffer
err := test.in.KaspaEncode(&buf, test.pver) err := test.in.KaspaEncode(&buf, test.pver)
if err != nil { if err != nil {
@@ -306,7 +306,7 @@ func TestTxEncoding(t *testing.T) {
continue continue
} }
// Decode the message from domainmessage format. // Decode the message from appmessage format.
var msg MsgTx var msg MsgTx
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
err = msg.KaspaDecode(rbuf, test.pver) err = msg.KaspaDecode(rbuf, test.pver)
@@ -322,7 +322,7 @@ func TestTxEncoding(t *testing.T) {
} }
} }
// TestTxEncodingErrors performs negative tests against domainmessage encode and decode // TestTxEncodingErrors performs negative tests against appmessage encode and decode
// of MsgTx to confirm error paths work correctly. // of MsgTx to confirm error paths work correctly.
func TestTxEncodingErrors(t *testing.T) { func TestTxEncodingErrors(t *testing.T) {
pver := ProtocolVersion pver := ProtocolVersion
@@ -330,7 +330,7 @@ func TestTxEncodingErrors(t *testing.T) {
tests := []struct { tests := []struct {
in *MsgTx // Value to encode in *MsgTx // Value to encode
buf []byte // Encoded value buf []byte // Encoded value
pver uint32 // Protocol version for domainmessage encoding pver uint32 // Protocol version for appmessage encoding
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error writeErr error // Expected write error
readErr error // Expected read error readErr error // Expected read error
@@ -363,7 +363,7 @@ func TestTxEncodingErrors(t *testing.T) {
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
// Encode to domainmessage format. // Encode to appmessage format.
w := newFixedWriter(test.max) w := newFixedWriter(test.max)
err := test.in.KaspaEncode(w, test.pver) err := test.in.KaspaEncode(w, test.pver)
if !errors.Is(err, test.writeErr) { if !errors.Is(err, test.writeErr) {
@@ -372,7 +372,7 @@ func TestTxEncodingErrors(t *testing.T) {
continue continue
} }
// Decode from domainmessage format. // Decode from appmessage format.
var msg MsgTx var msg MsgTx
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
err = msg.KaspaDecode(r, test.pver) err = msg.KaspaDecode(r, test.pver)
@@ -528,7 +528,7 @@ func TestTxSerialize(t *testing.T) {
} }
} }
// TestTxSerializeErrors performs negative tests against domainmessage encode and decode // TestTxSerializeErrors performs negative tests against appmessage encode and decode
// of MsgTx to confirm error paths work correctly. // of MsgTx to confirm error paths work correctly.
func TestTxSerializeErrors(t *testing.T) { func TestTxSerializeErrors(t *testing.T) {
tests := []struct { tests := []struct {
@@ -629,7 +629,7 @@ func TestTxOverflowErrors(t *testing.T) {
tests := []struct { tests := []struct {
buf []byte // Encoded value buf []byte // Encoded value
pver uint32 // Protocol version for domainmessage encoding pver uint32 // Protocol version for appmessage encoding
version uint32 // Transaction version version uint32 // Transaction version
err error // Expected error err error // Expected error
}{ }{
@@ -691,7 +691,7 @@ func TestTxOverflowErrors(t *testing.T) {
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
// Decode from domainmessage format. // Decode from appmessage format.
var msg MsgTx var msg MsgTx
r := bytes.NewReader(test.buf) r := bytes.NewReader(test.buf)
err := msg.KaspaDecode(r, test.pver) err := msg.KaspaDecode(r, test.pver)
@@ -701,7 +701,7 @@ func TestTxOverflowErrors(t *testing.T) {
continue continue
} }
// Decode from domainmessage format. // Decode from appmessage format.
r = bytes.NewReader(test.buf) r = bytes.NewReader(test.buf)
err = msg.Deserialize(r) err = msg.Deserialize(r)
if reflect.TypeOf(err) != reflect.TypeOf(test.err) { if reflect.TypeOf(err) != reflect.TypeOf(test.err) {
@@ -891,7 +891,7 @@ var multiTxOuts = []*TxOut{
} }
var multiTx = NewNativeMsgTx(1, multiTxIns, multiTxOuts) var multiTx = NewNativeMsgTx(1, multiTxIns, multiTxOuts)
// multiTxEncoded is the domainmessage encoded bytes for multiTx using protocol version // multiTxEncoded is the appmessage encoded bytes for multiTx using protocol version
// 60002 and is used in the various tests. // 60002 and is used in the various tests.
var multiTxEncoded = []byte{ var multiTxEncoded = []byte{
0x01, 0x00, 0x00, 0x00, // Version 0x01, 0x00, 0x00, 0x00, // Version

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
// MsgVerAck defines a kaspa verack message which is used for a peer to // MsgVerAck defines a kaspa verack message which is used for a peer to
// acknowledge a version message (MsgVersion) after it has used the information // acknowledge a version message (MsgVersion) after it has used the information

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"testing" "testing"

View File

@@ -2,14 +2,14 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"fmt" "fmt"
"github.com/kaspanet/kaspad/version" "github.com/kaspanet/kaspad/version"
"strings" "strings"
"github.com/kaspanet/kaspad/network/netadapter/id" "github.com/kaspanet/kaspad/infrastructure/network/netadapter/id"
"github.com/kaspanet/kaspad/util/mstime" "github.com/kaspanet/kaspad/util/mstime"
"github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/daghash"
@@ -20,7 +20,7 @@ import (
// version message (MsgVersion). // version message (MsgVersion).
const MaxUserAgentLen = 256 const MaxUserAgentLen = 256
// DefaultUserAgent for domainmessage in the stack // DefaultUserAgent for appmessage in the stack
var DefaultUserAgent = fmt.Sprintf("/kaspad:%s/", version.Version()) var DefaultUserAgent = fmt.Sprintf("/kaspad:%s/", version.Version())
// MsgVersion implements the Message interface and represents a kaspa version // MsgVersion implements the Message interface and represents a kaspa version
@@ -41,7 +41,7 @@ type MsgVersion struct {
// Bitfield which identifies the enabled services. // Bitfield which identifies the enabled services.
Services ServiceFlag Services ServiceFlag
// Time the message was generated. This is encoded as an int64 on the domainmessage. // Time the message was generated. This is encoded as an int64 on the appmessage.
Timestamp mstime.Time Timestamp mstime.Time
// Address of the local peer. // Address of the local peer.
@@ -51,7 +51,7 @@ type MsgVersion struct {
ID *id.ID ID *id.ID
// The user agent that generated messsage. This is a encoded as a varString // The user agent that generated messsage. This is a encoded as a varString
// on the domainmessage. This has a max length of MaxUserAgentLen. // on the appmessage. This has a max length of MaxUserAgentLen.
UserAgent string UserAgent string
// The selected tip hash of the generator of the version message. // The selected tip hash of the generator of the version message.

View File

@@ -2,11 +2,11 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
"github.com/kaspanet/kaspad/network/netadapter/id" "github.com/kaspanet/kaspad/infrastructure/network/netadapter/id"
"github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/daghash"
"net" "net"
"reflect" "reflect"

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"github.com/kaspanet/kaspad/util/mstime" "github.com/kaspanet/kaspad/util/mstime"
@@ -21,7 +21,7 @@ type NetAddress struct {
// IP address of the peer. // IP address of the peer.
IP net.IP IP net.IP
// Port the peer is using. This is encoded in big endian on the domainmessage // Port the peer is using. This is encoded in big endian on the appmessage
// which differs from most everything else. // which differs from most everything else.
Port uint16 Port uint16
} }

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"net" "net"

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import ( import (
"fmt" "fmt"
@@ -10,10 +10,13 @@ import (
"strings" "strings"
) )
// XXX pedro: we will probably need to bump this.
const ( const (
// ProtocolVersion is the latest protocol version this package supports. // ProtocolVersion is the latest protocol version this package supports.
ProtocolVersion uint32 = 1 ProtocolVersion uint32 = 1
// DefaultServices describes the default services that are supported by
// the server.
DefaultServices = SFNodeNetwork | SFNodeBloom | SFNodeCF
) )
// ServiceFlag identifies services supported by a kaspa peer. // ServiceFlag identifies services supported by a kaspa peer.
@@ -103,9 +106,6 @@ const (
// Testnet represents the test network. // Testnet represents the test network.
Testnet KaspaNet = 0xddb8af8f Testnet KaspaNet = 0xddb8af8f
// Regtest represents the regression test network.
Regtest KaspaNet = 0xf396cdd6
// Simnet represents the simulation test network. // Simnet represents the simulation test network.
Simnet KaspaNet = 0x374dcf1c Simnet KaspaNet = 0x374dcf1c
@@ -118,7 +118,6 @@ const (
var bnStrings = map[KaspaNet]string{ var bnStrings = map[KaspaNet]string{
Mainnet: "Mainnet", Mainnet: "Mainnet",
Testnet: "Testnet", Testnet: "Testnet",
Regtest: "Regtest",
Simnet: "Simnet", Simnet: "Simnet",
Devnet: "Devnet", Devnet: "Devnet",
} }

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package domainmessage package appmessage
import "testing" import "testing"
@@ -40,7 +40,6 @@ func TestKaspaNetStringer(t *testing.T) {
want string want string
}{ }{
{Mainnet, "Mainnet"}, {Mainnet, "Mainnet"},
{Regtest, "Regtest"},
{Testnet, "Testnet"}, {Testnet, "Testnet"},
{Simnet, "Simnet"}, {Simnet, "Simnet"},
{0xffffffff, "Unknown KaspaNet (4294967295)"}, {0xffffffff, "Unknown KaspaNet (4294967295)"},

View File

@@ -1,7 +1,7 @@
package flowcontext package flowcontext
import ( import (
"github.com/kaspanet/kaspad/network/addressmanager" "github.com/kaspanet/kaspad/infrastructure/network/addressmanager"
) )
// AddressManager returns the address manager associated to the flow context. // AddressManager returns the address manager associated to the flow context.

View File

@@ -3,9 +3,9 @@ package flowcontext
import ( import (
"sync/atomic" "sync/atomic"
"github.com/kaspanet/kaspad/app/appmessage"
"github.com/kaspanet/kaspad/app/protocol/flows/blockrelay"
"github.com/kaspanet/kaspad/domain/blockdag" "github.com/kaspanet/kaspad/domain/blockdag"
"github.com/kaspanet/kaspad/network/domainmessage"
"github.com/kaspanet/kaspad/network/protocol/flows/blockrelay"
"github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util"
"github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/daghash"
) )
@@ -39,16 +39,18 @@ func (f *FlowContext) broadcastTransactionsAfterBlockAdded(block *util.Block, tr
for i, tx := range transactionsAcceptedToMempool { for i, tx := range transactionsAcceptedToMempool {
txIDsToBroadcast[i] = tx.ID() txIDsToBroadcast[i] = tx.ID()
} }
offset := len(transactionsAcceptedToMempool)
copy(txIDsToBroadcast[len(transactionsAcceptedToMempool):], txIDsToBroadcast) for i, txID := range txIDsToRebroadcast {
txIDsToBroadcast[offset+i] = txID
}
if len(txIDsToBroadcast) == 0 { if len(txIDsToBroadcast) == 0 {
return nil return nil
} }
if len(txIDsToBroadcast) > domainmessage.MaxInvPerTxInvMsg { if len(txIDsToBroadcast) > appmessage.MaxInvPerTxInvMsg {
txIDsToBroadcast = txIDsToBroadcast[:domainmessage.MaxInvPerTxInvMsg] txIDsToBroadcast = txIDsToBroadcast[:appmessage.MaxInvPerTxInvMsg]
} }
inv := domainmessage.NewMsgInvTransaction(txIDsToBroadcast) inv := appmessage.NewMsgInvTransaction(txIDsToBroadcast)
return f.Broadcast(inv) return f.Broadcast(inv)
} }
@@ -64,5 +66,9 @@ func (f *FlowContext) AddBlock(block *util.Block, flags blockdag.BehaviorFlags)
if err != nil { if err != nil {
return err return err
} }
return f.Broadcast(domainmessage.NewMsgInvBlock(block.Hash())) err = f.OnNewBlock(block)
if err != nil {
return err
}
return f.Broadcast(appmessage.NewMsgInvBlock(block.Hash()))
} }

View File

@@ -0,0 +1,31 @@
package flowcontext
import (
"errors"
"sync/atomic"
"github.com/kaspanet/kaspad/infrastructure/network/netadapter/router"
"github.com/kaspanet/kaspad/app/protocol/protocolerrors"
)
// HandleError handles an error from a flow,
// It sends the error to errChan if isStopping == 0 and increments isStopping
//
// If this is ErrRouteClosed - forward it to errChan
// If this is ProtocolError - logs the error, and forward it to errChan
// Otherwise - panics
func (*FlowContext) HandleError(err error, flowName string, isStopping *uint32, errChan chan<- error) {
isErrRouteClosed := errors.Is(err, router.ErrRouteClosed)
if !isErrRouteClosed {
if protocolErr := &(protocolerrors.ProtocolError{}); !errors.As(err, &protocolErr) {
panic(err)
}
log.Errorf("error from %s: %s", flowName, err)
}
if atomic.AddUint32(isStopping, 1) == 1 {
errChan <- err
}
}

View File

@@ -4,16 +4,16 @@ import (
"sync" "sync"
"time" "time"
"github.com/kaspanet/kaspad/app/protocol/flows/blockrelay"
"github.com/kaspanet/kaspad/app/protocol/flows/relaytransactions"
peerpkg "github.com/kaspanet/kaspad/app/protocol/peer"
"github.com/kaspanet/kaspad/domain/blockdag" "github.com/kaspanet/kaspad/domain/blockdag"
"github.com/kaspanet/kaspad/domain/mempool" "github.com/kaspanet/kaspad/domain/mempool"
"github.com/kaspanet/kaspad/infrastructure/config" "github.com/kaspanet/kaspad/infrastructure/config"
"github.com/kaspanet/kaspad/network/addressmanager" "github.com/kaspanet/kaspad/infrastructure/network/addressmanager"
"github.com/kaspanet/kaspad/network/connmanager" "github.com/kaspanet/kaspad/infrastructure/network/connmanager"
"github.com/kaspanet/kaspad/network/netadapter" "github.com/kaspanet/kaspad/infrastructure/network/netadapter"
"github.com/kaspanet/kaspad/network/netadapter/id" "github.com/kaspanet/kaspad/infrastructure/network/netadapter/id"
"github.com/kaspanet/kaspad/network/protocol/flows/blockrelay"
"github.com/kaspanet/kaspad/network/protocol/flows/relaytransactions"
peerpkg "github.com/kaspanet/kaspad/network/protocol/peer"
"github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util"
"github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/daghash"
) )
@@ -39,7 +39,7 @@ type FlowContext struct {
startIBDMutex sync.Mutex startIBDMutex sync.Mutex
ibdPeer *peerpkg.Peer ibdPeer *peerpkg.Peer
peers map[*id.ID]*peerpkg.Peer peers map[id.ID]*peerpkg.Peer
peersMutex sync.RWMutex peersMutex sync.RWMutex
} }
@@ -57,7 +57,7 @@ func New(cfg *config.Config, dag *blockdag.BlockDAG, addressManager *addressmana
txPool: txPool, txPool: txPool,
sharedRequestedTransactions: relaytransactions.NewSharedRequestedTransactions(), sharedRequestedTransactions: relaytransactions.NewSharedRequestedTransactions(),
sharedRequestedBlocks: blockrelay.NewSharedRequestedBlocks(), sharedRequestedBlocks: blockrelay.NewSharedRequestedBlocks(),
peers: make(map[*id.ID]*peerpkg.Peer), peers: make(map[id.ID]*peerpkg.Peer),
transactionsToRebroadcast: make(map[daghash.TxID]*util.Tx), transactionsToRebroadcast: make(map[daghash.TxID]*util.Tx),
} }
} }

View File

@@ -4,8 +4,8 @@ import (
"sync/atomic" "sync/atomic"
"time" "time"
peerpkg "github.com/kaspanet/kaspad/app/protocol/peer"
"github.com/kaspanet/kaspad/domain/blockdag" "github.com/kaspanet/kaspad/domain/blockdag"
peerpkg "github.com/kaspanet/kaspad/network/protocol/peer"
) )
// StartIBDIfRequired selects a peer and starts IBD against it // StartIBDIfRequired selects a peer and starts IBD against it
@@ -37,6 +37,9 @@ func (f *FlowContext) IsInIBD() bool {
// selectPeerForIBD returns the first peer whose selected tip // selectPeerForIBD returns the first peer whose selected tip
// hash is not in our DAG // hash is not in our DAG
func (f *FlowContext) selectPeerForIBD(dag *blockdag.BlockDAG) *peerpkg.Peer { func (f *FlowContext) selectPeerForIBD(dag *blockdag.BlockDAG) *peerpkg.Peer {
f.peersMutex.RLock()
defer f.peersMutex.RUnlock()
for _, peer := range f.peers { for _, peer := range f.peers {
peerSelectedTipHash := peer.SelectedTipHash() peerSelectedTipHash := peer.SelectedTipHash()
if !dag.IsInDAG(peerSelectedTipHash) { if !dag.IsInDAG(peerSelectedTipHash) {
@@ -59,6 +62,9 @@ func (f *FlowContext) isDAGTimeCurrent() bool {
} }
func (f *FlowContext) requestSelectedTips() { func (f *FlowContext) requestSelectedTips() {
f.peersMutex.RLock()
defer f.peersMutex.RUnlock()
for _, peer := range f.peers { for _, peer := range f.peers {
peer.RequestSelectedTipIfRequired() peer.RequestSelectedTipIfRequired()
} }

View File

@@ -1,11 +1,11 @@
package flowcontext package flowcontext
import ( import (
"github.com/kaspanet/kaspad/network/connmanager" "github.com/kaspanet/kaspad/app/appmessage"
"github.com/kaspanet/kaspad/network/domainmessage" "github.com/kaspanet/kaspad/app/protocol/common"
"github.com/kaspanet/kaspad/network/netadapter" peerpkg "github.com/kaspanet/kaspad/app/protocol/peer"
"github.com/kaspanet/kaspad/network/protocol/common" "github.com/kaspanet/kaspad/infrastructure/network/connmanager"
peerpkg "github.com/kaspanet/kaspad/network/protocol/peer" "github.com/kaspanet/kaspad/infrastructure/network/netadapter"
"github.com/pkg/errors" "github.com/pkg/errors"
) )
@@ -24,15 +24,23 @@ func (f *FlowContext) AddToPeers(peer *peerpkg.Peer) error {
f.peersMutex.Lock() f.peersMutex.Lock()
defer f.peersMutex.Unlock() defer f.peersMutex.Unlock()
if _, ok := f.peers[peer.ID()]; ok { if _, ok := f.peers[*peer.ID()]; ok {
return errors.Wrapf(common.ErrPeerWithSameIDExists, "peer with ID %s already exists", peer.ID()) return errors.Wrapf(common.ErrPeerWithSameIDExists, "peer with ID %s already exists", peer.ID())
} }
f.peers[peer.ID()] = peer f.peers[*peer.ID()] = peer
return nil return nil
} }
// RemoveFromPeers remove this peer from the peers list.
func (f *FlowContext) RemoveFromPeers(peer *peerpkg.Peer) {
f.peersMutex.Lock()
defer f.peersMutex.Unlock()
delete(f.peers, *peer.ID())
}
// readyPeerConnections returns the NetConnections of all the ready peers. // readyPeerConnections returns the NetConnections of all the ready peers.
func (f *FlowContext) readyPeerConnections() []*netadapter.NetConnection { func (f *FlowContext) readyPeerConnections() []*netadapter.NetConnection {
f.peersMutex.RLock() f.peersMutex.RLock()
@@ -47,7 +55,7 @@ func (f *FlowContext) readyPeerConnections() []*netadapter.NetConnection {
} }
// Broadcast broadcast the given message to all the ready peers. // Broadcast broadcast the given message to all the ready peers.
func (f *FlowContext) Broadcast(message domainmessage.Message) error { func (f *FlowContext) Broadcast(message appmessage.Message) error {
return f.netAdapter.Broadcast(f.readyPeerConnections(), message) return f.netAdapter.Broadcast(f.readyPeerConnections(), message)
} }

View File

@@ -1,9 +1,9 @@
package flowcontext package flowcontext
import ( import (
"github.com/kaspanet/kaspad/app/appmessage"
"github.com/kaspanet/kaspad/app/protocol/flows/relaytransactions"
"github.com/kaspanet/kaspad/domain/mempool" "github.com/kaspanet/kaspad/domain/mempool"
"github.com/kaspanet/kaspad/network/domainmessage"
"github.com/kaspanet/kaspad/network/protocol/flows/relaytransactions"
"github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util"
"github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/daghash"
"github.com/pkg/errors" "github.com/pkg/errors"
@@ -25,7 +25,8 @@ func (f *FlowContext) AddTransaction(tx *util.Tx) error {
} }
f.transactionsToRebroadcast[*tx.ID()] = tx f.transactionsToRebroadcast[*tx.ID()] = tx
inv := domainmessage.NewMsgInvTransaction([]*daghash.TxID{tx.ID()}) inv := appmessage.NewMsgInvTransaction([]*daghash.TxID{tx.ID()})
log.Criticalf("~~~~~ FlowContext.AddTransaction() broadcasting %s", tx.ID())
return f.Broadcast(inv) return f.Broadcast(inv)
} }

View File

@@ -1,13 +1,13 @@
package addressexchange package addressexchange
import ( import (
"github.com/kaspanet/kaspad/app/appmessage"
"github.com/kaspanet/kaspad/app/protocol/common"
peerpkg "github.com/kaspanet/kaspad/app/protocol/peer"
"github.com/kaspanet/kaspad/app/protocol/protocolerrors"
"github.com/kaspanet/kaspad/infrastructure/config" "github.com/kaspanet/kaspad/infrastructure/config"
"github.com/kaspanet/kaspad/network/addressmanager" "github.com/kaspanet/kaspad/infrastructure/network/addressmanager"
"github.com/kaspanet/kaspad/network/domainmessage" "github.com/kaspanet/kaspad/infrastructure/network/netadapter/router"
"github.com/kaspanet/kaspad/network/netadapter/router"
"github.com/kaspanet/kaspad/network/protocol/common"
peerpkg "github.com/kaspanet/kaspad/network/protocol/peer"
"github.com/kaspanet/kaspad/network/protocol/protocolerrors"
) )
// ReceiveAddressesContext is the interface for the context needed for the ReceiveAddresses flow. // 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() subnetworkID := peer.SubnetworkID()
msgGetAddresses := domainmessage.NewMsgRequestAddresses(false, subnetworkID) msgGetAddresses := appmessage.NewMsgRequestAddresses(false, subnetworkID)
err := outgoingRoute.Enqueue(msgGetAddresses) err := outgoingRoute.Enqueue(msgGetAddresses)
if err != nil { if err != nil {
return err return err
@@ -36,9 +36,9 @@ func ReceiveAddresses(context ReceiveAddressesContext, incomingRoute *router.Rou
return err return err
} }
msgAddresses := message.(*domainmessage.MsgAddresses) msgAddresses := message.(*appmessage.MsgAddresses)
if len(msgAddresses.AddrList) > addressmanager.GetAddressesMax { if len(msgAddresses.AddrList) > addressmanager.GetAddressesMax {
return protocolerrors.Errorf(true, "address count excceeded %d", addressmanager.GetAddressesMax) return protocolerrors.Errorf(true, "address count exceeded %d", addressmanager.GetAddressesMax)
} }
if msgAddresses.IncludeAllSubnetworks { if msgAddresses.IncludeAllSubnetworks {

View File

@@ -1,9 +1,9 @@
package addressexchange package addressexchange
import ( import (
"github.com/kaspanet/kaspad/network/addressmanager" "github.com/kaspanet/kaspad/app/appmessage"
"github.com/kaspanet/kaspad/network/domainmessage" "github.com/kaspanet/kaspad/infrastructure/network/addressmanager"
"github.com/kaspanet/kaspad/network/netadapter/router" "github.com/kaspanet/kaspad/infrastructure/network/netadapter/router"
"math/rand" "math/rand"
) )
@@ -14,16 +14,15 @@ type SendAddressesContext interface {
// SendAddresses sends addresses to a peer that requests it. // SendAddresses sends addresses to a peer that requests it.
func SendAddresses(context SendAddressesContext, incomingRoute *router.Route, outgoingRoute *router.Route) error { func SendAddresses(context SendAddressesContext, incomingRoute *router.Route, outgoingRoute *router.Route) error {
message, err := incomingRoute.Dequeue() message, err := incomingRoute.Dequeue()
if err != nil { if err != nil {
return err return err
} }
msgGetAddresses := message.(*domainmessage.MsgRequestAddresses) msgGetAddresses := message.(*appmessage.MsgRequestAddresses)
addresses := context.AddressManager().AddressCache(msgGetAddresses.IncludeAllSubnetworks, addresses := context.AddressManager().AddressCache(msgGetAddresses.IncludeAllSubnetworks,
msgGetAddresses.SubnetworkID) msgGetAddresses.SubnetworkID)
msgAddresses := domainmessage.NewMsgAddresses(msgGetAddresses.IncludeAllSubnetworks, msgGetAddresses.SubnetworkID) msgAddresses := appmessage.NewMsgAddresses(msgGetAddresses.IncludeAllSubnetworks, msgGetAddresses.SubnetworkID)
err = msgAddresses.AddAddresses(shuffleAddresses(addresses)...) err = msgAddresses.AddAddresses(shuffleAddresses(addresses)...)
if err != nil { if err != nil {
return err return err
@@ -33,14 +32,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. // shuffleAddresses randomizes the given addresses sent if there are more than the maximum allowed in one message.
func shuffleAddresses(addresses []*domainmessage.NetAddress) []*domainmessage.NetAddress { func shuffleAddresses(addresses []*appmessage.NetAddress) []*appmessage.NetAddress {
addressCount := len(addresses) addressCount := len(addresses)
if addressCount < domainmessage.MaxAddressesPerMsg { if addressCount < appmessage.MaxAddressesPerMsg {
return addresses return addresses
} }
shuffleAddresses := make([]*domainmessage.NetAddress, addressCount) shuffleAddresses := make([]*appmessage.NetAddress, addressCount)
copy(shuffleAddresses, addresses) copy(shuffleAddresses, addresses)
rand.Shuffle(addressCount, func(i, j int) { rand.Shuffle(addressCount, func(i, j int) {
@@ -48,6 +47,6 @@ func shuffleAddresses(addresses []*domainmessage.NetAddress) []*domainmessage.Ne
}) })
// Truncate it to the maximum size. // Truncate it to the maximum size.
shuffleAddresses = shuffleAddresses[:domainmessage.MaxAddressesPerMsg] shuffleAddresses = shuffleAddresses[:appmessage.MaxAddressesPerMsg]
return shuffleAddresses return shuffleAddresses
} }

View File

@@ -1,11 +1,11 @@
package blockrelay package blockrelay
import ( import (
"github.com/kaspanet/kaspad/app/appmessage"
peerpkg "github.com/kaspanet/kaspad/app/protocol/peer"
"github.com/kaspanet/kaspad/app/protocol/protocolerrors"
"github.com/kaspanet/kaspad/domain/blockdag" "github.com/kaspanet/kaspad/domain/blockdag"
"github.com/kaspanet/kaspad/network/domainmessage" "github.com/kaspanet/kaspad/infrastructure/network/netadapter/router"
"github.com/kaspanet/kaspad/network/netadapter/router"
peerpkg "github.com/kaspanet/kaspad/network/protocol/peer"
"github.com/kaspanet/kaspad/network/protocol/protocolerrors"
"github.com/pkg/errors" "github.com/pkg/errors"
) )
@@ -14,7 +14,7 @@ type RelayBlockRequestsContext interface {
DAG() *blockdag.BlockDAG DAG() *blockdag.BlockDAG
} }
// HandleRelayBlockRequests listens to domainmessage.MsgRequestRelayBlocks messages and sends // HandleRelayBlockRequests listens to appmessage.MsgRequestRelayBlocks messages and sends
// their corresponding blocks to the requesting peer. // their corresponding blocks to the requesting peer.
func HandleRelayBlockRequests(context RelayBlockRequestsContext, incomingRoute *router.Route, func HandleRelayBlockRequests(context RelayBlockRequestsContext, incomingRoute *router.Route,
outgoingRoute *router.Route, peer *peerpkg.Peer) error { outgoingRoute *router.Route, peer *peerpkg.Peer) error {
@@ -24,7 +24,7 @@ func HandleRelayBlockRequests(context RelayBlockRequestsContext, incomingRoute *
if err != nil { if err != nil {
return err return err
} }
getRelayBlocksMessage := message.(*domainmessage.MsgRequestRelayBlocks) getRelayBlocksMessage := message.(*appmessage.MsgRequestRelayBlocks)
for _, hash := range getRelayBlocksMessage.Hashes { for _, hash := range getRelayBlocksMessage.Hashes {
// Fetch the block from the database. // Fetch the block from the database.
block, err := context.DAG().BlockByHash(hash) block, err := context.DAG().BlockByHash(hash)

View File

@@ -1,14 +1,14 @@
package blockrelay package blockrelay
import ( import (
"github.com/kaspanet/kaspad/app/appmessage"
"github.com/kaspanet/kaspad/app/protocol/blocklogger"
"github.com/kaspanet/kaspad/app/protocol/common"
peerpkg "github.com/kaspanet/kaspad/app/protocol/peer"
"github.com/kaspanet/kaspad/app/protocol/protocolerrors"
"github.com/kaspanet/kaspad/domain/blockdag" "github.com/kaspanet/kaspad/domain/blockdag"
"github.com/kaspanet/kaspad/network/domainmessage" "github.com/kaspanet/kaspad/infrastructure/network/netadapter"
"github.com/kaspanet/kaspad/network/netadapter" "github.com/kaspanet/kaspad/infrastructure/network/netadapter/router"
"github.com/kaspanet/kaspad/network/netadapter/router"
"github.com/kaspanet/kaspad/network/protocol/blocklogger"
"github.com/kaspanet/kaspad/network/protocol/common"
peerpkg "github.com/kaspanet/kaspad/network/protocol/peer"
"github.com/kaspanet/kaspad/network/protocol/protocolerrors"
"github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util"
"github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/daghash"
mathUtil "github.com/kaspanet/kaspad/util/math" mathUtil "github.com/kaspanet/kaspad/util/math"
@@ -23,17 +23,17 @@ type RelayInvsContext interface {
SharedRequestedBlocks() *SharedRequestedBlocks SharedRequestedBlocks() *SharedRequestedBlocks
StartIBDIfRequired() StartIBDIfRequired()
IsInIBD() bool IsInIBD() bool
Broadcast(message domainmessage.Message) error Broadcast(message appmessage.Message) error
} }
type handleRelayInvsFlow struct { type handleRelayInvsFlow struct {
RelayInvsContext RelayInvsContext
incomingRoute, outgoingRoute *router.Route incomingRoute, outgoingRoute *router.Route
peer *peerpkg.Peer peer *peerpkg.Peer
invsQueue []*domainmessage.MsgInvRelayBlock invsQueue []*appmessage.MsgInvRelayBlock
} }
// HandleRelayInvs listens to domainmessage.MsgInvRelayBlock messages, requests their corresponding blocks if they // HandleRelayInvs listens to appmessage.MsgInvRelayBlock messages, requests their corresponding blocks if they
// are missing, adds them to the DAG and propagates them to the rest of the network. // 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, func HandleRelayInvs(context RelayInvsContext, incomingRoute *router.Route, outgoingRoute *router.Route,
peer *peerpkg.Peer) error { peer *peerpkg.Peer) error {
@@ -43,7 +43,7 @@ func HandleRelayInvs(context RelayInvsContext, incomingRoute *router.Route, outg
incomingRoute: incomingRoute, incomingRoute: incomingRoute,
outgoingRoute: outgoingRoute, outgoingRoute: outgoingRoute,
peer: peer, peer: peer,
invsQueue: make([]*domainmessage.MsgInvRelayBlock, 0), invsQueue: make([]*appmessage.MsgInvRelayBlock, 0),
} }
return flow.start() return flow.start()
} }
@@ -55,6 +55,8 @@ func (flow *handleRelayInvsFlow) start() error {
return err return err
} }
log.Debugf("Got relay inv for block %s", inv.Hash)
if flow.DAG().IsKnownBlock(inv.Hash) { if flow.DAG().IsKnownBlock(inv.Hash) {
if flow.DAG().IsKnownInvalid(inv.Hash) { if flow.DAG().IsKnownInvalid(inv.Hash) {
return protocolerrors.Errorf(true, "sent inv of an invalid block %s", return protocolerrors.Errorf(true, "sent inv of an invalid block %s",
@@ -81,10 +83,10 @@ func (flow *handleRelayInvsFlow) start() error {
} }
} }
func (flow *handleRelayInvsFlow) readInv() (*domainmessage.MsgInvRelayBlock, error) { func (flow *handleRelayInvsFlow) readInv() (*appmessage.MsgInvRelayBlock, error) {
if len(flow.invsQueue) > 0 { if len(flow.invsQueue) > 0 {
var inv *domainmessage.MsgInvRelayBlock var inv *appmessage.MsgInvRelayBlock
inv, flow.invsQueue = flow.invsQueue[0], flow.invsQueue[1:] inv, flow.invsQueue = flow.invsQueue[0], flow.invsQueue[1:]
return inv, nil return inv, nil
} }
@@ -94,7 +96,7 @@ func (flow *handleRelayInvsFlow) readInv() (*domainmessage.MsgInvRelayBlock, err
return nil, err return nil, err
} }
inv, ok := msg.(*domainmessage.MsgInvRelayBlock) inv, ok := msg.(*appmessage.MsgInvRelayBlock)
if !ok { if !ok {
return nil, protocolerrors.Errorf(true, "unexpected %s message in the block relay handleRelayInvsFlow while "+ return nil, protocolerrors.Errorf(true, "unexpected %s message in the block relay handleRelayInvsFlow while "+
"expecting an inv message", msg.Command()) "expecting an inv message", msg.Command())
@@ -103,7 +105,7 @@ func (flow *handleRelayInvsFlow) readInv() (*domainmessage.MsgInvRelayBlock, err
} }
func (flow *handleRelayInvsFlow) requestBlocks(requestQueue *hashesQueueSet) error { func (flow *handleRelayInvsFlow) requestBlocks(requestQueue *hashesQueueSet) error {
numHashesToRequest := mathUtil.MinInt(domainmessage.MsgRequestRelayBlocksHashes, requestQueue.len()) numHashesToRequest := mathUtil.MinInt(appmessage.MsgRequestRelayBlocksHashes, requestQueue.len())
hashesToRequest := requestQueue.dequeue(numHashesToRequest) hashesToRequest := requestQueue.dequeue(numHashesToRequest)
pendingBlocks := map[daghash.Hash]struct{}{} pendingBlocks := map[daghash.Hash]struct{}{}
@@ -114,6 +116,11 @@ func (flow *handleRelayInvsFlow) requestBlocks(requestQueue *hashesQueueSet) err
continue continue
} }
// The block can become known from another peer in the process of orphan resolution
if flow.DAG().IsKnownBlock(hash) {
continue
}
pendingBlocks[*hash] = struct{}{} pendingBlocks[*hash] = struct{}{}
filteredHashesToRequest = append(filteredHashesToRequest, hash) filteredHashesToRequest = append(filteredHashesToRequest, hash)
} }
@@ -127,7 +134,7 @@ func (flow *handleRelayInvsFlow) requestBlocks(requestQueue *hashesQueueSet) err
// clean from any pending blocks. // clean from any pending blocks.
defer flow.SharedRequestedBlocks().removeSet(pendingBlocks) defer flow.SharedRequestedBlocks().removeSet(pendingBlocks)
getRelayBlocksMsg := domainmessage.NewMsgRequestRelayBlocks(filteredHashesToRequest) getRelayBlocksMsg := appmessage.NewMsgRequestRelayBlocks(filteredHashesToRequest)
err := flow.outgoingRoute.Enqueue(getRelayBlocksMsg) err := flow.outgoingRoute.Enqueue(getRelayBlocksMsg)
if err != nil { if err != nil {
return err return err
@@ -153,16 +160,15 @@ func (flow *handleRelayInvsFlow) requestBlocks(requestQueue *hashesQueueSet) err
delete(pendingBlocks, *blockHash) delete(pendingBlocks, *blockHash)
flow.SharedRequestedBlocks().remove(blockHash) flow.SharedRequestedBlocks().remove(blockHash)
} }
return nil return nil
} }
// readMsgBlock returns the next msgBlock in msgChan, and populates invsQueue with any inv messages that meanwhile arrive. // 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 domainmessage.MsgInvRelayBlock and domainmessage.MsgBlock messages. // Note: this function assumes msgChan can contain only appmessage.MsgInvRelayBlock and appmessage.MsgBlock messages.
func (flow *handleRelayInvsFlow) readMsgBlock() ( func (flow *handleRelayInvsFlow) readMsgBlock() (
msgBlock *domainmessage.MsgBlock, err error) { msgBlock *appmessage.MsgBlock, err error) {
for { for {
message, err := flow.incomingRoute.DequeueWithTimeout(common.DefaultTimeout) message, err := flow.incomingRoute.DequeueWithTimeout(common.DefaultTimeout)
@@ -171,9 +177,9 @@ func (flow *handleRelayInvsFlow) readMsgBlock() (
} }
switch message := message.(type) { switch message := message.(type) {
case *domainmessage.MsgInvRelayBlock: case *appmessage.MsgInvRelayBlock:
flow.invsQueue = append(flow.invsQueue, message) flow.invsQueue = append(flow.invsQueue, message)
case *domainmessage.MsgBlock: case *appmessage.MsgBlock:
return message, nil return message, nil
default: default:
return nil, errors.Errorf("unexpected message %s", message.Command()) return nil, errors.Errorf("unexpected message %s", message.Command())
@@ -190,7 +196,7 @@ func (flow *handleRelayInvsFlow) processAndRelayBlock(requestQueue *hashesQueueS
} }
log.Infof("Rejected block %s from %s: %s", blockHash, flow.peer, err) log.Infof("Rejected block %s from %s: %s", blockHash, flow.peer, err)
return protocolerrors.Wrapf(true, err, "got invalid block %s", blockHash) return protocolerrors.Wrapf(true, err, "got invalid block %s from relay", blockHash)
} }
if isDelayed { if isDelayed {
@@ -224,7 +230,7 @@ func (flow *handleRelayInvsFlow) processAndRelayBlock(requestQueue *hashesQueueS
if err != nil { if err != nil {
return err return err
} }
err = flow.Broadcast(domainmessage.NewMsgInvBlock(blockHash)) err = flow.Broadcast(appmessage.NewMsgInvBlock(blockHash))
if err != nil { if err != nil {
return err return err
} }

View File

@@ -4,17 +4,17 @@ import (
"sync" "sync"
"sync/atomic" "sync/atomic"
"github.com/kaspanet/kaspad/network/addressmanager" "github.com/kaspanet/kaspad/app/protocol/common"
"github.com/kaspanet/kaspad/network/protocol/common" "github.com/kaspanet/kaspad/app/protocol/protocolerrors"
"github.com/kaspanet/kaspad/network/protocol/protocolerrors" "github.com/kaspanet/kaspad/infrastructure/network/addressmanager"
"github.com/kaspanet/kaspad/domain/blockdag" "github.com/kaspanet/kaspad/domain/blockdag"
"github.com/kaspanet/kaspad/infrastructure/config" "github.com/kaspanet/kaspad/infrastructure/config"
"github.com/kaspanet/kaspad/network/netadapter" "github.com/kaspanet/kaspad/infrastructure/network/netadapter"
"github.com/kaspanet/kaspad/network/domainmessage" "github.com/kaspanet/kaspad/app/appmessage"
routerpkg "github.com/kaspanet/kaspad/network/netadapter/router" peerpkg "github.com/kaspanet/kaspad/app/protocol/peer"
peerpkg "github.com/kaspanet/kaspad/network/protocol/peer" routerpkg "github.com/kaspanet/kaspad/infrastructure/network/netadapter/router"
"github.com/kaspanet/kaspad/util/locks" "github.com/kaspanet/kaspad/util/locks"
"github.com/pkg/errors" "github.com/pkg/errors"
) )
@@ -34,7 +34,7 @@ type HandleHandshakeContext interface {
// version message, as well as a verack for the sent version // version message, as well as a verack for the sent version
func HandleHandshake(context HandleHandshakeContext, netConnection *netadapter.NetConnection, func HandleHandshake(context HandleHandshakeContext, netConnection *netadapter.NetConnection,
receiveVersionRoute *routerpkg.Route, sendVersionRoute *routerpkg.Route, outgoingRoute *routerpkg.Route, receiveVersionRoute *routerpkg.Route, sendVersionRoute *routerpkg.Route, outgoingRoute *routerpkg.Route,
) (peer *peerpkg.Peer, err error) { ) (*peerpkg.Peer, error) {
// For HandleHandshake to finish, we need to get from the other node // For HandleHandshake to finish, we need to get from the other node
// a version and verack messages, so we increase the wait group by 2 // a version and verack messages, so we increase the wait group by 2
@@ -45,26 +45,26 @@ func HandleHandshake(context HandleHandshakeContext, netConnection *netadapter.N
isStopping := uint32(0) isStopping := uint32(0)
errChan := make(chan error) errChan := make(chan error)
peer = peerpkg.New(netConnection) peer := peerpkg.New(netConnection)
var peerAddress *domainmessage.NetAddress var peerAddress *appmessage.NetAddress
spawn("HandleHandshake-ReceiveVersion", func() { spawn("HandleHandshake-ReceiveVersion", func() {
defer wg.Done()
address, err := ReceiveVersion(context, receiveVersionRoute, outgoingRoute, peer) address, err := ReceiveVersion(context, receiveVersionRoute, outgoingRoute, peer)
if err != nil { if err != nil {
handleError(err, "ReceiveVersion", &isStopping, errChan) handleError(err, "ReceiveVersion", &isStopping, errChan)
return return
} }
peerAddress = address peerAddress = address
wg.Done()
}) })
spawn("HandleHandshake-SendVersion", func() { spawn("HandleHandshake-SendVersion", func() {
defer wg.Done() err := SendVersion(context, sendVersionRoute, outgoingRoute, peer)
err := SendVersion(context, sendVersionRoute, outgoingRoute)
if err != nil { if err != nil {
handleError(err, "SendVersion", &isStopping, errChan) handleError(err, "SendVersion", &isStopping, errChan)
return return
} }
wg.Done()
}) })
select { select {
@@ -76,7 +76,7 @@ func HandleHandshake(context HandleHandshakeContext, netConnection *netadapter.N
case <-locks.ReceiveFromChanWhenDone(func() { wg.Wait() }): case <-locks.ReceiveFromChanWhenDone(func() { wg.Wait() }):
} }
err = context.AddToPeers(peer) err := context.AddToPeers(peer)
if err != nil { if err != nil {
if errors.As(err, &common.ErrPeerWithSameIDExists) { if errors.As(err, &common.ErrPeerWithSameIDExists) {
return nil, protocolerrors.Wrap(false, err, "peer already exists") return nil, protocolerrors.Wrap(false, err, "peer already exists")

View File

@@ -1,11 +1,11 @@
package handshake package handshake
import ( import (
"github.com/kaspanet/kaspad/network/domainmessage" "github.com/kaspanet/kaspad/app/appmessage"
"github.com/kaspanet/kaspad/network/netadapter/router" "github.com/kaspanet/kaspad/app/protocol/common"
"github.com/kaspanet/kaspad/network/protocol/common" peerpkg "github.com/kaspanet/kaspad/app/protocol/peer"
peerpkg "github.com/kaspanet/kaspad/network/protocol/peer" "github.com/kaspanet/kaspad/app/protocol/protocolerrors"
"github.com/kaspanet/kaspad/network/protocol/protocolerrors" "github.com/kaspanet/kaspad/infrastructure/network/netadapter/router"
) )
var ( var (
@@ -16,7 +16,7 @@ var (
// minAcceptableProtocolVersion is the lowest protocol version that a // minAcceptableProtocolVersion is the lowest protocol version that a
// connected peer may support. // connected peer may support.
minAcceptableProtocolVersion = domainmessage.ProtocolVersion minAcceptableProtocolVersion = appmessage.ProtocolVersion
) )
type receiveVersionFlow struct { type receiveVersionFlow struct {
@@ -28,7 +28,7 @@ type receiveVersionFlow struct {
// ReceiveVersion waits for the peer to send a version message, sends a // ReceiveVersion waits for the peer to send a version message, sends a
// verack in response, and updates its info accordingly. // verack in response, and updates its info accordingly.
func ReceiveVersion(context HandleHandshakeContext, incomingRoute *router.Route, outgoingRoute *router.Route, func ReceiveVersion(context HandleHandshakeContext, incomingRoute *router.Route, outgoingRoute *router.Route,
peer *peerpkg.Peer) (*domainmessage.NetAddress, error) { peer *peerpkg.Peer) (*appmessage.NetAddress, error) {
flow := &receiveVersionFlow{ flow := &receiveVersionFlow{
HandleHandshakeContext: context, HandleHandshakeContext: context,
@@ -40,13 +40,13 @@ func ReceiveVersion(context HandleHandshakeContext, incomingRoute *router.Route,
return flow.start() return flow.start()
} }
func (flow *receiveVersionFlow) start() (*domainmessage.NetAddress, error) { func (flow *receiveVersionFlow) start() (*appmessage.NetAddress, error) {
message, err := flow.incomingRoute.DequeueWithTimeout(common.DefaultTimeout) message, err := flow.incomingRoute.DequeueWithTimeout(common.DefaultTimeout)
if err != nil { if err != nil {
return nil, err return nil, err
} }
msgVersion, ok := message.(*domainmessage.MsgVersion) msgVersion, ok := message.(*appmessage.MsgVersion)
if !ok { if !ok {
return nil, protocolerrors.New(true, "a version message must precede all others") return nil, protocolerrors.New(true, "a version message must precede all others")
} }
@@ -64,7 +64,7 @@ func (flow *receiveVersionFlow) start() (*domainmessage.NetAddress, error) {
// too old. // too old.
// //
// NOTE: If minAcceptableProtocolVersion is raised to be higher than // NOTE: If minAcceptableProtocolVersion is raised to be higher than
// domainmessage.RejectVersion, this should send a reject packet before // appmessage.RejectVersion, this should send a reject packet before
// disconnecting. // disconnecting.
if msgVersion.ProtocolVersion < minAcceptableProtocolVersion { if msgVersion.ProtocolVersion < minAcceptableProtocolVersion {
return nil, protocolerrors.Errorf(false, "protocol version must be %d or greater", return nil, protocolerrors.Errorf(false, "protocol version must be %d or greater",
@@ -90,7 +90,7 @@ func (flow *receiveVersionFlow) start() (*domainmessage.NetAddress, error) {
} }
flow.peer.UpdateFieldsFromMsgVersion(msgVersion) flow.peer.UpdateFieldsFromMsgVersion(msgVersion)
err = flow.outgoingRoute.Enqueue(domainmessage.NewMsgVerAck()) err = flow.outgoingRoute.Enqueue(appmessage.NewMsgVerAck())
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@@ -1,9 +1,10 @@
package handshake package handshake
import ( import (
"github.com/kaspanet/kaspad/network/domainmessage" "github.com/kaspanet/kaspad/app/appmessage"
"github.com/kaspanet/kaspad/network/netadapter/router" "github.com/kaspanet/kaspad/app/protocol/common"
"github.com/kaspanet/kaspad/network/protocol/common" peerpkg "github.com/kaspanet/kaspad/app/protocol/peer"
"github.com/kaspanet/kaspad/infrastructure/network/netadapter/router"
"github.com/kaspanet/kaspad/version" "github.com/kaspanet/kaspad/version"
) )
@@ -18,24 +19,28 @@ var (
// defaultServices describes the default services that are supported by // defaultServices describes the default services that are supported by
// the server. // the server.
defaultServices = domainmessage.SFNodeNetwork | domainmessage.SFNodeBloom | domainmessage.SFNodeCF defaultServices = appmessage.DefaultServices
// defaultRequiredServices describes the default services that are // defaultRequiredServices describes the default services that are
// required to be supported by outbound peers. // required to be supported by outbound peers.
defaultRequiredServices = domainmessage.SFNodeNetwork defaultRequiredServices = appmessage.SFNodeNetwork
) )
type sendVersionFlow struct { type sendVersionFlow struct {
HandleHandshakeContext HandleHandshakeContext
incomingRoute, outgoingRoute *router.Route incomingRoute, outgoingRoute *router.Route
peer *peerpkg.Peer
} }
// SendVersion sends a version to a peer and waits for verack. // SendVersion sends a version to a peer and waits for verack.
func SendVersion(context HandleHandshakeContext, incomingRoute *router.Route, outgoingRoute *router.Route) error { func SendVersion(context HandleHandshakeContext, incomingRoute *router.Route,
outgoingRoute *router.Route, peer *peerpkg.Peer) error {
flow := &sendVersionFlow{ flow := &sendVersionFlow{
HandleHandshakeContext: context, HandleHandshakeContext: context,
incomingRoute: incomingRoute, incomingRoute: incomingRoute,
outgoingRoute: outgoingRoute, outgoingRoute: outgoingRoute,
peer: peer,
} }
return flow.start() return flow.start()
} }
@@ -45,11 +50,8 @@ func (flow *sendVersionFlow) start() error {
subnetworkID := flow.Config().SubnetworkID subnetworkID := flow.Config().SubnetworkID
// Version message. // Version message.
localAddress, err := flow.NetAdapter().GetBestLocalAddress() localAddress := flow.AddressManager().GetBestLocalAddress(flow.peer.Connection().NetAddress())
if err != nil { msg := appmessage.NewMsgVersion(localAddress, flow.NetAdapter().ID(),
return err
}
msg := domainmessage.NewMsgVersion(localAddress, flow.NetAdapter().ID(),
flow.Config().ActiveNetParams.Name, selectedTipHash, subnetworkID) flow.Config().ActiveNetParams.Name, selectedTipHash, subnetworkID)
msg.AddUserAgent(userAgentName, userAgentVersion, flow.Config().UserAgentComments...) msg.AddUserAgent(userAgentName, userAgentVersion, flow.Config().UserAgentComments...)
@@ -57,12 +59,12 @@ func (flow *sendVersionFlow) start() error {
msg.Services = defaultServices msg.Services = defaultServices
// Advertise our max supported protocol version. // Advertise our max supported protocol version.
msg.ProtocolVersion = domainmessage.ProtocolVersion msg.ProtocolVersion = appmessage.ProtocolVersion
// Advertise if inv messages for transactions are desired. // Advertise if inv messages for transactions are desired.
msg.DisableRelayTx = flow.Config().BlocksOnly msg.DisableRelayTx = flow.Config().BlocksOnly
err = flow.outgoingRoute.Enqueue(msg) err := flow.outgoingRoute.Enqueue(msg)
if err != nil { if err != nil {
return err return err
} }

View File

@@ -1,10 +1,10 @@
package ibd package ibd
import ( import (
"github.com/kaspanet/kaspad/app/appmessage"
"github.com/kaspanet/kaspad/app/protocol/protocolerrors"
"github.com/kaspanet/kaspad/domain/blockdag" "github.com/kaspanet/kaspad/domain/blockdag"
"github.com/kaspanet/kaspad/network/domainmessage" "github.com/kaspanet/kaspad/infrastructure/network/netadapter/router"
"github.com/kaspanet/kaspad/network/netadapter/router"
"github.com/kaspanet/kaspad/network/protocol/protocolerrors"
"github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/daghash"
) )
@@ -57,13 +57,13 @@ func (flow *handleRequestBlockLocatorFlow) receiveGetBlockLocator() (lowHash *da
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
msgGetBlockLocator := message.(*domainmessage.MsgRequestBlockLocator) msgGetBlockLocator := message.(*appmessage.MsgRequestBlockLocator)
return msgGetBlockLocator.LowHash, msgGetBlockLocator.HighHash, nil return msgGetBlockLocator.LowHash, msgGetBlockLocator.HighHash, nil
} }
func (flow *handleRequestBlockLocatorFlow) sendBlockLocator(locator blockdag.BlockLocator) error { func (flow *handleRequestBlockLocatorFlow) sendBlockLocator(locator blockdag.BlockLocator) error {
msgBlockLocator := domainmessage.NewMsgBlockLocator(locator) msgBlockLocator := appmessage.NewMsgBlockLocator(locator)
err := flow.outgoingRoute.Enqueue(msgBlockLocator) err := flow.outgoingRoute.Enqueue(msgBlockLocator)
if err != nil { if err != nil {
return err return err

View File

@@ -2,10 +2,10 @@ package ibd
import ( import (
"errors" "errors"
"github.com/kaspanet/kaspad/app/appmessage"
"github.com/kaspanet/kaspad/app/protocol/protocolerrors"
"github.com/kaspanet/kaspad/domain/blockdag" "github.com/kaspanet/kaspad/domain/blockdag"
"github.com/kaspanet/kaspad/network/domainmessage" "github.com/kaspanet/kaspad/infrastructure/network/netadapter/router"
"github.com/kaspanet/kaspad/network/netadapter/router"
"github.com/kaspanet/kaspad/network/protocol/protocolerrors"
"github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/daghash"
) )
@@ -66,12 +66,12 @@ func (flow *handleRequestBlocksFlow) start() error {
return err return err
} }
if _, ok := message.(*domainmessage.MsgRequestNextIBDBlocks); !ok { if _, ok := message.(*appmessage.MsgRequestNextIBDBlocks); !ok {
return protocolerrors.Errorf(true, "received unexpected message type. "+ return protocolerrors.Errorf(true, "received unexpected message type. "+
"expected: %s, got: %s", domainmessage.CmdRequestNextIBDBlocks, message.Command()) "expected: %s, got: %s", appmessage.CmdRequestNextIBDBlocks, message.Command())
} }
} }
err = flow.outgoingRoute.Enqueue(domainmessage.NewMsgDoneIBDBlocks()) err = flow.outgoingRoute.Enqueue(appmessage.NewMsgDoneIBDBlocks())
if err != nil { if err != nil {
return err return err
} }
@@ -85,15 +85,15 @@ func receiveRequestIBDBlocks(incomingRoute *router.Route) (lowHash *daghash.Hash
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
msgRequestIBDBlocks := message.(*domainmessage.MsgRequestIBDBlocks) msgRequestIBDBlocks := message.(*appmessage.MsgRequestIBDBlocks)
return msgRequestIBDBlocks.LowHash, msgRequestIBDBlocks.HighHash, nil return msgRequestIBDBlocks.LowHash, msgRequestIBDBlocks.HighHash, nil
} }
func (flow *handleRequestBlocksFlow) buildMsgIBDBlocks(lowHash *daghash.Hash, func (flow *handleRequestBlocksFlow) buildMsgIBDBlocks(lowHash *daghash.Hash,
highHash *daghash.Hash) ([]*domainmessage.MsgIBDBlock, error) { highHash *daghash.Hash) ([]*appmessage.MsgIBDBlock, error) {
const maxHashesInMsgIBDBlocks = domainmessage.MaxInvPerMsg const maxHashesInMsgIBDBlocks = appmessage.MaxInvPerMsg
blockHashes, err := flow.DAG().AntiPastHashesBetween(lowHash, highHash, maxHashesInMsgIBDBlocks) blockHashes, err := flow.DAG().AntiPastHashesBetween(lowHash, highHash, maxHashesInMsgIBDBlocks)
if err != nil { if err != nil {
if errors.Is(err, blockdag.ErrInvalidParameter) { if errors.Is(err, blockdag.ErrInvalidParameter) {
@@ -103,19 +103,19 @@ func (flow *handleRequestBlocksFlow) buildMsgIBDBlocks(lowHash *daghash.Hash,
return nil, err return nil, err
} }
msgIBDBlocks := make([]*domainmessage.MsgIBDBlock, len(blockHashes)) msgIBDBlocks := make([]*appmessage.MsgIBDBlock, len(blockHashes))
for i, blockHash := range blockHashes { for i, blockHash := range blockHashes {
block, err := flow.DAG().BlockByHash(blockHash) block, err := flow.DAG().BlockByHash(blockHash)
if err != nil { if err != nil {
return nil, err return nil, err
} }
msgIBDBlocks[i] = domainmessage.NewMsgIBDBlock(block.MsgBlock()) msgIBDBlocks[i] = appmessage.NewMsgIBDBlock(block.MsgBlock())
} }
return msgIBDBlocks, nil return msgIBDBlocks, nil
} }
func (flow *handleRequestBlocksFlow) sendMsgIBDBlocks(msgIBDBlocks []*domainmessage.MsgIBDBlock) error { func (flow *handleRequestBlocksFlow) sendMsgIBDBlocks(msgIBDBlocks []*appmessage.MsgIBDBlock) error {
for _, msgIBDBlock := range msgIBDBlocks { for _, msgIBDBlock := range msgIBDBlocks {
err := flow.outgoingRoute.Enqueue(msgIBDBlock) err := flow.outgoingRoute.Enqueue(msgIBDBlock)
if err != nil { if err != nil {

View File

@@ -1,14 +1,16 @@
package ibd package ibd
import ( import (
"github.com/kaspanet/kaspad/app/appmessage"
"github.com/kaspanet/kaspad/app/protocol/blocklogger"
"github.com/kaspanet/kaspad/app/protocol/common"
peerpkg "github.com/kaspanet/kaspad/app/protocol/peer"
"github.com/kaspanet/kaspad/app/protocol/protocolerrors"
"github.com/kaspanet/kaspad/domain/blockdag" "github.com/kaspanet/kaspad/domain/blockdag"
"github.com/kaspanet/kaspad/network/domainmessage" "github.com/kaspanet/kaspad/infrastructure/network/netadapter/router"
"github.com/kaspanet/kaspad/network/netadapter/router"
"github.com/kaspanet/kaspad/network/protocol/common"
peerpkg "github.com/kaspanet/kaspad/network/protocol/peer"
"github.com/kaspanet/kaspad/network/protocol/protocolerrors"
"github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util"
"github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/daghash"
"github.com/pkg/errors"
) )
// HandleIBDContext is the interface for the context needed for the HandleIBD flow. // HandleIBDContext is the interface for the context needed for the HandleIBD flow.
@@ -52,10 +54,13 @@ func (flow *handleIBDFlow) runIBD() error {
defer flow.FinishIBD() defer flow.FinishIBD()
peerSelectedTipHash := flow.peer.SelectedTipHash() peerSelectedTipHash := flow.peer.SelectedTipHash()
log.Debugf("Trying to find highest shared chain block with peer %s with selected tip %s", flow.peer, peerSelectedTipHash)
highestSharedBlockHash, err := flow.findHighestSharedBlockHash(peerSelectedTipHash) highestSharedBlockHash, err := flow.findHighestSharedBlockHash(peerSelectedTipHash)
if err != nil { if err != nil {
return err return err
} }
log.Debugf("Found highest shared chain block %s with peer %s", highestSharedBlockHash, flow.peer)
if flow.DAG().IsKnownFinalizedBlock(highestSharedBlockHash) { if flow.DAG().IsKnownFinalizedBlock(highestSharedBlockHash) {
return protocolerrors.Errorf(false, "cannot initiate "+ return protocolerrors.Errorf(false, "cannot initiate "+
"IBD with peer %s because the highest shared chain block (%s) is "+ "IBD with peer %s because the highest shared chain block (%s) is "+
@@ -96,7 +101,7 @@ func (flow *handleIBDFlow) findHighestSharedBlockHash(peerSelectedTipHash *dagha
func (flow *handleIBDFlow) sendGetBlockLocator(lowHash *daghash.Hash, highHash *daghash.Hash) error { func (flow *handleIBDFlow) sendGetBlockLocator(lowHash *daghash.Hash, highHash *daghash.Hash) error {
msgGetBlockLocator := domainmessage.NewMsgRequestBlockLocator(highHash, lowHash) msgGetBlockLocator := appmessage.NewMsgRequestBlockLocator(highHash, lowHash)
return flow.outgoingRoute.Enqueue(msgGetBlockLocator) return flow.outgoingRoute.Enqueue(msgGetBlockLocator)
} }
@@ -105,11 +110,11 @@ func (flow *handleIBDFlow) receiveBlockLocator() (blockLocatorHashes []*daghash.
if err != nil { if err != nil {
return nil, err return nil, err
} }
msgBlockLocator, ok := message.(*domainmessage.MsgBlockLocator) msgBlockLocator, ok := message.(*appmessage.MsgBlockLocator)
if !ok { if !ok {
return nil, return nil,
protocolerrors.Errorf(true, "received unexpected message type. "+ protocolerrors.Errorf(true, "received unexpected message type. "+
"expected: %s, got: %s", domainmessage.CmdBlockLocator, message.Command()) "expected: %s, got: %s", appmessage.CmdBlockLocator, message.Command())
} }
return msgBlockLocator.BlockLocatorHashes, nil return msgBlockLocator.BlockLocatorHashes, nil
} }
@@ -140,7 +145,7 @@ func (flow *handleIBDFlow) downloadBlocks(highestSharedBlockHash *daghash.Hash,
blocksReceived++ blocksReceived++
if blocksReceived%ibdBatchSize == 0 { if blocksReceived%ibdBatchSize == 0 {
err = flow.outgoingRoute.Enqueue(domainmessage.NewMsgRequestNextIBDBlocks()) err = flow.outgoingRoute.Enqueue(appmessage.NewMsgRequestNextIBDBlocks())
if err != nil { if err != nil {
return err return err
} }
@@ -151,36 +156,41 @@ func (flow *handleIBDFlow) downloadBlocks(highestSharedBlockHash *daghash.Hash,
func (flow *handleIBDFlow) sendGetBlocks(highestSharedBlockHash *daghash.Hash, func (flow *handleIBDFlow) sendGetBlocks(highestSharedBlockHash *daghash.Hash,
peerSelectedTipHash *daghash.Hash) error { peerSelectedTipHash *daghash.Hash) error {
msgGetBlockInvs := domainmessage.NewMsgRequstIBDBlocks(highestSharedBlockHash, peerSelectedTipHash) msgGetBlockInvs := appmessage.NewMsgRequstIBDBlocks(highestSharedBlockHash, peerSelectedTipHash)
return flow.outgoingRoute.Enqueue(msgGetBlockInvs) return flow.outgoingRoute.Enqueue(msgGetBlockInvs)
} }
func (flow *handleIBDFlow) receiveIBDBlock() (msgIBDBlock *domainmessage.MsgIBDBlock, doneIBD bool, err error) { func (flow *handleIBDFlow) receiveIBDBlock() (msgIBDBlock *appmessage.MsgIBDBlock, doneIBD bool, err error) {
message, err := flow.incomingRoute.DequeueWithTimeout(common.DefaultTimeout) message, err := flow.incomingRoute.DequeueWithTimeout(common.DefaultTimeout)
if err != nil { if err != nil {
return nil, false, err return nil, false, err
} }
switch message := message.(type) { switch message := message.(type) {
case *domainmessage.MsgIBDBlock: case *appmessage.MsgIBDBlock:
return message, false, nil return message, false, nil
case *domainmessage.MsgDoneIBDBlocks: case *appmessage.MsgDoneIBDBlocks:
return nil, true, nil return nil, true, nil
default: default:
return nil, false, return nil, false,
protocolerrors.Errorf(true, "received unexpected message type. "+ protocolerrors.Errorf(true, "received unexpected message type. "+
"expected: %s, got: %s", domainmessage.CmdIBDBlock, message.Command()) "expected: %s, got: %s", appmessage.CmdIBDBlock, message.Command())
} }
} }
func (flow *handleIBDFlow) processIBDBlock(msgIBDBlock *domainmessage.MsgIBDBlock) error { func (flow *handleIBDFlow) processIBDBlock(msgIBDBlock *appmessage.MsgIBDBlock) error {
block := util.NewBlock(msgIBDBlock.MsgBlock) block := util.NewBlock(msgIBDBlock.MsgBlock)
if flow.DAG().IsInDAG(block.Hash()) { if flow.DAG().IsInDAG(block.Hash()) {
log.Debugf("IBD block %s is already in the DAG. Skipping...", block.Hash())
return nil return nil
} }
isOrphan, isDelayed, err := flow.DAG().ProcessBlock(block, blockdag.BFNone) isOrphan, isDelayed, err := flow.DAG().ProcessBlock(block, blockdag.BFNone)
if err != nil { if err != nil {
return err if !errors.As(err, &blockdag.RuleError{}) {
return errors.Wrapf(err, "failed to process block %s during IBD", block.Hash())
}
log.Infof("Rejected block %s from %s during IBD: %s", block.Hash(), flow.peer, err)
return protocolerrors.Wrapf(true, err, "got invalid block %s during IBD", block.Hash())
} }
if isOrphan { if isOrphan {
return protocolerrors.Errorf(true, "received orphan block %s "+ return protocolerrors.Errorf(true, "received orphan block %s "+
@@ -194,5 +204,9 @@ func (flow *handleIBDFlow) processIBDBlock(msgIBDBlock *domainmessage.MsgIBDBloc
if err != nil { if err != nil {
return err return err
} }
err = blocklogger.LogBlock(block)
if err != nil {
return err
}
return nil return nil
} }

View File

@@ -1,9 +1,9 @@
package selectedtip package selectedtip
import ( import (
"github.com/kaspanet/kaspad/app/appmessage"
"github.com/kaspanet/kaspad/domain/blockdag" "github.com/kaspanet/kaspad/domain/blockdag"
"github.com/kaspanet/kaspad/network/domainmessage" "github.com/kaspanet/kaspad/infrastructure/network/netadapter/router"
"github.com/kaspanet/kaspad/network/netadapter/router"
"github.com/pkg/errors" "github.com/pkg/errors"
) )
@@ -46,16 +46,16 @@ func (flow *handleRequestSelectedTipFlow) receiveGetSelectedTip() error {
if err != nil { if err != nil {
return err return err
} }
_, ok := message.(*domainmessage.MsgRequestSelectedTip) _, ok := message.(*appmessage.MsgRequestSelectedTip)
if !ok { if !ok {
return errors.Errorf("received unexpected message type. "+ return errors.Errorf("received unexpected message type. "+
"expected: %s, got: %s", domainmessage.CmdRequestSelectedTip, message.Command()) "expected: %s, got: %s", appmessage.CmdRequestSelectedTip, message.Command())
} }
return nil return nil
} }
func (flow *handleRequestSelectedTipFlow) sendSelectedTipHash() error { func (flow *handleRequestSelectedTipFlow) sendSelectedTipHash() error {
msgSelectedTip := domainmessage.NewMsgSelectedTip(flow.DAG().SelectedTipHash()) msgSelectedTip := appmessage.NewMsgSelectedTip(flow.DAG().SelectedTipHash())
return flow.outgoingRoute.Enqueue(msgSelectedTip) return flow.outgoingRoute.Enqueue(msgSelectedTip)
} }

View File

@@ -1,11 +1,11 @@
package selectedtip package selectedtip
import ( import (
"github.com/kaspanet/kaspad/app/appmessage"
"github.com/kaspanet/kaspad/app/protocol/common"
peerpkg "github.com/kaspanet/kaspad/app/protocol/peer"
"github.com/kaspanet/kaspad/domain/blockdag" "github.com/kaspanet/kaspad/domain/blockdag"
"github.com/kaspanet/kaspad/network/domainmessage" "github.com/kaspanet/kaspad/infrastructure/network/netadapter/router"
"github.com/kaspanet/kaspad/network/netadapter/router"
"github.com/kaspanet/kaspad/network/protocol/common"
peerpkg "github.com/kaspanet/kaspad/network/protocol/peer"
"github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/daghash"
) )
@@ -64,7 +64,7 @@ func (flow *requestSelectedTipFlow) runSelectedTipRequest() error {
} }
func (flow *requestSelectedTipFlow) requestSelectedTip() error { func (flow *requestSelectedTipFlow) requestSelectedTip() error {
msgGetSelectedTip := domainmessage.NewMsgRequestSelectedTip() msgGetSelectedTip := appmessage.NewMsgRequestSelectedTip()
return flow.outgoingRoute.Enqueue(msgGetSelectedTip) return flow.outgoingRoute.Enqueue(msgGetSelectedTip)
} }
@@ -73,7 +73,7 @@ func (flow *requestSelectedTipFlow) receiveSelectedTip() (selectedTipHash *dagha
if err != nil { if err != nil {
return nil, err return nil, err
} }
msgSelectedTip := message.(*domainmessage.MsgSelectedTip) msgSelectedTip := message.(*appmessage.MsgSelectedTip)
return msgSelectedTip.SelectedTipHash, nil return msgSelectedTip.SelectedTipHash, nil
} }

View File

@@ -1,8 +1,8 @@
package ping package ping
import ( import (
"github.com/kaspanet/kaspad/network/domainmessage" "github.com/kaspanet/kaspad/app/appmessage"
"github.com/kaspanet/kaspad/network/netadapter/router" "github.com/kaspanet/kaspad/infrastructure/network/netadapter/router"
) )
// ReceivePingsContext is the interface for the context needed for the ReceivePings flow. // ReceivePingsContext is the interface for the context needed for the ReceivePings flow.
@@ -31,9 +31,9 @@ func (flow *receivePingsFlow) start() error {
if err != nil { if err != nil {
return err return err
} }
pingMessage := message.(*domainmessage.MsgPing) pingMessage := message.(*appmessage.MsgPing)
pongMessage := domainmessage.NewMsgPong(pingMessage.Nonce) pongMessage := appmessage.NewMsgPong(pingMessage.Nonce)
err = flow.outgoingRoute.Enqueue(pongMessage) err = flow.outgoingRoute.Enqueue(pongMessage)
if err != nil { if err != nil {
return err return err

View File

@@ -1,13 +1,13 @@
package ping package ping
import ( import (
"github.com/kaspanet/kaspad/app/protocol/common"
"time" "time"
"github.com/kaspanet/kaspad/network/domainmessage" "github.com/kaspanet/kaspad/app/appmessage"
"github.com/kaspanet/kaspad/network/netadapter/router" peerpkg "github.com/kaspanet/kaspad/app/protocol/peer"
"github.com/kaspanet/kaspad/network/protocol/common" "github.com/kaspanet/kaspad/app/protocol/protocolerrors"
peerpkg "github.com/kaspanet/kaspad/network/protocol/peer" "github.com/kaspanet/kaspad/infrastructure/network/netadapter/router"
"github.com/kaspanet/kaspad/network/protocol/protocolerrors"
"github.com/kaspanet/kaspad/util/random" "github.com/kaspanet/kaspad/util/random"
) )
@@ -46,7 +46,7 @@ func (flow *sendPingsFlow) start() error {
} }
flow.peer.SetPingPending(nonce) flow.peer.SetPingPending(nonce)
pingMessage := domainmessage.NewMsgPing(nonce) pingMessage := appmessage.NewMsgPing(nonce)
err = flow.outgoingRoute.Enqueue(pingMessage) err = flow.outgoingRoute.Enqueue(pingMessage)
if err != nil { if err != nil {
return err return err
@@ -56,7 +56,7 @@ func (flow *sendPingsFlow) start() error {
if err != nil { if err != nil {
return err return err
} }
pongMessage := message.(*domainmessage.MsgPong) pongMessage := message.(*appmessage.MsgPong)
if pongMessage.Nonce != pingMessage.Nonce { if pongMessage.Nonce != pingMessage.Nonce {
return protocolerrors.New(true, "nonce mismatch between ping and pong") return protocolerrors.New(true, "nonce mismatch between ping and pong")
} }

View File

@@ -1,9 +1,9 @@
package rejects package rejects
import ( import (
"github.com/kaspanet/kaspad/network/domainmessage" "github.com/kaspanet/kaspad/app/appmessage"
"github.com/kaspanet/kaspad/network/netadapter/router" "github.com/kaspanet/kaspad/app/protocol/protocolerrors"
"github.com/kaspanet/kaspad/network/protocol/protocolerrors" "github.com/kaspanet/kaspad/infrastructure/network/netadapter/router"
) )
// HandleRejectsContext is the interface for the context needed for the HandleRejects flow. // HandleRejectsContext is the interface for the context needed for the HandleRejects flow.
@@ -31,7 +31,7 @@ func (flow *handleRejectsFlow) start() error {
if err != nil { if err != nil {
return err return err
} }
rejectMessage := message.(*domainmessage.MsgReject) rejectMessage := message.(*appmessage.MsgReject)
const maxReasonLength = 255 const maxReasonLength = 255
if len(rejectMessage.Reason) > maxReasonLength { if len(rejectMessage.Reason) > maxReasonLength {

View File

@@ -1,13 +1,13 @@
package relaytransactions package relaytransactions
import ( import (
"github.com/kaspanet/kaspad/app/appmessage"
"github.com/kaspanet/kaspad/app/protocol/common"
"github.com/kaspanet/kaspad/app/protocol/protocolerrors"
"github.com/kaspanet/kaspad/domain/blockdag" "github.com/kaspanet/kaspad/domain/blockdag"
"github.com/kaspanet/kaspad/domain/mempool" "github.com/kaspanet/kaspad/domain/mempool"
"github.com/kaspanet/kaspad/network/domainmessage" "github.com/kaspanet/kaspad/infrastructure/network/netadapter"
"github.com/kaspanet/kaspad/network/netadapter" "github.com/kaspanet/kaspad/infrastructure/network/netadapter/router"
"github.com/kaspanet/kaspad/network/netadapter/router"
"github.com/kaspanet/kaspad/network/protocol/common"
"github.com/kaspanet/kaspad/network/protocol/protocolerrors"
"github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util"
"github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/daghash"
"github.com/pkg/errors" "github.com/pkg/errors"
@@ -20,23 +20,23 @@ type TransactionsRelayContext interface {
DAG() *blockdag.BlockDAG DAG() *blockdag.BlockDAG
SharedRequestedTransactions() *SharedRequestedTransactions SharedRequestedTransactions() *SharedRequestedTransactions
TxPool() *mempool.TxPool TxPool() *mempool.TxPool
Broadcast(message domainmessage.Message) error Broadcast(message appmessage.Message) error
} }
type handleRelayedTransactionsFlow struct { type handleRelayedTransactionsFlow struct {
TransactionsRelayContext TransactionsRelayContext
incomingRoute, outgoingRoute *router.Route incomingRoute, outgoingRoute *router.Route
invsQueue []*domainmessage.MsgInvTransaction invsQueue []*appmessage.MsgInvTransaction
} }
// HandleRelayedTransactions listens to domainmessage.MsgInvTransaction messages, requests their corresponding transactions if they // HandleRelayedTransactions listens to appmessage.MsgInvTransaction messages, requests their corresponding transactions if they
// are missing, adds them to the mempool and propagates them to the rest of the network. // 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 { func HandleRelayedTransactions(context TransactionsRelayContext, incomingRoute *router.Route, outgoingRoute *router.Route) error {
flow := &handleRelayedTransactionsFlow{ flow := &handleRelayedTransactionsFlow{
TransactionsRelayContext: context, TransactionsRelayContext: context,
incomingRoute: incomingRoute, incomingRoute: incomingRoute,
outgoingRoute: outgoingRoute, outgoingRoute: outgoingRoute,
invsQueue: make([]*domainmessage.MsgInvTransaction, 0), invsQueue: make([]*appmessage.MsgInvTransaction, 0),
} }
return flow.start() return flow.start()
} }
@@ -48,6 +48,10 @@ func (flow *handleRelayedTransactionsFlow) start() error {
return err return err
} }
for _, txID := range inv.TxIDs {
log.Criticalf("~~~~~ handleRelayedTransactionsFlow.start() got %s", txID)
}
requestedIDs, err := flow.requestInvTransactions(inv) requestedIDs, err := flow.requestInvTransactions(inv)
if err != nil { if err != nil {
return err return err
@@ -61,7 +65,7 @@ func (flow *handleRelayedTransactionsFlow) start() error {
} }
func (flow *handleRelayedTransactionsFlow) requestInvTransactions( func (flow *handleRelayedTransactionsFlow) requestInvTransactions(
inv *domainmessage.MsgInvTransaction) (requestedIDs []*daghash.TxID, err error) { inv *appmessage.MsgInvTransaction) (requestedIDs []*daghash.TxID, err error) {
idsToRequest := make([]*daghash.TxID, 0, len(inv.TxIDs)) idsToRequest := make([]*daghash.TxID, 0, len(inv.TxIDs))
for _, txID := range inv.TxIDs { for _, txID := range inv.TxIDs {
@@ -79,7 +83,7 @@ func (flow *handleRelayedTransactionsFlow) requestInvTransactions(
return idsToRequest, nil return idsToRequest, nil
} }
msgGetTransactions := domainmessage.NewMsgRequestTransactions(idsToRequest) msgGetTransactions := appmessage.NewMsgRequestTransactions(idsToRequest)
err = flow.outgoingRoute.Enqueue(msgGetTransactions) err = flow.outgoingRoute.Enqueue(msgGetTransactions)
if err != nil { if err != nil {
flow.SharedRequestedTransactions().removeMany(idsToRequest) flow.SharedRequestedTransactions().removeMany(idsToRequest)
@@ -103,7 +107,7 @@ func (flow *handleRelayedTransactionsFlow) isKnownTransaction(txID *daghash.TxID
// checked because the vast majority of transactions consist of // checked because the vast majority of transactions consist of
// two outputs where one is some form of "pay-to-somebody-else" // two outputs where one is some form of "pay-to-somebody-else"
// and the other is a change output. // and the other is a change output.
prevOut := domainmessage.Outpoint{TxID: *txID} prevOut := appmessage.Outpoint{TxID: *txID}
for i := uint32(0); i < 2; i++ { for i := uint32(0); i < 2; i++ {
prevOut.Index = i prevOut.Index = i
_, ok := flow.DAG().GetUTXOEntry(prevOut) _, ok := flow.DAG().GetUTXOEntry(prevOut)
@@ -114,9 +118,9 @@ func (flow *handleRelayedTransactionsFlow) isKnownTransaction(txID *daghash.TxID
return false return false
} }
func (flow *handleRelayedTransactionsFlow) readInv() (*domainmessage.MsgInvTransaction, error) { func (flow *handleRelayedTransactionsFlow) readInv() (*appmessage.MsgInvTransaction, error) {
if len(flow.invsQueue) > 0 { if len(flow.invsQueue) > 0 {
var inv *domainmessage.MsgInvTransaction var inv *appmessage.MsgInvTransaction
inv, flow.invsQueue = flow.invsQueue[0], flow.invsQueue[1:] inv, flow.invsQueue = flow.invsQueue[0], flow.invsQueue[1:]
return inv, nil return inv, nil
} }
@@ -126,7 +130,7 @@ func (flow *handleRelayedTransactionsFlow) readInv() (*domainmessage.MsgInvTrans
return nil, err return nil, err
} }
inv, ok := msg.(*domainmessage.MsgInvTransaction) inv, ok := msg.(*appmessage.MsgInvTransaction)
if !ok { if !ok {
return nil, protocolerrors.Errorf(true, "unexpected %s message in the block relay flow while "+ return nil, protocolerrors.Errorf(true, "unexpected %s message in the block relay flow while "+
"expecting an inv message", msg.Command()) "expecting an inv message", msg.Command())
@@ -137,9 +141,10 @@ func (flow *handleRelayedTransactionsFlow) readInv() (*domainmessage.MsgInvTrans
func (flow *handleRelayedTransactionsFlow) broadcastAcceptedTransactions(acceptedTxs []*mempool.TxDesc) error { func (flow *handleRelayedTransactionsFlow) broadcastAcceptedTransactions(acceptedTxs []*mempool.TxDesc) error {
idsToBroadcast := make([]*daghash.TxID, len(acceptedTxs)) idsToBroadcast := make([]*daghash.TxID, len(acceptedTxs))
for i, tx := range acceptedTxs { for i, tx := range acceptedTxs {
log.Criticalf("~~~~~ broadcastAcceptedTransactions() broadcasting %s", tx.Tx.ID())
idsToBroadcast[i] = tx.Tx.ID() idsToBroadcast[i] = tx.Tx.ID()
} }
inv := domainmessage.NewMsgInvTransaction(idsToBroadcast) inv := appmessage.NewMsgInvTransaction(idsToBroadcast)
return flow.Broadcast(inv) return flow.Broadcast(inv)
} }
@@ -148,7 +153,7 @@ func (flow *handleRelayedTransactionsFlow) broadcastAcceptedTransactions(accepte
// //
// and populates invsQueue with any inv messages that meanwhile arrive. // and populates invsQueue with any inv messages that meanwhile arrive.
func (flow *handleRelayedTransactionsFlow) readMsgTxOrNotFound() ( func (flow *handleRelayedTransactionsFlow) readMsgTxOrNotFound() (
msgTx *domainmessage.MsgTx, msgNotFound *domainmessage.MsgTransactionNotFound, err error) { msgTx *appmessage.MsgTx, msgNotFound *appmessage.MsgTransactionNotFound, err error) {
for { for {
message, err := flow.incomingRoute.DequeueWithTimeout(common.DefaultTimeout) message, err := flow.incomingRoute.DequeueWithTimeout(common.DefaultTimeout)
@@ -157,11 +162,11 @@ func (flow *handleRelayedTransactionsFlow) readMsgTxOrNotFound() (
} }
switch message := message.(type) { switch message := message.(type) {
case *domainmessage.MsgInvTransaction: case *appmessage.MsgInvTransaction:
flow.invsQueue = append(flow.invsQueue, message) flow.invsQueue = append(flow.invsQueue, message)
case *domainmessage.MsgTx: case *appmessage.MsgTx:
return message, nil, nil return message, nil, nil
case *domainmessage.MsgTransactionNotFound: case *appmessage.MsgTransactionNotFound:
return nil, message, nil return nil, message, nil
default: default:
return nil, nil, errors.Errorf("unexpected message %s", message.Command()) return nil, nil, errors.Errorf("unexpected message %s", message.Command())
@@ -187,6 +192,7 @@ func (flow *handleRelayedTransactionsFlow) receiveTransactions(requestedTransact
continue continue
} }
tx := util.NewTx(msgTx) tx := util.NewTx(msgTx)
log.Criticalf("~~~~~ receiveTransactions() got %s", tx.ID())
if !tx.ID().IsEqual(expectedID) { if !tx.ID().IsEqual(expectedID) {
return protocolerrors.Errorf(true, "expected transaction %s, but got %s", return protocolerrors.Errorf(true, "expected transaction %s, but got %s",
expectedID, tx.ID()) expectedID, tx.ID())

View File

@@ -1,8 +1,8 @@
package relaytransactions package relaytransactions
import ( import (
"github.com/kaspanet/kaspad/network/domainmessage" "github.com/kaspanet/kaspad/app/appmessage"
"github.com/kaspanet/kaspad/network/netadapter/router" "github.com/kaspanet/kaspad/infrastructure/network/netadapter/router"
) )
type handleRequestedTransactionsFlow struct { type handleRequestedTransactionsFlow struct {
@@ -10,7 +10,7 @@ type handleRequestedTransactionsFlow struct {
incomingRoute, outgoingRoute *router.Route incomingRoute, outgoingRoute *router.Route
} }
// HandleRequestedTransactions listens to domainmessage.MsgRequestTransactions messages, responding with the requested // HandleRequestedTransactions listens to appmessage.MsgRequestTransactions messages, responding with the requested
// transactions if those are in the mempool. // transactions if those are in the mempool.
// Missing transactions would be ignored // Missing transactions would be ignored
func HandleRequestedTransactions(context TransactionsRelayContext, incomingRoute *router.Route, outgoingRoute *router.Route) error { func HandleRequestedTransactions(context TransactionsRelayContext, incomingRoute *router.Route, outgoingRoute *router.Route) error {
@@ -30,10 +30,11 @@ func (flow *handleRequestedTransactionsFlow) start() error {
} }
for _, transactionID := range msgRequestTransactions.IDs { for _, transactionID := range msgRequestTransactions.IDs {
log.Criticalf("~~~~~ handleRequestedTransactionsFlow.start() tx %s was requested", transactionID)
tx, ok := flow.TxPool().FetchTransaction(transactionID) tx, ok := flow.TxPool().FetchTransaction(transactionID)
if !ok { if !ok {
msgTransactionNotFound := domainmessage.NewMsgTransactionNotFound(transactionID) msgTransactionNotFound := appmessage.NewMsgTransactionNotFound(transactionID)
err := flow.outgoingRoute.Enqueue(msgTransactionNotFound) err := flow.outgoingRoute.Enqueue(msgTransactionNotFound)
if err != nil { if err != nil {
return err return err
@@ -49,11 +50,11 @@ func (flow *handleRequestedTransactionsFlow) start() error {
} }
} }
func (flow *handleRequestedTransactionsFlow) readRequestTransactions() (*domainmessage.MsgRequestTransactions, error) { func (flow *handleRequestedTransactionsFlow) readRequestTransactions() (*appmessage.MsgRequestTransactions, error) {
msg, err := flow.incomingRoute.Dequeue() msg, err := flow.incomingRoute.Dequeue()
if err != nil { if err != nil {
return nil, err return nil, err
} }
return msg.(*domainmessage.MsgRequestTransactions), nil return msg.(*appmessage.MsgRequestTransactions), nil
} }

View File

@@ -0,0 +1,9 @@
package relaytransactions
import (
"github.com/kaspanet/kaspad/infrastructure/logger"
"github.com/kaspanet/kaspad/util/panics"
)
var log, _ = logger.Get(logger.SubsystemTags.PROT)
var spawn = panics.GoroutineWrapperFunc(log)

View File

@@ -3,14 +3,14 @@ package protocol
import ( import (
"fmt" "fmt"
"github.com/kaspanet/kaspad/app/protocol/flowcontext"
peerpkg "github.com/kaspanet/kaspad/app/protocol/peer"
"github.com/kaspanet/kaspad/domain/blockdag" "github.com/kaspanet/kaspad/domain/blockdag"
"github.com/kaspanet/kaspad/domain/mempool" "github.com/kaspanet/kaspad/domain/mempool"
"github.com/kaspanet/kaspad/infrastructure/config" "github.com/kaspanet/kaspad/infrastructure/config"
"github.com/kaspanet/kaspad/network/addressmanager" "github.com/kaspanet/kaspad/infrastructure/network/addressmanager"
"github.com/kaspanet/kaspad/network/connmanager" "github.com/kaspanet/kaspad/infrastructure/network/connmanager"
"github.com/kaspanet/kaspad/network/netadapter" "github.com/kaspanet/kaspad/infrastructure/network/netadapter"
"github.com/kaspanet/kaspad/network/protocol/flowcontext"
peerpkg "github.com/kaspanet/kaspad/network/protocol/peer"
"github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util"
) )

View File

@@ -1,13 +1,13 @@
package peer package peer
import ( import (
"github.com/kaspanet/kaspad/network/netadapter" "github.com/kaspanet/kaspad/infrastructure/network/netadapter"
"sync" "sync"
"sync/atomic" "sync/atomic"
"time" "time"
"github.com/kaspanet/kaspad/network/domainmessage" "github.com/kaspanet/kaspad/app/appmessage"
"github.com/kaspanet/kaspad/network/netadapter/id" "github.com/kaspanet/kaspad/infrastructure/network/netadapter/id"
"github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/daghash"
mathUtil "github.com/kaspanet/kaspad/util/math" mathUtil "github.com/kaspanet/kaspad/util/math"
"github.com/kaspanet/kaspad/util/mstime" "github.com/kaspanet/kaspad/util/mstime"
@@ -22,7 +22,7 @@ type Peer struct {
selectedTipHash *daghash.Hash selectedTipHash *daghash.Hash
userAgent string userAgent string
services domainmessage.ServiceFlag services appmessage.ServiceFlag
advertisedProtocolVerion uint32 // protocol version advertised by remote advertisedProtocolVerion uint32 // protocol version advertised by remote
protocolVersion uint32 // negotiated protocol version protocolVersion uint32 // negotiated protocol version
disableRelayTx bool disableRelayTx bool
@@ -109,7 +109,7 @@ func (p *Peer) IsOutbound() bool {
} }
// UpdateFieldsFromMsgVersion updates the peer with the data from the version message. // UpdateFieldsFromMsgVersion updates the peer with the data from the version message.
func (p *Peer) UpdateFieldsFromMsgVersion(msg *domainmessage.MsgVersion) { func (p *Peer) UpdateFieldsFromMsgVersion(msg *appmessage.MsgVersion) {
// Negotiate the protocol version. // Negotiate the protocol version.
p.advertisedProtocolVerion = msg.ProtocolVersion p.advertisedProtocolVerion = msg.ProtocolVersion
p.protocolVersion = mathUtil.MinUint32(p.protocolVersion, p.advertisedProtocolVerion) p.protocolVersion = mathUtil.MinUint32(p.protocolVersion, p.advertisedProtocolVerion)

View File

@@ -1,22 +1,22 @@
package protocol package protocol
import ( import (
"github.com/kaspanet/kaspad/network/protocol/flows/rejects" "github.com/kaspanet/kaspad/app/protocol/flows/rejects"
"sync/atomic" "sync/atomic"
"github.com/kaspanet/kaspad/network/addressmanager" "github.com/kaspanet/kaspad/app/appmessage"
"github.com/kaspanet/kaspad/network/domainmessage" "github.com/kaspanet/kaspad/app/protocol/flows/addressexchange"
"github.com/kaspanet/kaspad/network/netadapter" "github.com/kaspanet/kaspad/app/protocol/flows/blockrelay"
routerpkg "github.com/kaspanet/kaspad/network/netadapter/router" "github.com/kaspanet/kaspad/app/protocol/flows/handshake"
"github.com/kaspanet/kaspad/network/protocol/flows/addressexchange" "github.com/kaspanet/kaspad/app/protocol/flows/ibd"
"github.com/kaspanet/kaspad/network/protocol/flows/blockrelay" "github.com/kaspanet/kaspad/app/protocol/flows/ibd/selectedtip"
"github.com/kaspanet/kaspad/network/protocol/flows/handshake" "github.com/kaspanet/kaspad/app/protocol/flows/ping"
"github.com/kaspanet/kaspad/network/protocol/flows/ibd" "github.com/kaspanet/kaspad/app/protocol/flows/relaytransactions"
"github.com/kaspanet/kaspad/network/protocol/flows/ibd/selectedtip" peerpkg "github.com/kaspanet/kaspad/app/protocol/peer"
"github.com/kaspanet/kaspad/network/protocol/flows/ping" "github.com/kaspanet/kaspad/app/protocol/protocolerrors"
"github.com/kaspanet/kaspad/network/protocol/flows/relaytransactions" "github.com/kaspanet/kaspad/infrastructure/network/addressmanager"
peerpkg "github.com/kaspanet/kaspad/network/protocol/peer" "github.com/kaspanet/kaspad/infrastructure/network/netadapter"
"github.com/kaspanet/kaspad/network/protocol/protocolerrors" routerpkg "github.com/kaspanet/kaspad/infrastructure/network/netadapter/router"
"github.com/pkg/errors" "github.com/pkg/errors"
) )
@@ -68,6 +68,7 @@ func (m *Manager) routerInitializer(router *routerpkg.Router, netConnection *net
m.handleError(err, netConnection, router.OutgoingRoute()) m.handleError(err, netConnection, router.OutgoingRoute())
return return
} }
defer m.context.RemoveFromPeers(peer)
removeHandshakeRoutes(router) removeHandshakeRoutes(router)
@@ -89,7 +90,7 @@ func (m *Manager) handleError(err error, netConnection *netadapter.NetConnection
panic(err) panic(err)
} }
err = outgoingRoute.Enqueue(domainmessage.NewMsgReject(protocolErr.Error())) err = outgoingRoute.Enqueue(appmessage.NewMsgReject(protocolErr.Error()))
if err != nil && !errors.Is(err, routerpkg.ErrRouteClosed) { if err != nil && !errors.Is(err, routerpkg.ErrRouteClosed) {
panic(err) panic(err)
} }
@@ -123,13 +124,13 @@ func (m *Manager) registerAddressFlows(router *routerpkg.Router, isStopping *uin
outgoingRoute := router.OutgoingRoute() outgoingRoute := router.OutgoingRoute()
return []*flow{ return []*flow{
m.registerOneTimeFlow("SendAddresses", router, []domainmessage.MessageCommand{domainmessage.CmdRequestAddresses}, isStopping, errChan, m.registerOneTimeFlow("SendAddresses", router, []appmessage.MessageCommand{appmessage.CmdRequestAddresses}, isStopping, errChan,
func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error {
return addressexchange.SendAddresses(m.context, incomingRoute, outgoingRoute) return addressexchange.SendAddresses(m.context, incomingRoute, outgoingRoute)
}, },
), ),
m.registerOneTimeFlow("ReceiveAddresses", router, []domainmessage.MessageCommand{domainmessage.CmdAddresses}, isStopping, errChan, m.registerOneTimeFlow("ReceiveAddresses", router, []appmessage.MessageCommand{appmessage.CmdAddresses}, isStopping, errChan,
func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error {
return addressexchange.ReceiveAddresses(m.context, incomingRoute, outgoingRoute, peer) return addressexchange.ReceiveAddresses(m.context, incomingRoute, outgoingRoute, peer)
}, },
@@ -141,14 +142,14 @@ func (m *Manager) registerBlockRelayFlows(router *routerpkg.Router, isStopping *
outgoingRoute := router.OutgoingRoute() outgoingRoute := router.OutgoingRoute()
return []*flow{ return []*flow{
m.registerFlow("HandleRelayInvs", router, []domainmessage.MessageCommand{domainmessage.CmdInvRelayBlock, domainmessage.CmdBlock}, isStopping, errChan, m.registerFlow("HandleRelayInvs", router, []appmessage.MessageCommand{appmessage.CmdInvRelayBlock, appmessage.CmdBlock}, isStopping, errChan,
func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error {
return blockrelay.HandleRelayInvs(m.context, incomingRoute, return blockrelay.HandleRelayInvs(m.context, incomingRoute,
outgoingRoute, peer) outgoingRoute, peer)
}, },
), ),
m.registerFlow("HandleRelayBlockRequests", router, []domainmessage.MessageCommand{domainmessage.CmdRequestRelayBlocks}, isStopping, errChan, m.registerFlow("HandleRelayBlockRequests", router, []appmessage.MessageCommand{appmessage.CmdRequestRelayBlocks}, isStopping, errChan,
func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error {
return blockrelay.HandleRelayBlockRequests(m.context, incomingRoute, outgoingRoute, peer) return blockrelay.HandleRelayBlockRequests(m.context, incomingRoute, outgoingRoute, peer)
}, },
@@ -160,13 +161,13 @@ func (m *Manager) registerPingFlows(router *routerpkg.Router, isStopping *uint32
outgoingRoute := router.OutgoingRoute() outgoingRoute := router.OutgoingRoute()
return []*flow{ return []*flow{
m.registerFlow("ReceivePings", router, []domainmessage.MessageCommand{domainmessage.CmdPing}, isStopping, errChan, m.registerFlow("ReceivePings", router, []appmessage.MessageCommand{appmessage.CmdPing}, isStopping, errChan,
func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error {
return ping.ReceivePings(m.context, incomingRoute, outgoingRoute) return ping.ReceivePings(m.context, incomingRoute, outgoingRoute)
}, },
), ),
m.registerFlow("SendPings", router, []domainmessage.MessageCommand{domainmessage.CmdPong}, isStopping, errChan, m.registerFlow("SendPings", router, []appmessage.MessageCommand{appmessage.CmdPong}, isStopping, errChan,
func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error {
return ping.SendPings(m.context, incomingRoute, outgoingRoute, peer) return ping.SendPings(m.context, incomingRoute, outgoingRoute, peer)
}, },
@@ -178,32 +179,32 @@ func (m *Manager) registerIBDFlows(router *routerpkg.Router, isStopping *uint32,
outgoingRoute := router.OutgoingRoute() outgoingRoute := router.OutgoingRoute()
return []*flow{ return []*flow{
m.registerFlow("HandleIBD", router, []domainmessage.MessageCommand{domainmessage.CmdBlockLocator, domainmessage.CmdIBDBlock, m.registerFlow("HandleIBD", router, []appmessage.MessageCommand{appmessage.CmdBlockLocator, appmessage.CmdIBDBlock,
domainmessage.CmdDoneIBDBlocks}, isStopping, errChan, appmessage.CmdDoneIBDBlocks}, isStopping, errChan,
func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error {
return ibd.HandleIBD(m.context, incomingRoute, outgoingRoute, peer) return ibd.HandleIBD(m.context, incomingRoute, outgoingRoute, peer)
}, },
), ),
m.registerFlow("RequestSelectedTip", router, []domainmessage.MessageCommand{domainmessage.CmdSelectedTip}, isStopping, errChan, m.registerFlow("RequestSelectedTip", router, []appmessage.MessageCommand{appmessage.CmdSelectedTip}, isStopping, errChan,
func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error {
return selectedtip.RequestSelectedTip(m.context, incomingRoute, outgoingRoute, peer) return selectedtip.RequestSelectedTip(m.context, incomingRoute, outgoingRoute, peer)
}, },
), ),
m.registerFlow("HandleRequestSelectedTip", router, []domainmessage.MessageCommand{domainmessage.CmdRequestSelectedTip}, isStopping, errChan, m.registerFlow("HandleRequestSelectedTip", router, []appmessage.MessageCommand{appmessage.CmdRequestSelectedTip}, isStopping, errChan,
func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error {
return selectedtip.HandleRequestSelectedTip(m.context, incomingRoute, outgoingRoute) return selectedtip.HandleRequestSelectedTip(m.context, incomingRoute, outgoingRoute)
}, },
), ),
m.registerFlow("HandleRequestBlockLocator", router, []domainmessage.MessageCommand{domainmessage.CmdRequestBlockLocator}, isStopping, errChan, m.registerFlow("HandleRequestBlockLocator", router, []appmessage.MessageCommand{appmessage.CmdRequestBlockLocator}, isStopping, errChan,
func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error {
return ibd.HandleRequestBlockLocator(m.context, incomingRoute, outgoingRoute) return ibd.HandleRequestBlockLocator(m.context, incomingRoute, outgoingRoute)
}, },
), ),
m.registerFlow("HandleRequestIBDBlocks", router, []domainmessage.MessageCommand{domainmessage.CmdRequestIBDBlocks, domainmessage.CmdRequestNextIBDBlocks}, isStopping, errChan, m.registerFlow("HandleRequestIBDBlocks", router, []appmessage.MessageCommand{appmessage.CmdRequestIBDBlocks, appmessage.CmdRequestNextIBDBlocks}, isStopping, errChan,
func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error {
return ibd.HandleRequestIBDBlocks(m.context, incomingRoute, outgoingRoute) return ibd.HandleRequestIBDBlocks(m.context, incomingRoute, outgoingRoute)
}, },
@@ -216,13 +217,13 @@ func (m *Manager) registerTransactionRelayFlow(router *routerpkg.Router, isStopp
return []*flow{ return []*flow{
m.registerFlow("HandleRelayedTransactions", router, m.registerFlow("HandleRelayedTransactions", router,
[]domainmessage.MessageCommand{domainmessage.CmdInvTransaction, domainmessage.CmdTx, domainmessage.CmdTransactionNotFound}, isStopping, errChan, []appmessage.MessageCommand{appmessage.CmdInvTransaction, appmessage.CmdTx, appmessage.CmdTransactionNotFound}, isStopping, errChan,
func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error {
return relaytransactions.HandleRelayedTransactions(m.context, incomingRoute, outgoingRoute) return relaytransactions.HandleRelayedTransactions(m.context, incomingRoute, outgoingRoute)
}, },
), ),
m.registerFlow("HandleRequestTransactions", router, m.registerFlow("HandleRequestTransactions", router,
[]domainmessage.MessageCommand{domainmessage.CmdRequestTransactions}, isStopping, errChan, []appmessage.MessageCommand{appmessage.CmdRequestTransactions}, isStopping, errChan,
func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error {
return relaytransactions.HandleRequestedTransactions(m.context, incomingRoute, outgoingRoute) return relaytransactions.HandleRequestedTransactions(m.context, incomingRoute, outgoingRoute)
}, },
@@ -235,7 +236,7 @@ func (m *Manager) registerRejectsFlow(router *routerpkg.Router, isStopping *uint
return []*flow{ return []*flow{
m.registerFlow("HandleRejects", router, m.registerFlow("HandleRejects", router,
[]domainmessage.MessageCommand{domainmessage.CmdReject}, isStopping, errChan, []appmessage.MessageCommand{appmessage.CmdReject}, isStopping, errChan,
func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error {
return rejects.HandleRejects(m.context, incomingRoute, outgoingRoute) return rejects.HandleRejects(m.context, incomingRoute, outgoingRoute)
}, },
@@ -243,7 +244,7 @@ func (m *Manager) registerRejectsFlow(router *routerpkg.Router, isStopping *uint
} }
} }
func (m *Manager) registerFlow(name string, router *routerpkg.Router, messageTypes []domainmessage.MessageCommand, isStopping *uint32, func (m *Manager) registerFlow(name string, router *routerpkg.Router, messageTypes []appmessage.MessageCommand, isStopping *uint32,
errChan chan error, initializeFunc flowInitializeFunc) *flow { errChan chan error, initializeFunc flowInitializeFunc) *flow {
route, err := router.AddIncomingRoute(messageTypes) route, err := router.AddIncomingRoute(messageTypes)
@@ -263,7 +264,7 @@ func (m *Manager) registerFlow(name string, router *routerpkg.Router, messageTyp
} }
} }
func (m *Manager) registerOneTimeFlow(name string, router *routerpkg.Router, messageTypes []domainmessage.MessageCommand, func (m *Manager) registerOneTimeFlow(name string, router *routerpkg.Router, messageTypes []appmessage.MessageCommand,
isStopping *uint32, stopChan chan error, initializeFunc flowInitializeFunc) *flow { isStopping *uint32, stopChan chan error, initializeFunc flowInitializeFunc) *flow {
route, err := router.AddIncomingRoute(messageTypes) route, err := router.AddIncomingRoute(messageTypes)
@@ -292,12 +293,12 @@ func (m *Manager) registerOneTimeFlow(name string, router *routerpkg.Router, mes
func registerHandshakeRoutes(router *routerpkg.Router) ( func registerHandshakeRoutes(router *routerpkg.Router) (
receiveVersionRoute *routerpkg.Route, sendVersionRoute *routerpkg.Route) { receiveVersionRoute *routerpkg.Route, sendVersionRoute *routerpkg.Route) {
receiveVersionRoute, err := router.AddIncomingRoute([]domainmessage.MessageCommand{domainmessage.CmdVersion}) receiveVersionRoute, err := router.AddIncomingRoute([]appmessage.MessageCommand{appmessage.CmdVersion})
if err != nil { if err != nil {
panic(err) panic(err)
} }
sendVersionRoute, err = router.AddIncomingRoute([]domainmessage.MessageCommand{domainmessage.CmdVerAck}) sendVersionRoute, err = router.AddIncomingRoute([]appmessage.MessageCommand{appmessage.CmdVerAck})
if err != nil { if err != nil {
panic(err) panic(err)
} }
@@ -306,7 +307,7 @@ func registerHandshakeRoutes(router *routerpkg.Router) (
} }
func removeHandshakeRoutes(router *routerpkg.Router) { func removeHandshakeRoutes(router *routerpkg.Router) {
err := router.RemoveRoute([]domainmessage.MessageCommand{domainmessage.CmdVersion, domainmessage.CmdVerAck}) err := router.RemoveRoute([]appmessage.MessageCommand{appmessage.CmdVersion, appmessage.CmdVerAck})
if err != nil { if err != nil {
panic(err) panic(err)
} }

View File

@@ -5,11 +5,11 @@
package main package main
import ( import (
"github.com/kaspanet/kaspad/infrastructure/logger"
"os" "os"
"runtime" "runtime"
"github.com/kaspanet/kaspad/infrastructure/limits" "github.com/kaspanet/kaspad/infrastructure/os/limits"
"github.com/kaspanet/kaspad/infrastructure/logs"
"github.com/kaspanet/kaspad/util/panics" "github.com/kaspanet/kaspad/util/panics"
) )
@@ -20,7 +20,7 @@ const (
var ( var (
cfg *ConfigFlags cfg *ConfigFlags
log *logs.Logger log *logger.Logger
spawn func(string, func()) spawn func(string, func())
) )
@@ -35,7 +35,7 @@ func realMain() error {
cfg = tcfg cfg = tcfg
// Setup logging. // Setup logging.
backendLogger := logs.NewBackend() backendLogger := logger.NewBackend()
defer os.Stdout.Sync() defer os.Stdout.Sync()
log = backendLogger.Logger("MAIN") log = backendLogger.Logger("MAIN")
spawn = panics.GoroutineWrapperFunc(log) spawn = panics.GoroutineWrapperFunc(log)

View File

@@ -13,8 +13,8 @@ import (
"sync" "sync"
"time" "time"
"github.com/kaspanet/kaspad/app/appmessage"
"github.com/kaspanet/kaspad/domain/blockdag" "github.com/kaspanet/kaspad/domain/blockdag"
"github.com/kaspanet/kaspad/network/domainmessage"
"github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util"
) )
@@ -68,10 +68,10 @@ func (bi *blockImporter) readBlock() ([]byte, error) {
if err := binary.Read(bi.r, binary.LittleEndian, &blockLen); err != nil { if err := binary.Read(bi.r, binary.LittleEndian, &blockLen); err != nil {
return nil, err return nil, err
} }
if blockLen > domainmessage.MaxMessagePayload { if blockLen > appmessage.MaxMessagePayload {
return nil, errors.Errorf("block payload of %d bytes is larger "+ return nil, errors.Errorf("block payload of %d bytes is larger "+
"than the max allowed %d bytes", blockLen, "than the max allowed %d bytes", blockLen,
domainmessage.MaxMessagePayload) appmessage.MaxMessagePayload)
} }
serializedBlock := make([]byte, blockLen) serializedBlock := make([]byte, blockLen)

Some files were not shown because too many files have changed in this diff Show More