Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[P2P] refactor: unicast router #844

Merged
merged 18 commits into from
Jun 29, 2023
Merged

Conversation

bryanchriswhite
Copy link
Contributor

@bryanchriswhite bryanchriswhite commented Jun 19, 2023

Description

Factor out "unicast routing" concerns which will be common to both RainTree and background routers. To implement the Router interface (which I believe is applied appropriately), each must be able to both send and receive messages directly to/from individual peers. In libp2p this is done via streams.

Before

classDiagram
    class RainTreeMessage {
        <<protobuf>>
        +Level uint32
        +Data []byte
    }

    class PocketEnvelope {
        <<protobuf>>
        +Content *anypb.Any
        +Nonce uint64
    }

    RainTreeMessage --* PocketEnvelope : serialized as `Data`
    
    %% class p2pModule {
    %%     -handlePocketEnvelope([]byte) error
    %% }

    %% class P2PModule {
    %%     <<interface>>
    %%     GetAddress() (Address, error)
    %%     HandleEvent(*anypb.Any) error
    %%     Send([]byte, address Address) error
    %%     Broadcast([]byte) error
    %%     BroadcastStaked([]byte) error
    %% }
    %% p2pModule --|> P2PModule

    class RainTreeRouter {
        -handler RouterHandler
        +Broadcast([]byte) error
        +Send([]byte, address Address) error
        -handleStream(stream libp2pNetwork.Stream)
        -readStream(stream libp2pNetwork.Stream)
        -handleRainTreeMsg([]byte) ([]byte, error)
    }

    %% p2pModule --* RainTreeRouter
    %% RainTreeRouter --> p2pModule : `handler` == `handlePocketEnvelope`
    RainTreeRouter --o RainTreeMessage


    %% p2pModule --o PocketEnvelope
    %% p2pModule --* NonceDeduper

    class Router {
        <<interface>>
        +Send([]byte, address Address) error
        +Broadcast([]byte) error
    }
    RainTreeRouter --|> Router
Loading

After

classDiagram
    class RainTreeMessage {
        <<protobuf>>
        +Level uint32
        +Data []byte
    }

    class PocketEnvelope {
        <<protobuf>>
        +Content *anypb.Any
        +Nonce uint64
    }

    RainTreeMessage --* PocketEnvelope : serialized as `Data`
    
    %% class p2pModule {
    %%     -handlePocketEnvelope([]byte) error
    %% }

    %% class P2PModule {
    %%     <<interface>>
    %%     GetAddress() (Address, error)
    %%     HandleEvent(*anypb.Any) error
    %%     Send([]byte, address Address) error
    %%     Broadcast([]byte) error
    %%     BroadcastStaked([]byte) error
    %% }
    %% p2pModule --|> P2PModule

    class RainTreeRouter {
        UnicastRouter
        -handler MessageHandler
        +Broadcast([]byte) error
        -handleRainTreeMsg([]byte) error
    }

    class UnicastRouter {
        -messageHandler MessageHandler
        -peerHandler PeerHandler
        +Send([]byte, address Address) error
        -handleStream(stream libp2pNetwork.Stream)
        -readStream(stream libp2pNetwork.Stream)
    }
    RainTreeRouter --* UnicastRouter : (embedded)
    %% UnicastRouter --> RainTreeRouter : via `messageHandler`


    %% p2pModule --* RainTreeRouter
    %% RainTreeRouter --> p2pModule : `handler` == `handlePocketEnvelope`
    RainTreeRouter --o RainTreeMessage


    %% p2pModule --o PocketEnvelope
    %% p2pModule --* NonceDeduper

    class Router {
        <<interface>>
        +Send([]byte, address Address) error
        +Broadcast([]byte) error
    }
    RainTreeRouter --|> Router
Loading

See #505 "Integration / Architecture" class diagrams for more context.

Summary generated by Reviewpad on 29 Jun 23 06:52 UTC

