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

feat(api): constraints getter functions #4

Merged
merged 24 commits into from
Oct 3, 2024

Conversation

namn-grg
Copy link

@namn-grg namn-grg commented Sep 20, 2024

This PR adds the following -

  • Implements the constraint getter fns in builder api
  • Changes the cache storage from ConstraintWithProofData to SignedConstraintWithProofData
  • Add checks during submit constraints
  • Add tests for constraints-api and getter fns

@namn-grg namn-grg changed the title feat(api): getter functions for constraints feat(api): constraints getter functions Sep 20, 2024
@namn-grg namn-grg marked this pull request as ready for review September 23, 2024 07:01
Copy link
Collaborator

@thedevbirb thedevbirb left a comment

Choose a reason for hiding this comment

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

Great job! Some minor comments

Comment on lines 33 to 37
// TODO: Move this to appropriate place
#[derive(Clone)]
pub struct ConstraintsHandle {
pub(crate) constraints_tx: mpsc::Sender<ConstraintsMessage>,
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

Where would you like to put this?

Copy link
Author

Choose a reason for hiding this comment

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

On second thought I think this might be right place itself. lmk if any suggestions

Comment on lines 149 to 151
// TODO: Return err if the slot is outside expiry bounds i.e. before an epoch
// For this we need a beacon state tracker
let slot = params as u64;
Copy link
Collaborator

Choose a reason for hiding this comment

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

It makes sense to return an error in such case. Anyway, I'd consider to make the slot parameter optional (and reflect it in the docs), and when it is not sent we should consider the current slot (from the beacon state) the default one. It is most likely the most requested slot.

Copy link
Author

Choose a reason for hiding this comment

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

Good point

Comment on lines 172 to 187
/// Implements this API: <https://chainbound.github.io/bolt-docs/api/relay#constraints-stream>
pub async fn constraints_stream(
Extension(data_api): Extension<Arc<DataApi<A, DB>>>,
) -> Sse<impl Stream<Item = Result<Event, DataApiError>>> {
let constraints_rx = data_api.constraints_rx.read().await;

// pub async fn blocks_with_proofs() {
// unimplemented!()
// }
let filtered = constraints_rx.map(|constraint| match serde_json::to_string(&constraint) {
Ok(json) => Ok(Event::default().data(json).event("constraint").retry(Duration::from_millis(50))),
Err(err) => {
warn!(error=%err, "Failed to serialize constraint");
Err(DataApiError::InternalServerError)
}
});

Sse::new(filtered).keep_alive(KeepAlive::default())
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

This is great and very short, however I have never implemented SSE in Rust. I have two questions:

  • can you please add some unit tests for this?
  • what did you use as a reference for this implementation?

Copy link
Author

Choose a reason for hiding this comment

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

Comment on lines 172 to 188
/// Implements this API: <https://chainbound.github.io/bolt-docs/api/relay#constraints-stream>
pub async fn constraints_stream(
Extension(data_api): Extension<Arc<DataApi<A, DB>>>,
) -> Sse<impl Stream<Item = Result<Event, DataApiError>>> {
let constraints_rx = data_api.constraints_rx.read().await;

// pub async fn blocks_with_proofs() {
// unimplemented!()
// }
let filtered = constraints_rx.map(|constraint| match serde_json::to_string(&constraint) {
Ok(json) => Ok(Event::default().data(json).event("constraint").retry(Duration::from_millis(50))),
Err(err) => {
warn!(error=%err, "Failed to serialize constraint");
Err(DataApiError::InternalServerError)
}
});

Sse::new(filtered).keep_alive(KeepAlive::default())
}
}
Copy link

@merklefruit merklefruit Sep 23, 2024

Choose a reason for hiding this comment

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

How does this SSE stay open? I don't fully understand how long we are keeping the read() lock for when opening a stream. What happens if we want to write in the constraints while also streaming contents to clients?

Copy link
Author

Choose a reason for hiding this comment

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

Thanks for pointing out, resolved

@namn-grg
Copy link
Author

Testing WIP

}

