Use traits to keep event methods dry
This commit is contained in:
+17
-17
@@ -44,7 +44,7 @@ pub mod pow;
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::events::{Event, HashedEvent, OwnedEvent};
|
||||
use crate::events::{HasId, HasTags, HashedEvent, OwnedEvent};
|
||||
use crate::tags::{Tag, Tags};
|
||||
```
|
||||
|
||||
@@ -119,31 +119,31 @@ commitment was made.
|
||||
|
||||
### Methods on event types
|
||||
|
||||
Both `HashedEvent` and `Event` carry an id and tags, so both get a
|
||||
`get_pow` method that delegates to the free function. This lets callers
|
||||
write `event.get_pow() >= 20` regardless of whether the event has been
|
||||
signed yet.
|
||||
Proof of work is the first query that needs the event id as well as its
|
||||
tags, so its extension trait is bounded on both `HasId` and `HasTags` from
|
||||
the events chapter. The method body delegates to the free function through
|
||||
those accessors, and the blanket impl puts `get_pow` on every type that
|
||||
satisfies the bound — both `HashedEvent` and `Event` do. Callers write
|
||||
`event.get_pow() >= 20` regardless of whether the event has been signed yet,
|
||||
as long as the trait is in scope (via `coracle_lib::prelude::*`).
|
||||
|
||||
```rust {file=coracle-lib/src/pow.rs}
|
||||
impl HashedEvent {
|
||||
/// Proof-of-work queries on any event that has an id and tags.
|
||||
pub trait EventExtensionProofOfWork: HasId + HasTags {
|
||||
/// Return the validated proof-of-work difficulty of this event.
|
||||
///
|
||||
/// The result is the minimum of the actual leading zero bits in the
|
||||
/// event id and the difficulty claimed in the nonce tag.
|
||||
pub fn get_pow(&self) -> u8 {
|
||||
get_pow(&self.id, &self.tags)
|
||||
fn get_pow(&self) -> u8 {
|
||||
get_pow(self.id(), self.tags())
|
||||
}
|
||||
}
|
||||
|
||||
impl Event {
|
||||
/// Return the validated proof-of-work difficulty of this event.
|
||||
///
|
||||
/// The result is the minimum of the actual leading zero bits in the
|
||||
/// event id and the difficulty claimed in the nonce tag.
|
||||
pub fn get_pow(&self) -> u8 {
|
||||
get_pow(&self.id, &self.tags)
|
||||
}
|
||||
}
|
||||
impl<T: HasId + HasTags> EventExtensionProofOfWork for T {}
|
||||
```
|
||||
|
||||
```rust {file=coracle-lib/src/prelude.rs}
|
||||
pub use crate::pow::EventExtensionProofOfWork;
|
||||
```
|
||||
|
||||
## Mining
|
||||
|
||||
Reference in New Issue
Block a user