This pull request includes several changes related to improving testability, reducing technical debt, and implementing unicast functionality.

The overall changes aim to improve the code structure, make it more maintainable and testable, and add support for handling unicast messages in a peer-to-peer network.

Here is a summary of the changes per file:

  1. In the file setup.go, changes were made to register providers and routers to the module registry and improve testability.
  2. In the file router.go, changes were made to improve peer discovery, introduce encapsulated approaches, and share interfaces among modules. Additionally, type and function names were updated.
  3. The file logging.go underwent a rename and changes were made to the package name, logging functionality, and function names.
  4. In the file network.go, changes were made to imports, type names, function names, and the implementation of the handleRainTreeMsg function to support the unicast functionality.
  5. The file testutil.go was added as a new file to provide testing utilities for the unicast functionality.
  6. In the file p2p/raintree/testutil.go, changes were made to imports and a function to call the HandleStream method from the UnicastRouter struct.

These changes collectively improve the testability, code structure, and unicast functionality in the project.

Issue

Dependants

Type of change

Please mark the relevant option(s):

  • New feature, functionality or library
  • Bug fix
  • Code health or cleanup
  • Major breaking change
  • Documentation
  • Other

List of changes

  • Refactored stream handling logic (i.e. unicast routing) out of rainTreeRouter and into new UnicastRouter type

Testing

  • make develop_test; if any code changes were made
  • make test_e2e on k8s LocalNet; if any code changes were made
  • e2e-devnet-test passes tests on DevNet; if any code was changed
  • Docker Compose LocalNet; if any major functionality was changed or introduced
  • k8s LocalNet; if any infrastructure or configuration changes were made

Required Checklist

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added, or updated, godoc format comments on touched members (see: tip.golang.org/doc/comment)
  • I have tested my changes using the available tooling
  • I have updated the corresponding CHANGELOG

