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

Implement subscribeNewHeads,subscriptionReorg,subscribePendingTransactions #2211

Open
wants to merge 26 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions adapters/p2p2core/felt.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ package p2p2core

import (
"encoding/binary"
"reflect"

"github.com/NethermindEth/juno/core/felt"
"github.com/NethermindEth/juno/p2p/starknet/spec"
"github.com/NethermindEth/juno/utils"
"github.com/ethereum/go-ethereum/common"
)

Expand All @@ -28,7 +28,7 @@ func AdaptFelt(f *spec.Felt252) *felt.Felt {
func adapt(v interface{ GetElements() []byte }) *felt.Felt {
// when passing a nil pointer `v` is boxed to an interface and is not nil
// see: https://blog.devtrovert.com/p/go-secret-interface-nil-is-not-nil
if v == nil || reflect.ValueOf(v).IsNil() {
if utils.IsNil(v) {
return nil
}

Expand Down
2 changes: 1 addition & 1 deletion docs/docs/faq.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ docker logs -f juno
<details>
<summary>How can I get real-time updates of new blocks?</summary>

The [WebSocket](websocket#subscribe-to-newly-created-blocks) interface provides a `juno_subscribeNewHeads` method that emits an event when new blocks are added to the blockchain.
The [WebSocket](websocket#subscribe-to-newly-created-blocks) interface provides a `starknet_subscribeNewHeads` method that emits an event when new blocks are added to the blockchain.

</details>

Expand Down
9 changes: 4 additions & 5 deletions docs/docs/websocket.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,16 +96,15 @@ Get the most recent accepted block hash and number with the `starknet_blockHashA

## Subscribe to newly created blocks

The WebSocket server provides a `juno_subscribeNewHeads` method that emits an event when new blocks are added to the blockchain:
The WebSocket server provides a `starknet_subscribeNewHeads` method that emits an event when new blocks are added to the blockchain:

<Tabs>
<TabItem value="request" label="Request">

```json
{
"jsonrpc": "2.0",
"method": "juno_subscribeNewHeads",
"params": [],
"method": "starknet_subscribeNewHeads",
"id": 1
}
```
Expand All @@ -129,7 +128,7 @@ When a new block is added, you will receive a message like this:
```json
{
"jsonrpc": "2.0",
"method": "juno_subscribeNewHeads",
"method": "starknet_subscriptionNewHeads",
"params": {
"result": {
"block_hash": "0x840660a07a17ae6a55d39fb6d366698ecda11e02280ca3e9ca4b4f1bad741c",
Expand All @@ -149,7 +148,7 @@ When a new block is added, you will receive a message like this:
"l1_da_mode": "BLOB",
"starknet_version": "0.13.1.1"
},
"subscription": 16570962336122680234
"subscription_id": 16570962336122680234
}
}
```
Expand Down
23 changes: 19 additions & 4 deletions jsonrpc/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -422,8 +422,17 @@
return false
}

func isNil(i any) bool {
return i == nil || reflect.ValueOf(i).IsNil()
func isNilOrEmpty(i any) (bool, error) {
if utils.IsNil(i) {
return true, nil
}

switch reflect.TypeOf(i).Kind() {
case reflect.Slice, reflect.Array, reflect.Map:
weiihann marked this conversation as resolved.
Show resolved Hide resolved
return reflect.ValueOf(i).Len() == 0, nil
default:
return false, fmt.Errorf("impossible param type: check request.isSane")

Check warning on line 434 in jsonrpc/server.go

View check run for this annotation

Codecov / codecov/patch

jsonrpc/server.go#L433-L434

Added lines #L433 - L434 were not covered by tests
}
}

func (s *Server) handleRequest(ctx context.Context, req *Request) (*response, http.Header, error) {
Expand Down Expand Up @@ -471,7 +480,7 @@
header = (tuple[1].Interface()).(http.Header)
}

if errAny := tuple[errorIndex].Interface(); !isNil(errAny) {
if errAny := tuple[errorIndex].Interface(); !utils.IsNil(errAny) {
res.Error = errAny.(*Error)
if res.Error.Code == InternalError {
s.listener.OnRequestFailed(req.Method, res.Error)
Expand All @@ -486,6 +495,7 @@
return res, header, nil
}

//nolint:gocyclo
func (s *Server) buildArguments(ctx context.Context, params any, method Method) ([]reflect.Value, error) {
handlerType := reflect.TypeOf(method.Handler)

Expand All @@ -498,7 +508,12 @@
addContext = 1
}

if isNil(params) {
isNilOrEmpty, err := isNilOrEmpty(params)
if err != nil {
return nil, err
}

Check warning on line 514 in jsonrpc/server.go

View check run for this annotation

Codecov / codecov/patch

jsonrpc/server.go#L513-L514

Added lines #L513 - L514 were not covered by tests

if isNilOrEmpty {
allParamsAreOptional := utils.All(method.Params, func(p Parameter) bool {
return p.Optional
})
Expand Down
28 changes: 28 additions & 0 deletions mocks/mock_synchronizer.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

68 changes: 0 additions & 68 deletions rpc/events.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
package rpc

import (
"context"
"encoding/json"

"github.com/NethermindEth/juno/blockchain"
"github.com/NethermindEth/juno/core/felt"
"github.com/NethermindEth/juno/jsonrpc"
Expand Down Expand Up @@ -51,71 +48,6 @@ type SubscriptionID struct {
/****************************************************
Events Handlers
*****************************************************/

func (h *Handler) SubscribeNewHeads(ctx context.Context) (uint64, *jsonrpc.Error) {
w, ok := jsonrpc.ConnFromContext(ctx)
if !ok {
return 0, jsonrpc.Err(jsonrpc.MethodNotFound, nil)
}

id := h.idgen()
subscriptionCtx, subscriptionCtxCancel := context.WithCancel(ctx)
sub := &subscription{
cancel: subscriptionCtxCancel,
conn: w,
}
h.mu.Lock()
h.subscriptions[id] = sub
h.mu.Unlock()
headerSub := h.newHeads.Subscribe()
sub.wg.Go(func() {
defer func() {
headerSub.Unsubscribe()
h.unsubscribe(sub, id)
}()
for {
select {
case <-subscriptionCtx.Done():
return
case header := <-headerSub.Recv():
resp, err := json.Marshal(SubscriptionResponse{
Version: "2.0",
Method: "juno_subscribeNewHeads",
Params: map[string]any{
"result": adaptBlockHeader(header),
"subscription": id,
},
})
if err != nil {
h.log.Warnw("Error marshalling a subscription reply", "err", err)
return
}
if _, err = w.Write(resp); err != nil {
h.log.Warnw("Error writing a subscription reply", "err", err)
return
}
}
}
})
return id, nil
}

func (h *Handler) Unsubscribe(ctx context.Context, id uint64) (bool, *jsonrpc.Error) {
w, ok := jsonrpc.ConnFromContext(ctx)
if !ok {
return false, jsonrpc.Err(jsonrpc.MethodNotFound, nil)
}
h.mu.Lock()
sub, ok := h.subscriptions[id]
h.mu.Unlock() // Don't defer since h.unsubscribe acquires the lock.
if !ok || !sub.conn.Equal(w) {
return false, ErrSubscriptionNotFound
}
sub.cancel()
sub.wg.Wait() // Let the subscription finish before responding.
return true, nil
}

// Events gets the events matching a filter
//
// It follows the specification defined here:
Expand Down
Loading
Loading