# newBlocks

`newBlocks` provides a stream of all new blocks as they propagate through the BDN. It is intended for use cases that are not latency-sensitive and require fully validated blocks. For lower-latency use cases, use `bdnBlocks`.

**Service available via Gateway and Cloud API.**

{% hint style="warning" %}
Note: Gateway must have a node connection to both Consensus Layer and Execution Layer as well as be using the `eth-ws-uri`startup argument (see [How to connect Go-Gateway to consensus layer](https://docs.bloxroute.com/eth/streams/blocks-streams/broken-reference)).
{% endhint %}

## Stream Endpoint

* Method: `newBlocks`
* Cloud-API Endpoint: `wss://<region>.eth.blxrbdn.com/ws`
* Gateway-API Endpoint: `ws://127.0.0.1:28333/ws`
* Request type: `gRPC`*`,WSS`*&#x20;

{% hint style="info" %}
For valid `<region>` values, refer to [#available-regions](https://docs.bloxroute.com/core-solutions/accessing-the-bdn/cloud-api#available-regions "mention")
{% endhint %}

### **Parameters**

| Key             | Description                                                                                                                                                                                                     | Values                                                                                                                                                                                                                                                                                                                                                                                                                     |
| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **`include`**   | Fields to include in the block stream.                                                                                                                                                                          | <p><strong><code>hash,header,transactions,future\_validator\_info,withdrawals</code></strong></p><p><em>\[Default: all]</em><br><br><em><strong>future\_validator\_info</strong></em> contains validator addresses for future blocks and indicates whether the validators are connected to the BDN (currently only supported in BSC)<br><em><strong>withdrawals</strong></em></p><p>contains withdrawals for ETH block</p> |
| **`parsedTxs`** | Controls whether transactions in each block are returned as fully parsed JSON objects (`true`) or as raw, unparsed RLP payloads (`false`). Disabling parsing reduces server work and improves delivery latency. | <p><strong>Type:</strong> boolean<br><br>\[Default: <code>false</code>]</p>                                                                                                                                                                                                                                                                                                                                                |

### **Examples (Websocket)**

#### Cloud-API

{% tabs %}
{% tab title="wscat" %}

```bash
## ETH Example
wscat -c wss://virginia.eth.blxrbdn.com/ws --header "Authorization: <YOUR-AUTHORIZATION-HEADER>"
> {"jsonrpc": "2.0", "id": 1, "method": "subscribe", "params": ["newBlocks", {"include": [""]}]}
< ......

```

{% endtab %}

{% tab title="Node.js" %}

```javascript
var fs = require('fs');
const WebSocket = require('ws');

// Enterprise users can follow line 5-16
const ws = new WebSocket(
  'wss://virginia.eth.blxrbdn.com/ws', // for ETH
  // use 'wss://virginia.bsc.blxrbdn.com/ws',     //for BSC
  {
    headers: { 
      "Authorization" : <YOUR-AUTHORIZATION-HEADER> 
    },
    // Add the following line if you work with IP instead of DNS
    // rejectUnauthorized: false,
  }
);
//  const ws = new WebSocket(
//    "wss://api.blxrbdn.com/ws", 
//    {
//      headers: { 
//        "Authorization" : <YOUR-AUTHORIZATION-HEADER> 
//      },
//      rejectUnauthorized: false,
//    }
//  );

function proceed() {
    // ETH Example
    ws.send(`{"jsonrpc": "2.0", "id": 1, "method": "subscribe", "params": ["newBlocks", {"include": ["hash"]}]}`);

}


function handle(nextNotification) {
    console.log(nextNotification.toString()); // or process it generally
}

ws.on('open', proceed);
ws.on('message', handle);
```

{% endtab %}

{% tab title="Python" %}

```python
# Python version 3.7 or higher required
import asyncio, json, websockets

async def main():
    try:
        uri = "wss://virginia.eth.blxrbdn.com/ws"
        auth_key = "YOUR_AUTHORIZATION_HEADER"
        
        async with websockets.connect(
            uri, 
            header=["Authorization:{}".format(auth_key)],
            # Add the following line if you work with IP instead of DNS
            # sslopt={"cert_reqs": ssl.CERT_NONE}
            ) as websocket:
                # ETH Example
                subscription_request = json.dumps({
                    "jsonrpc": "2.0",
                    "method": "subscribe",
                    "params": ["newBlocks", {"include": ["hash"]}],
                    "id": 1,
                })
                
                await websocket.send(subscription_request)
                while True:
                    response = await websocket.recv()
                    print(response)  # or process it generally
    except Exception as e:
        print(f'Connection failed, Reason: {e}')

if __name__ == '__main__':
    asyncio.run(main())
```

{% endtab %}

{% tab title="Golang" %}

```go
package main

import (
	"crypto/tls"
	"fmt"
	"github.com/gorilla/websocket"
	"net/http"
)

func main() {
	dialer := websocket.DefaultDialer
	// Add the following lines if you work with IP instead of DNS
	// tlsConfig := &tls.Config{
	// 	Certificates:       []tls.Certificate{cert},
	// 	InsecureSkipVerify: true,
	// }
	// dialer.TLSClientConfig = tlsConfig

	wsSubscriber, _, err := dialer.Dial("wss://virginia.eth.blxrbdn.com/ws", http.Header{"Authorization": []string{<YOUR-AUTHORIZATION-HEADER>}})


	if err != nil {
		fmt.Println(err)
		return
	}

	// ETH Example
	subRequest := `{"id": 1, "method": "subscribe", "params": ["newBlocks", {"include": ["hash"]}]}`

	err = wsSubscriber.WriteMessage(websocket.TextMessage, []byte(subRequest))
	if err != nil {
		fmt.Println(err)
		return
	}

	for {
		_, nextNotification, err := wsSubscriber.ReadMessage()
		if err != nil {
			fmt.Println(err)
		}
		fmt.Println(string(nextNotification)) // or process it generally
	}
}

```

{% endtab %}
{% endtabs %}

#### Gateway-API (gRPC)

{% tabs %}
{% tab title="gRPC" %}

```go
package main

import (
	"context"
	"fmt"
	pb "github.com/bloXroute-Labs/gateway/v2/protobuf"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"time"
)

type blxrCredentials struct {
	authorization string
}

func (bc blxrCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
	return map[string]string{
		"authorization": bc.authorization,
	}, nil
}

func (bc blxrCredentials) RequireTransportSecurity() bool {
	return false
}

func main() {
	// gRPC server default values
	gatewayHostIP := "localhost"
	gatewayGRPCPort := 5001
	
	// this will use localhost CA to verify the certificate
	creds := credentials.NewClientTLSFromCert(nil, "")

	// Open gRPC connection to Gateway.
	conn, _ := grpc.Dial(
		fmt.Sprintf("%v:%v", gatewayHostIP, gatewayGRPCPort),
		grpc.WithTransportCredentials(creds),
		grpc.WithPerRPCCredentials(blxrCredentials{authorization: "<YOUR-AUTHORIZATION-HEADER>"}),
	)

	// Use the Gateway client connection interface.
	client := pb.NewGatewayClient(conn)

	// create context and defer cancel of context
	callContext, cancel := context.WithTimeout(context.Background(), 24*time.Hour)
	defer cancel()

	// Create a subscription using the stream-specific method and request.
	stream, _ := client.NewBlocks(callContext, &pb.BlocksRequest{})

	for {
		subscriptionNotification, err := stream.Recv()
		if err == nil {
			fmt.Println(subscriptionNotification) // or process it generally
		}
	}
}
```

{% endtab %}
{% endtabs %}

#### Response (Block Event)

{% hint style="info" %}
This response is for when `parsedTxs` is set to `true` in the stream subscription
{% endhint %}

{% tabs %}
{% tab title="Block Event Cloud-API" %}

```bash
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "subscribe",
  "params": {
    "subscription": "b5c2d94d-932c-49ba-b33b-77f8aa48038e",
    "result": {
      "hash": "0x7f523fa4c2f1817f466c19c758e39548a3cf6a409867789e1881b3cd558d7dc2",
      "Block": {
        "ReceivedAt": "0001-01-01T00:00:00Z",
        "ReceivedFrom": null
      },
      "header": {
        "parentHash": "0x6bdd73c3bc4bb4c89f7030cd761a57ae5162d73ac4c07c8bda1f97cd6debb8c2",
        "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
        "miner": "0x396343362be2a4da1ce0c1c210945346fb82aa49",
        "stateRoot": "0xaf84b0e9636d33a8f5d6dd75bd966dcce3eaf5802f528004114f941b39373a56",
        "transactionsRoot": "0x2251a8ce676b2c30e1572494813987793fe31d01693f1270fe50cb01cdb14b9b",
        "receiptsRoot": "0x927f20e30a29a18b15369af9361f265f075d6c874b9715502466b29d883fdddd",
        "logsBloom": "0xd7adffffefed5bdbeff77fbfefbfabfd3f4daf78edd9fafdfffdfffffbfffffffffdfedff3cdffbffbfadfefb6ffbddff7bbffeffffafbfcffffeff779ffbbffffdbb7f74dfbeffffebbdffdb5fbdff7fddffbff7d57ffef76fbff6fd6efddf7ffefffbb9fffb7f7dedf7dfbfffdffdfbf7f9e72fffddf5adffeff5ffebbda5fe5f7fbdbf385effff8fff7fdfeffffe7ebf7f7f7ddfefffcfee9bf5fbfffdffffff7f7fbfcffef6f6fffdff799fe7efef7b6fbfde3efdbeffcff9efffbed97d746f77d7befefadf37f5fdfbedf7f7bff6fefb3fbbfffbffd77777fffdefffbfff3f7afffdbefe2bfeeff3ff7ffbfdf9f7ffaf7feff7f4defdeff7df67fd6f7b2",
        "difficulty": "0x0",
        "number": "0x1749bbc",
        "gasLimit": "0x3938700",
        "gasUsed": "0x199fa9c",
        "timestamp": "0x6989d563",
        "milliTimestamp": "0x19c42698ab8",
        "extraData": "0xe29ca82051756173617220287175617361722e77696e2920e29ca8",
        "mixHash": "0x09ff73e2cac159e9b51a8551c3b4c4c8d0bd2983b4b2b3cc310956991a98be55",
        "nonce": "0x0000000000000000",
        "baseFeePerGas": 56430067,
        "withdrawalsRoot": "0xd3729e7538b8429960c89884f8303fcbd2f9acf763eecb8d7d07f985b6244a68",
        "blobGasUsed": "0xa0000",
        "excessBlobGas": "0xa7524ff",
        "parentBeaconBlockRoot": "0xfca8908485db24b844eaa38c4b00172963e9d3420466fbea9555a1f03c866e12",
        "requestsHash": "0x85e253b40599d0df756be043ea6949e49a07e756deef72b3588a4b05362206b5"
      },
      "transactions": [
        {
          "accessList": [],
          "blobVersionedHashes": [],
          "chainId": "0x1",
          "from": "0x77c3cde112804ea43af31dfa5b371c146c3d98ee",
          "gas": "0x22e95",
          "gasPrice": "0x7c4b15fb",
          "hash": "0x02bbc7ea80cc7107df781fd61d2ae45afe0e4fd19e4e12131aab7efa31049cc5",
          "input": "0x3593564c000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000006989dc6100000000000000000000000000000000000000000000000000000000000000020b000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000002ea0334ab450d4d000000000000000000000000000000000000000000000000000000000000010000000000000000000000000077c3cde112804ea43af31dfa5b371c146c3d98ee00000000000000000000000000000000000000000000000002ea0334ab450d4d00000000000000000000000000000000000000001517bb81de484320b0fdd9ce00000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002bc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2002710f19308f923582a6f7c465e5ce7a9dc1bec6665b1000000000000000000000000000000000000000000756e697800000000000c",
          "maxFeePerGas": "0x7c4b15fb",
          "maxPriorityFeePerGas": "0x77359400",
          "nonce": "0x4",
          "r": "0x7538f7aabcd6d8140f36e45b5cdcdb2c4ff18050e8761475c8047f966cfa4c2d",
          "s": "0x23656ec1217a032e2666d9f0af73e40bb1caa8c3fa57e6181ee7a76927730ad7",
          "to": "0x66a9893cc07d91d95644aedd05d03f95e1dba8af",
          "type": "0x2",
          "v": "0x1",
          "value": "0x2ea0334ab450d4d",
          "yParity": "0x1"
        },
        ...
      ]
    }
  }
}
```

{% endtab %}

{% tab title="Block Event Gateway-API" %}

```bash
{
    "future_validator_info": [],
    "transaction": [
        {
            "from": "",
            "local_region": false,
            "time": "0",
            "raw_tx": "+I6DAlTHhQHc1lHAglnYlBXsRrWI...3SFs7n3n3UUCAVX1weV6HLAcAKuA"
        },
        ....
        {
            "from": "",
            "local_region": false,
            "time": "0",
            "raw_tx": "AviPgkJogwkGOoQ7mso...3Z99ZUu1/Jc0B9ytQ="
        }
    ],
    "withdrawals": [
        {
            "address": "0x9baA3244565d51D9C7897c0EB6679eD4890e536E",
            "amount": "0x60077b",
            "index": "0x104ed81",
            "validator_index": "0x1ee90"
        },
        ....
        {
            "address": "0x9baA3244565d51D9C7897c0EB6679eD4890e536E",
            "amount": "0x604095",
            "index": "0x104ed90",
            "validator_index": "0x1ee9f"
        }
    ],
    "hash": "0xd9cfa479b98ae15...a7e629fe3435e6169abca",
    "subscriptionID": "c5451b97-c82c-47e2-a70e-74e3256584e6",
    "header": {
        "parent_hash": "0xf3fd6b6011eed8d...f482e9345a3fe5dfe9e26c1db",
        "sha3_uncles": "0x1dcc4de8dec75d7aa...48a7413f0a142fd40d49347",
        "miner": "0x0c10000000756...7f022929a97bda45",
        "state_root": "0xf074e94fc3d700a8f....9ea3280595bd5acd5d97d0",
        "transactions_root": "0xedade2fe2198c....ccf38eeaacb2ccaa92e60",
        "receipts_root": "0x2ff34bb52237c31b8...78e0ac369028cb63f",
        "logs_bloom": "0x4c0008000804...00402004048",
        "difficulty": "0x0",
        "number": "0x107336",
        "gas_limit": "0x1c9c380",
        "gas_used": "0x11bc8e3",
        "timestamp": "0x65e73b50",
        "extra_data": "0xd883010d0e846....2312e37856c696e7578",
        "mix_hash": "0xf6743b00bce48fc1617acf...84d781807a3866ab",
        "nonce": "0x0000000000000000",
        "base_fee_per_gas": "59",
        "withdrawals_root": "0x5e9855e2716a2b4793d4e...9faa41d9c876fcff1b",
        "blob_gas_used": "0x80000",
        "excess_blob_gas": "0x4b20000",
        "parent_beacon_root": "0xe83661292da71373c38...3a91a5e27ac4a59ea3c"
    }
}
```

{% endtab %}
{% endtabs %}