If Applicable Checklist

  • I have updated the corresponding README(s); local and/or global
  • I have added tests that prove my fix is effective or that my feature works
  • I have added, or updated, mermaid.js diagrams in the corresponding README(s)
  • I have added, or updated, documentation and mermaid.js diagrams in shared/docs/* if I updated shared/*README(s)

@bryanchriswhite bryanchriswhite added p2p P2P specific changes code health Nice to have code improvement labels Jun 19, 2023
@bryanchriswhite bryanchriswhite self-assigned this Jun 19, 2023
@bryanchriswhite bryanchriswhite changed the title refactor: unicast router [P2P]refactor: unicast router Jun 19, 2023
@reviewpad reviewpad bot added the large Pull request is large label Jun 19, 2023
@bryanchriswhite bryanchriswhite changed the title [P2P]refactor: unicast router [P2P] refactor: unicast router Jun 19, 2023
@codecov
Copy link

codecov bot commented Jun 19, 2023

Codecov Report

Patch coverage: 32.43% and project coverage change: +0.25 🎉

Comparison is base (9d5dffe) 31.52% compared to head (fe24824) 31.78%.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #844      +/-   ##
==========================================
+ Coverage   31.52%   31.78%   +0.25%     
==========================================
  Files         107      106       -1     
  Lines        9034     8996      -38     
==========================================
+ Hits         2848     2859      +11     
+ Misses       5846     5795      -51     
- Partials      340      342       +2     
Impacted Files Coverage Δ
p2p/raintree/testutil.go 0.00% <0.00%> (ø)
p2p/raintree/router.go 29.53% <40.00%> (+8.71%) ⬆️

☔ View full report in Codecov by Sentry.
📢 Do you have feedback about the report comment? Let us know in this issue.

@bryanchriswhite bryanchriswhite force-pushed the refactor/unicast-router branch from 30e94a6 to fe24824 Compare June 19, 2023 13:20
@bryanchriswhite bryanchriswhite marked this pull request as ready for review June 20, 2023 18:19
* pokt/main:
  [Persistence] TreeStore Refactor (#756)
  [General] Ignore false positive secret uncovered by `ggshield` on main (#848)
  [Utility] Add trustless relay to CLI (#778)
  Devlog 9 (#846)
  [Configs] Cleanup private keys and genesis file (#827)
@gitguardian
Copy link

gitguardian bot commented Jun 22, 2023

⚠️ GitGuardian has uncovered 1 secret following the scan of your pull request.

Please consider investigating the findings and remediating the incidents. Failure to do so may lead to compromising the associated services or software components.

🔎 Detected hardcoded secret in your pull request
GitGuardian id Secret Commit Filename
5841025 Generic High Entropy Secret 4b19d8f charts/pocket/templates/configmap-genesis.yaml View secret
🛠 Guidelines to remediate hardcoded secrets
  1. Understand the implications of revoking this secret by investigating where it is used in your code.
  2. Replace and store your secret safely. Learn here the best practices.
  3. Revoke and rotate this secret.
  4. If possible, rewrite git history. Rewriting git history is not a trivial act. You might completely break other contributing developers' workflow and you risk accidentally deleting legitimate data.

To avoid such incidents in the future consider


🦉 GitGuardian detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request.

Our GitHub checks need improvements? Share your feedbacks!

return new(UnicastRouter).Create(bus, cfg)
}

func (*UnicastRouter) Create(bus modules.Bus, cfg *config.UnicastRouterConfig) (*UnicastRouter, error) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Question: What motivates the preference for accepting configs vs options in the module pattern?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fact that everything in the config is required.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If it's not already done, stating this out explicitly in the README could help future readers!

p2p/unicast/logging.go Outdated Show resolved Hide resolved
Copy link
Contributor

@dylanlott dylanlott left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just some minor feedback and questions, overall looks pretty good.

* pokt/main:
  [Persistence] Update KVStore to use Badger wrapper functions (#838)
  [Persistence] Adds TreeStore Module (#851)
@bryanchriswhite bryanchriswhite added push-image Build and push a container image on non-main builds e2e-devnet-test Runs E2E tests on devnet labels Jun 26, 2023
p2p/raintree/router.go Outdated Show resolved Hide resolved
p2p/raintree/router.go Outdated Show resolved Hide resolved
p2p/raintree/router.go Outdated Show resolved Hide resolved
p2p/raintree/router.go Show resolved Hide resolved
p2p/unicast/logging.go Show resolved Hide resolved
p2p/unicast/router.go Outdated Show resolved Hide resolved
p2p/unicast/router.go Show resolved Hide resolved
p2p/unicast/router.go Show resolved Hide resolved
p2p/unicast/router.go Show resolved Hide resolved
p2p/unicast/router.go Show resolved Hide resolved
@bryanchriswhite bryanchriswhite requested a review from Olshansk June 28, 2023 11:52
Copy link
Member

@Olshansk Olshansk left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Aside from this one comment, lgtm: #844 (comment)

bryanchriswhite and others added 2 commits June 29, 2023 08:52
* pokt/main:
  Update E2E_FEATURE_LIST.md
  Update vault_test.go (#862)
Co-authored-by: Daniel Olshansky <[email protected]>
@bryanchriswhite bryanchriswhite merged commit fd30526 into main Jun 29, 2023
bryanchriswhite added a commit that referenced this pull request Jun 29, 2023
* pokt/main:
  [P2P] refactor: unicast router (#844)
  Update E2E_FEATURE_LIST.md
  Update vault_test.go (#862)
@bryanchriswhite bryanchriswhite deleted the refactor/unicast-router branch June 29, 2023 07:39
@bryanchriswhite bryanchriswhite linked an issue Jun 29, 2023 that may be closed by this pull request
11 tasks
bryanchriswhite added a commit that referenced this pull request Jun 29, 2023
…duce-submodule

* 'feat/integrate-bg-router' (early part): (21 commits)
  test: fix raintree message target test
  [P2P] refactor: unicast router (#844)
  chore: add TECHDEBT comment
  Update E2E_FEATURE_LIST.md
  Update vault_test.go (#862)
  chore: return early
  chore: improve debug logging
  chore: improve comments
  chore: improve variable naming
  fix: `p2pModule#Send()` routing logic
  fix: interim background router bootstrapping
  chore: router logging improvements
  fix: return error
  chore: cleanup unused garbage
  chore: add missing godoc comments
  chore: add submodule TECHDEBT comments
  chore: comment cleanup
  chore: cleanup unused test utils
  [IBC] Create initial IBC module (#842)
  [Persistence] Adds TreeStore logger (#852)
  ...
bryanchriswhite added a commit that referenced this pull request Jun 30, 2023
* feat/integrate-bg-router: (27 commits)
  chore: convert `DISCUSS_THIS_COMMIT` to `TECHDEBT`
  chore: remove warning log
  chore: add godoc comment
  docs: tweak P2P readme
  docs: update table of contents
  docs: update P2P readme
  test: fix raintree message target test
  [P2P] refactor: unicast router (#844)
  chore: add TECHDEBT comment
  Update E2E_FEATURE_LIST.md
  Update vault_test.go (#862)
  chore: return early
  chore: improve debug logging
  chore: improve comments
  chore: improve variable naming
  fix: `p2pModule#Send()` routing logic
  fix: interim background router bootstrapping
  chore: router logging improvements
  fix: return error
  chore: cleanup unused garbage
  ...
bryanchriswhite added a commit that referenced this pull request Jul 11, 2023
## @Reviewer
This PR may be more digestible / reviewable on a commit-by-commit basis.
Commits are organized logically and any given line is only modified in a
single commit, with few exceptions*.

*(In the interest of preserving the git-time-continuum
:police_officer::rotating_light:, this applies in batches of commits
between comments or reviews *by humans*, only once "in review")

---

## Description

### Before

While `backgroundRouter` exists and implements the `Router` interface,
it had yet to be connected to anything. Additionally, it was not able to
handle incoming unicast messages.

```mermaid
classDiagram
    class p2pModule {
        -router Router
        -handlePocketEnvelope([]byte) error
    }

    class P2PModule {
        <<interface>>
        GetAddress() (Address, error)
        HandleEvent(*anypb.Any) error
        Send([]byte, Address) error
        Broadcast([]byte) error
    }
    p2pModule --|> P2PModule

    class RainTreeRouter {
        UnicastRouter
        -handler MessageHandler
        +Broadcast([]byte) error
        -handleRainTreeMsg([]byte) error
    }

    class BackgroundRouter {
        UnicastRouter
        -handler MessageHandler
        +Broadcast([]byte) error
        -handleBackgroundMsg([]byte) error
        -readSubscription(subscription *pubsub.Subscription)
    }

    class UnicastRouter {
        -messageHandler MessageHandler
        -peerHandler PeerHandler
        +Send([]byte, Address) error
        -handleStream(libp2pNetwork.Stream)
        -readStream(libp2pNetwork.Stream)
    }
    RainTreeRouter --* UnicastRouter : (embedded)

    p2pModule --o "1" Router
    p2pModule ..* RainTreeRouter : (`router`)
    
    class Router {
        <<interface>>
        +Send([]byte, Address) error
        +Broadcast([]byte) error
    }
    BackgroundRouter --|> Router
    RainTreeRouter --|> Router
```

### After

`backgroundRouter` embeds `UnicastRouter` and is integrated into
`p2pModule` such that it is considered when calling `P2PModule#Send()`
and `P2PModule#Broadcast()`.

```mermaid
classDiagram
    class p2pModule {
        -stakedActorRouter Router
        -unstakedActorRouter Router
        -handlePocketEnvelope([]byte) error
    }

    class P2PModule {
        <<interface>>
        GetAddress() (Address, error)
        HandleEvent(*anypb.Any) error
        Send([]byte, Address) error
        Broadcast([]byte) error
    }
    p2pModule --|> P2PModule

    class RainTreeRouter {
        UnicastRouter
        -handler MessageHandler
        +Broadcast([]byte) error
        -handleRainTreeMsg([]byte) error
    }

    class BackgroundRouter {
        UnicastRouter
        -handler MessageHandler
        +Broadcast([]byte) error
        -handleBackgroundMsg([]byte) error
        -readSubscription(subscription *pubsub.Subscription)
    }

    class UnicastRouter {
        -messageHandler MessageHandler
        -peerHandler PeerHandler
        +Send([]byte, Address) error
        -handleStream(libp2pNetwork.Stream)
        -readStream(libp2pNetwork.Stream)
    }
    RainTreeRouter --* UnicastRouter : (embedded)
    BackgroundRouter --* UnicastRouter : (embedded)

    p2pModule --o "2" Router
    p2pModule ..* RainTreeRouter : (`stakedActorRouter`)
    p2pModule ..* BackgroundRouter : (`unstakedActorRouter`)
    
    class Router {
        <<interface>>
        +Send([]byte, Address) error
        +Broadcast([]byte) error
    }
    BackgroundRouter --|> Router
    RainTreeRouter --|> Router
```

## Issue

- #505 

## Dependencies

- #844 

## Type of change

Please mark the relevant option(s):

- [x] New feature, functionality or library
- [ ] Bug fix
- [ ] Code health or cleanup
- [ ] Major breaking change
- [ ] Documentation
- [ ] Other <!-- add details here if it a different type of change -->

## List of changes

* added background message protobuf type
* added `Router#Close()` interface method
* separated raintree & bg protocol IDs
* move `PocketEnvelope` nonce generation to `PackMessage()`
* added `Handler` to router configs
* refactored raintree router to support P2P module & `Router` interface
changes
* refactored raintree router bootstrapping
* refactored background router to support P2P module integration &
`Router` interface changes
* integrated background router into P2P module
* refactored staked actor router (raintree) peer discovery
* updated tests, post-refactoring


## Testing

- [x] `make develop_test`; if any code changes were made
- [ ] [Docker Compose
LocalNet](https://github.com/pokt-network/pocket/blob/main/docs/development/README.md);
if any major functionality was changed or introduced
- [x] [k8s
LocalNet](https://github.com/pokt-network/pocket/blob/main/build/localnet/README.md);
if any infrastructure or configuration changes were made

<!-- REMOVE this comment block after following the instructions
 If you added additional tests or infrastructure, describe it here.
 Bonus points for images and videos or gifs.
-->

## Required Checklist

- [x] I have performed a self-review of my own code
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] I have added, or updated, [`godoc` format
comments](https://go.dev/blog/godoc) on touched members (see:
[tip.golang.org/doc/comment](https://tip.golang.org/doc/comment))
- [x] I have tested my changes using the available tooling
- [ ] I have updated the corresponding CHANGELOG

### If Applicable Checklist

- [x] I have updated the corresponding README(s); local and/or global
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] I have added, or updated,
[mermaid.js](https://mermaid-js.github.io) diagrams in the corresponding
README(s)
- [ ] I have added, or updated, documentation and
[mermaid.js](https://mermaid-js.github.io) diagrams in `shared/docs/*`
if I updated `shared/*`README(s)

---------

Co-authored-by: @Olshansk <[email protected]>
Co-authored-by: Daniel Olshansky <[email protected]>
Co-authored-by: d7t <[email protected]>
Co-authored-by: Daniel Olshansky <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
code health Nice to have code improvement e2e-devnet-test Runs E2E tests on devnet large Pull request is large p2p P2P specific changes push-image Build and push a container image on non-main builds waiting-for-review
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

[P2P] Background gossip using libp2p-pubsub
3 participants