# 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/bsc/streams/block-streams/broken-reference)).
{% endhint %}

## Stream Endpoint

* Method: `newBlocks`
* Cloud-API Endpoint: `wss://<region>.bsc.blxrbdn.com/ws`
* Gateway-API Endpoint: `ws://127.0.0.1:28333/ws`&#x20;
* 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> |
| **`blockchain_network`** | Use **`BSC-Mainnet`**                                                                                                                                                                                           |                                                                                                                                                                                                                                                                                                                                                                                                                            |
| **`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
## BSC Example
wscat -c wss://virginia.bsc.blxrbdn.com/ws --header "Authorization: <YOUR-AUTHORIZATION-HEADER>"
> {"jsonrpc": "2.0", "id": 1, "method": "subscribe", "params": ["newBlocks", {"include": [""], "blockchain_network": "BSC-Mainnet"}]}
< ......
```

{% 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.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() {
    
    // BSC Example (only available at endpoint wss://<region>.bsc.blxrbdn.com/ws)
    ws.send(`{"jsonrpc": "2.0", "id": 1, "method": "subscribe", "params": ["newBlocks", {"include": ["hash"], "blockchain_network": "BSC-Mainnet"}]}`);

}


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:
        # Enterprise users and above
        uri = "wss://virginia.bsc.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:
                
                subscription_request = json.dumps({"id": 1, "jsonrpc": "2.0","newBlocks", "method": "subscribe","params": ["newBlocks", {"include": ["hash"]}], "blockchain_network": "BSC-Mainnet"})
                
                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
	}
	
	// BSC Example (only available at endpoint wss://<region>.bsc.feed.blxrbdn.com:28333)
	subRequest := `{"id": 1, "method": "subscribe", "params": ["newBlocks", {"include": ["hash"], "blockchain_network": "BSC-Mainnet"}]}`

	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": "28678fca-b084-41c5-927a-3fe5ad00d1b0",
        "result": {
            "hash": "0x382aa8c6ac7b6e2ce16f51bff3b89c382c4fce6b4c6c622c268c5ffbb0ad8d70",
            "Block": {
                "ReceivedAt": "0001-01-01T00:00:00Z",
                "ReceivedFrom": null
            },
            "header": {
                "parentHash": "0xeaaafa74cfef87fcc450fa89da5589a8311c3aa5e49e5cbb7822591c0df3a2ca",
                "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
                "miner": "0xb4647b856cb9c3856d559c885bed8b43e0846a47",
                "stateRoot": "0xd4d4c22d508b400cb7bd902fcc4410a526079e463e8662e220ed4799eabbcbb3",
                "transactionsRoot": "0x6b5b908a12f1c19ed4b20c0c90ff7636e5f6e3bc7783607607968454af71f36a",
                "receiptsRoot": "0x358f7dd8e8f96bb9c5824e65f1c841e5234c3d9fd26ce73cf1213d069fc6b653",
                "logsBloom": "0x62e12a800e0d1c38b3b62560a832420911c0002028ea222ce02212a2725001a88e08b6894942a458461a6261891730a1a56880a0c00e24a85c7026092c2c94805e5280192160383a2f18c018b80c4030e8d2012004415c8c250d2e42a2307c94324e01e102aa60081501210fa490dc204c70a4639874c3b71c80d057a3ab028108a1c041083021e028da54ab363195e9052c455180bc361a4b9489df003068220ecbc654403047bcca4b908b9e80cd0955c01975081980c70374e332b8256c0cb2aa27c37582c7680065402a46e8858a2246361208a436750010422ac033e9cf7e55b223068062087d2412844491018000888a4003283258c87a138045c09125",
                "difficulty": "0x2",
                "number": "0x4c7e7c0",
                "gasLimit": "0x3473bc0",
                "gasUsed": "0x9f4064",
                "timestamp": "0x6989d2af",
                "milliTimestamp": "0x19c425efe54",
                "extraData": "0xdb8301060588663832386233306189676f312e32342e3131836c696e4d518ce1f8b5831f7fffb86096482fd1ece92d220001f5c7cc02b0fd002158c6cc9b8d158081eef7e2e78c0a3169fb373ed6c444ee059cb7ae6f51810df37817811cc57e1943cd7006c2a46f65e18e7a7966290b4a067b0c62221eef80cd33a4b2dfd6749e92346afa8e2a61f84c8404c7e7bea096c9a14505df66d62275c2ef7a44b2e4a28f2fc3bc8f46b67d28b8fda7e8b3748404c7e7bfa0eaaafa74cfef87fcc450fa89da5589a8311c3aa5e49e5cbb7822591c0df3a2ca80874fd091da1e643109434d9813c093ba583fa295f6d20892abe440b7d9f104b61fb11e9ea3bb4acb7d20738991e9e760d9f8252263abb0db7f6512461b89be2900",
                "mixHash": "0x00000000000000000000000000000000000000000000000000000000000002bc",
                "nonce": "0x0000000000000000",
                "baseFeePerGas": 0,
                "withdrawalsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
                "blobGasUsed": "0x0",
                "excessBlobGas": "0x0",
                "parentBeaconBlockRoot": "0x0000000000000000000000000000000000000000000000000000000000000000",
                "requestsHash": "0xe3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
            },
            "transactions": [
                {
                    "blobVersionedHashes": [],
                    "from": "0xb4647b856cb9c3856d559c885bed8b43e0846a47",
                    "gas": "0x7fffffffffffffff",
                    "gasPrice": "0x0",
                    "hash": "0x789fdfea773775fd70f33248845d654cf88b7e55a0c0cc20c8d407e0a7cdad3f",
                    "input": "0xf340fa01000000000000000000000000b4647b856cb9c3856d559c885bed8b43e0846a47",
                    "nonce": "0x1b18d7",
                    "r": "0x6a87babc402e1906d929e7570403e87769e6ec61e6a0e3f90ddb98f4013a89eb",
                    "s": "0x581a6d565850c8e9bc8f0b5ec2e3b62798a96b625b3ab646c0ce5514c61249e",
                    "to": "0x0000000000000000000000000000000000001000",
                    "type": "0x0",
                    "v": "0x93",
                    "value": "0x24065cf9b52e1"
                }
...
            ],
            "future_validator_info": [
                {
                    "block_height": 80209857,
                    "wallet_id": "0xb4647b856cb9c3856d559c885bed8b43e0846a47",
                    "accessible": true
                },
                {
                    "block_height": 80209858,
                    "wallet_id": "0xb4647b856cb9c3856d559c885bed8b43e0846a47",
                    "accessible": true
                }
            ]
        }
    }
}
```

{% 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 %}