impl<A: Auctioneer + 'static, DB: DatabaseService + 'static> DataApi<A, DB> {
pub fn new(validator_preferences: Arc<ValidatorPreferences>, auctioneer:Arc<A>, db: Arc<DB>) -> (Self, ConstraintsHandle) {
let (constraints_tx, constraints_rx) = mpsc::channel(100); // Should we have buffer?
let (constraints_tx, constraints_rx ) = broadcast::channel(100); // Should we have buffer?

Choose a reason for hiding this comment

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

to address the comment, I would leave the channel to something like 128 constraint messages - it's not likely to ever get filled anyway

Comment on lines 176 to 177
let constraints_rx = data_api.constraints_rx.resubscribe();
let stream = BroadcastStream::new(constraints_rx);

Choose a reason for hiding this comment

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

lovely

Copy link

PBS Stack Update

Copy link

@merklefruit merklefruit left a comment

Choose a reason for hiding this comment

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

Great job! Few nits

let slot = slot.slot;
let head_slot = api.curr_slot_info.read().await.0;

if slot > head_slot || slot < head_slot - 32 {

Choose a reason for hiding this comment

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

shouldn't this be if slot < head_slot || slot > head_slot + 32 ?

Presumably we want to fetch the constraints for a future slot.

Copy link
Author

Choose a reason for hiding this comment

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

right! mb

Comment on lines 231 to 232
let duty_bytes = api.proposer_duties_response.read().await.clone();
let proposer_duties: Vec<BuilderGetValidatorsResponse> = serde_json::from_slice(&duty_bytes.unwrap()).unwrap();

Choose a reason for hiding this comment

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

suggestion

        let Some(duty_bytes) = api.proposer_duties_response.read().await else {
		return Err(...)
	}

        let Ok(proposer_duties) = serde_json::from_slice::<Vec<BuilderGetValidatorsResponse>>(duty_bytes) else {
		return Err(...)
	}

Copy link
Author

Choose a reason for hiding this comment

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

good point

Err(err) => {
match err {
DatabaseError::ValidatorDelegationNotFound => {
warn!("No delegations found for validator");

Choose a reason for hiding this comment

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

Suggested change
warn!("No delegations found for validator");
debug!("No delegations found for validator");

let mut tx_clone = payload.transactions().clone();
let root = tx_clone.hash_tree_root().expect("failed to hash tree root");
let root = root.to_vec().as_slice().try_into().expect("failed to convert to hash32");

let proofs = payload.proofs().expect("proofs not found");
match verify_multiproofs(constraints, proofs, root) {
let constraints: Vec<ConstraintsWithProofData> = constraints.iter().map(|c| ConstraintsWithProofData {

Choose a reason for hiding this comment

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

should be able to avoid clone() inside by using into_iter()

Copy link
Author

Choose a reason for hiding this comment

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

If I use into_iter() and remove clone it still gives move occurs, copy trait not implemented

Comment on lines 1480 to 1482
let mut tx_clone = payload.transactions().clone();
let root = tx_clone.hash_tree_root().expect("failed to hash tree root");
let root = root.to_vec().as_slice().try_into().expect("failed to convert to hash32");

Choose a reason for hiding this comment

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

Great workaround of the types :)


#[tokio::test]
#[serial]
async fn test_constraints_stream_ok() {

Choose a reason for hiding this comment

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

great test

) {
return Err(ConstraintsApiError::InvalidSignature);
};

// Once we support sending messages signed with correct validator pubkey on the sidecar,
// return error if invalid

let message = signed_constraints.message.clone();
let message = constraint.message.clone();

Choose a reason for hiding this comment

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

can probably do this and use slot below to avoid clone

Suggested change
let message = constraint.message.clone();
let slot = constraint.message.slot;

Copy link
Author

Choose a reason for hiding this comment

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

man I seriously need to start avoiding clone haha. I remember this was needed before but after making some changes to the verification part, I forgot to remove this clone.

Copy link
Author

Choose a reason for hiding this comment

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

resolved

Copy link

@merklefruit merklefruit left a comment

Choose a reason for hiding this comment

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

lgtm, let's move on to testing on devnet

Copy link

coderabbitai bot commented Oct 2, 2024

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@namn-grg namn-grg merged commit 5b45570 into naman/feat/constraints-api-new Oct 3, 2024
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants