PHPackages                             dev404ai/drand-client-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. dev404ai/drand-client-php

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

dev404ai/drand-client-php
=========================

Minimal-dependency PHP client for the drand randomness beacon. Supports all drand signature schemes and provides fast, verifiable, unbiased public randomness for blockchain, games, lotteries, and any application requiring cryptographically secure randomness.

v1.0.0(11mo ago)01MITPHPPHP &gt;=8.2CI passing

Since May 27Pushed 11mo agoCompare

[ Source](https://github.com/dev404ai/drand-client-php)[ Packagist](https://packagist.org/packages/dev404ai/drand-client-php)[ Docs](https://github.com/dev404ai/drand-client-php)[ RSS](/packages/dev404ai-drand-client-php/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (9)Versions (2)Used By (0)

Drand Client for PHP
====================

[](#drand-client-for-php)

[![Build Status](https://github.com/dev404ai/drand-client-php/actions/workflows/ci.yml/badge.svg)](https://github.com/dev404ai/drand-client-php/actions)[![Psalm](https://camo.githubusercontent.com/1ce165ed9b745103249b5a760b6c3fe66629903f8409575128c67dde04627e60/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7073616c6d2d70617373696e672d627269676874677265656e3f6c6f676f3d706870)](https://github.com/dev404ai/drand-client-php/actions?query=workflow%3ACI)[![PHPStan](https://camo.githubusercontent.com/bdf1e10538c74ced0f7b1b623d902c34f123967fd46a1cddde70ec0be588755c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068707374616e2d70617373696e672d627269676874677265656e3f6c6f676f3d706870)](https://github.com/dev404ai/drand-client-php/actions?query=workflow%3ACI)[![Code Style: PSR-12](https://camo.githubusercontent.com/88796f43286701cea418d9a43a72f4ca39b769304bd5c189e3a73b4e61edf93f/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f64652532307374796c652d5053522d2d31322d626c7565)](https://www.php-fig.org/psr/psr-12/)[![Mutation Testing](https://camo.githubusercontent.com/e4bd8d576857ff5078024831bc13638a786fd6da835504f24af7c68e0b49df44/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6d75746174696f6e25323074657374696e672d696e66656374696f6e2d677265656e)](https://github.com/dev404ai/drand-client-php/actions?query=workflow%3ACI)[![Latest Stable Version](https://camo.githubusercontent.com/7f6ec3236f00e59b62f8b85baedd5a904b5d5ed30ccd7fc031bce82680a861d8/68747470733a2f2f706f7365722e707567782e6f72672f64657634303461692f6472616e642d636c69656e742d7068702f762f737461626c65)](https://packagist.org/packages/dev404ai/drand-client-php)[![Total Downloads](https://camo.githubusercontent.com/1f0c300dcee1c60d3e65857c59ce4c08539b0e08179eae51c5888d0bdc9c2c57/68747470733a2f2f706f7365722e707567782e6f72672f64657634303461692f6472616e642d636c69656e742d7068702f646f776e6c6f616473)](https://packagist.org/packages/dev404ai/drand-client-php)[![License](https://camo.githubusercontent.com/f3808a8e8483694c261420e0c41a989b21119406ff7d31dd27162a65915dcd3b/68747470733a2f2f706f7365722e707567782e6f72672f64657634303461692f6472616e642d636c69656e742d7068702f6c6963656e7365)](https://packagist.org/packages/dev404ai/drand-client-php)[![PHP Version](https://camo.githubusercontent.com/e0cc071c12c13cbc361e00674946795e94dd5d5166a55d3f736cf9b307b05f28/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f64657634303461692f6472616e642d636c69656e742d706870)](https://packagist.org/packages/dev404ai/drand-client-php)[![Last Commit](https://camo.githubusercontent.com/cfdb6e08d29cfa4a267b6046f6ca8c815e53165eb2fbd6b3b7153432e95abf4c/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6173742d636f6d6d69742f64657634303461692f6472616e642d636c69656e742d7068702e737667)](https://github.com/dev404ai/drand-client-php/commits/main)[![PRs Welcome](https://camo.githubusercontent.com/25b3e6d0d42c98de74a98cbb4d149a1c09020cf6d1361993b72d7d5b8ffed363/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5052732d77656c636f6d652d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](https://makeapullrequest.com)

About
-----

[](#about)

A minimal-dependency PHP client for the [drand randomness beacon](https://drand.love), providing fast, verifiable, and unbiased public randomness. Supports all drand signature schemes, efficient BLS verification via libblst, and is suitable for blockchain, games, lotteries, and any application requiring cryptographically secure randomness. Easy to install, PSR-4 autoloaded, and fully tested with PHPUnit.

Table of Contents
-----------------

[](#table-of-contents)

- [Quick Install](#quick-install)
- [Usage Examples](#usage-examples)
- [Supported Signature Schemes](#supported-signature-schemes)
- [Configuration Enums](#configuration-enums)
- [Testing](#testing)
- [Contributing](#contributing)
- [License](#license)

A **minimal‑dependency** PHP client for the [drand randomness beacon](https://drand.love).

- Fast BLS‑signature verification via **libblst** (same core used by Ethereum 2).
- Supports all drand signature schemes: chained, unchained, G1, RFC9380, and BN254 (see below).
- No PECL modules — just enable **FFI**.
- Composer‑installable, PSR‑4, PHPUnit‑tested.

---

Use Cases
---------

[](#use-cases)

This library can be used wherever **verifiable, unbiased, and public randomness** is required, including:

- **Random number generation (RNG)**: Use as a source of entropy for applications needing strong, unpredictable randomness.
- **Blockchain and smart contracts**: Integrate with on-chain or off-chain systems that require public randomness.
- **Games and competitions**: Provide fair shuffling, matchmaking, or prize draws.
- **Auditable random selection**: Any scenario where you need to prove to users that the randomness was not manipulated.
- **Betting and gambling platforms**: Ensure fair, auditable outcomes for games and bets.
- **Online lotteries and raffles**: Draw winners transparently and provably at random.

Drand randomness is **public, distributed, and cryptographically verifiable**, making it suitable for regulated and high-stakes environments.

---

Supported Signature Schemes
---------------------------

[](#supported-signature-schemes)

This client supports all major drand signature schemes:

- `pedersen-bls-chained` (default, BLS12-381, chained)
- `pedersen-bls-unchained` (BLS12-381, unchained)
- `bls-unchained-on-g1` (BLS12-381, G1, legacy)
- `bls-unchained-g1-rfc9380` (BLS12-381, G1, RFC9380)
- `bn254-on-g1` (BN254, G1, experimental)

> **Note:**
>
> - For G1 and RFC9380 schemes, FFI and libblst are required.
> - The client automatically detects and verifies the correct scheme based on chain info.
> - BN254 support requires a separate backend (not included by default).

---

Quick install
-------------

[](#quick-install)

### 1. Install `libblst`

[](#1-install-libblst)

PlatformCommand**Ubuntu / Debian**`sudo apt install libblst-dev`**Arch Linux**`sudo pacman -S blst`**Alpine Linux**`apk add blst`**macOS (Homebrew)**`brew install blst`**Windows**Download **blst.dll** from the [releases](https://github.com/supranational/blst/releases) and copy it next to `php.exe` or into `%SystemRoot%\System32`.> **Important:** This project requires the [php-ffi](https://www.php.net/manual/en/book.ffi.php) extension. Make sure it is installed and enabled in your PHP environment.
>
> - On **Arch Linux**, install it with: ```
>     sudo pacman -S php-ffi
>     ```
> - On other systems, ensure the `ffi` extension is enabled in your `php.ini` (see below).
> - You can check if FFI is enabled by running: ```
>     php -m | grep ffi
>     ```
>
>
>
>     If you see `ffi` in the output, the extension is enabled.

Alternatively, build from source```
git clone https://github.com/supranational/blst.git
cd blst
./build.sh shared                               # creates libblst.{so|dylib|dll}
sudo cp build/*/generic/libblst.* /usr/local/lib
sudo ldconfig                                   # Linux only
```

### 2. Enable FFI

[](#2-enable-ffi)

```
# Permanent
echo "ffi.enable = true" | sudo tee /etc/php/conf.d/20-ffi.ini

# One‑off
php -dffi.enable=1 your_script.php
```

> **Reloading web SAPIs:**
> CLI picks the change immediately. For PHP‑FPM / Apache reload the service:
>
> ```
> # find your FPM unit
> systemctl list-units 'php*-fpm*'
>
> # e.g. php8.2-fpm
> sudo systemctl reload php8.2-fpm
>
> # Apache with mod_php
> sudo systemctl reload apache2
> ```

### 3. Install the client via Composer

[](#3-install-the-client-via-composer)

```
composer require dev404ai/drand-client-php
```

This pulls the latest tagged release and registers PSR‑4 autoloading.

> **Verify setup**
>
> ```
> php -m | grep ffi        # ffi
> php -r "new FFI(); echo 'FFI OK\n';"
> ```

---

Usage Examples
--------------

[](#usage-examples)

### Basic Usage

[](#basic-usage)

```
require 'vendor/autoload.php';

use Drand\Client\DrandClient;

// Create a client with default settings
$client = DrandClient::createDefault();

// Get the latest beacon (scheme is detected and verified automatically)
$beacon = $client->getLatestBeacon();
printf("Round %d: %s\n", $beacon->getRound(), $beacon->getRandomness());

// Get a specific round
$beacon = $client->getBeacon(12345);

// Get chain information
$chain = $client->getChain();
printf("Chain period: %d seconds\n", $chain->getPeriod());
printf("Signature scheme: %s\n", $chain->getSchemeID());
```

### Advanced Configuration

[](#advanced-configuration)

```
// Create a client with custom options
$client = DrandClient::createDefault(
    'https://api.drand.sh',  // Base URL
    [
        // Disable signature verification (not recommended for production)
        'disableBeaconVerification' => false,

        // Disable response caching
        'noCache' => false,

        // Verify chain hash and public key
        'chainVerificationParams' => [
            'chainHash' => '8990e7a9aaed2ffed73dbd7092123d6f289930540d7651336225dc172e51b2ce',
            'publicKey' => '868f005eb8e6e4ca0a47c8a77ceaa5309a47978a7c71bc5cce96366b5d7a569937c529eeda66c7293784a9402801af31'
        ],

        // HTTP request timeout in seconds
        'timeout' => 10
    ],
    true,           // Enable caching (default)
    300,            // Chain info cache TTL (5 minutes)
    30              // Beacon cache TTL (30 seconds)
);
```

### Working with Rounds and Time

[](#working-with-rounds-and-time)

```
// Get the round number for a specific time
$roundNumber = $client->roundAt(time() + 3600); // Round an hour from now

// Get the time when a round will be available
$roundTime = $client->roundTime(12345);
$whenAvailable = new DateTime("@$roundTime");

// Calculate current round
$currentRound = $client->roundAt();
```

### Error Handling

[](#error-handling)

```
try {
    $beacon = $client->getLatestBeacon();
} catch (\RuntimeException $e) {
    // Handle HTTP errors, verification failures, etc.
    error_log("Failed to get beacon: " . $e->getMessage());
} catch (\InvalidArgumentException $e) {
    // Handle invalid parameters
    error_log("Invalid parameters: " . $e->getMessage());
}
```

### Using the Caching Client Directly

[](#using-the-caching-client-directly)

```
use Drand\Client\HttpClient;
use Drand\Client\CachingHttpClient;

// Create HTTP client with caching
$httpClient = new HttpClient('https://api.drand.sh');
$cachingClient = new CachingHttpClient(
    $httpClient,
    300,  // Chain info TTL (5 minutes)
    30    // Beacon TTL (30 seconds)
);

// Clear cache if needed
$cachingClient->clearCache();
```

### Using Multiple Chains

[](#using-multiple-chains)

```
use Drand\Client\HttpClient;
use Drand\Client\MultiChainClient;

// Create clients for different drand networks
$mainnet = new HttpClient('https://api.drand.sh');
$testnet = new HttpClient('https://pl-us.testnet.drand.sh');

// Combine them into a MultiChainClient
$multi = new MultiChainClient([$mainnet, $testnet]);

// Select by chain hash or beaconID
$mainnetClient = $multi->forChainHash('8990e7a9aaed2ffed73dbd7092123d6f289930540d7651336225dc172e51b2ce');
$testnetClient = $multi->forBeaconID('default');

// Use as a regular client (default is the first one)
$beacon = $multi->getLatestBeacon();
```

### Using the Fastest Node

[](#using-the-fastest-node)

```
use Drand\Client\HttpClient;
use Drand\Client\FastestNodeClient;

// Create clients for several public endpoints
$clients = [
    new HttpClient('https://api.drand.sh'),
    new HttpClient('https://drand.cloudflare.com'),
    new HttpClient('https://drand.cloudflare.com/public')
];

// FastestNodeClient will always use the fastest node (auto-updated)
$fastest = new FastestNodeClient($clients);

$beacon = $fastest->getLatestBeacon();
printf("Fastest node randomness: %s\n", $beacon['randomness']);
```

### Selecting Network and Scheme via Configuration

[](#selecting-network-and-scheme-via-configuration)

You can use the built-in `Networks` class for easy selection of mainnet, testnet, or your own custom network:

```
use Drand\Client\DrandClient;
use Drand\Client\Networks;

// Mainnet
$client = DrandClient::createDefault(
    Networks::MAINNET['url'],
    [
        'chainVerificationParams' => Networks::MAINNET['chainVerificationParams']
    ]
);

// Testnet
$client = DrandClient::createDefault(
    Networks::TESTNET['url'],
    [
        'chainVerificationParams' => Networks::TESTNET['chainVerificationParams']
    ]
);

// Custom network
$client = DrandClient::createDefault(
    'https://your.custom.drand.node',
    [
        'chainVerificationParams' => [
            'chainHash' => 'your_chain_hash',
            'publicKey' => 'your_public_key'
        ]
    ]
);
```

The `chainVerificationParams` option ensures you are connecting to the correct network and using the correct signature scheme. The scheme is automatically detected from the chain info.

### Advanced Usage Examples

[](#advanced-usage-examples)

#### Fetch beacon by time

[](#fetch-beacon-by-time)

```
$round = $client->roundAt(time());
$beacon = $client->getBeacon($round);
printf("Randomness for round %d: %s\n", $round, $beacon->getRandomness());
```

#### Get time for a round

[](#get-time-for-a-round)

```
$round = 1000000;
$timestamp = $client->roundTime($round);
echo "Round $round will be available at: " . date('c', $timestamp) . "\n";
```

#### Print chain info and signature scheme

[](#print-chain-info-and-signature-scheme)

```
$chain = $client->getChain();
echo "Chain hash: " . $chain->getHash() . "\n";
echo "Signature scheme: " . $chain->getSchemeID() . "\n";
```

#### Use MultiChainClient and select by beaconID

[](#use-multichainclient-and-select-by-beaconid)

```
use Drand\Client\MultiChainClient;
use Drand\Client\HttpClient;
use Drand\Client\DrandClient;

$mainnet = new HttpClient(Drand\Client\Networks::MAINNET['url']);
$testnet = new HttpClient(Drand\Client\Networks::TESTNET['url']);
$multi = DrandClient::createMultiChain([$mainnet, $testnet]);

// Select mainnet by beaconID
$mainnetClient = $multi->getChain()->getHash() === Drand\Client\Networks::MAINNET['chainVerificationParams']['chainHash']
    ? $multi : null;
if ($mainnetClient) {
    $beacon = $mainnetClient->getBeacon(12345);
    echo "Mainnet randomness: " . $beacon->getRandomness() . "\n";
}
```

#### Use FastestNodeClient

[](#use-fastestnodeclient)

```
use Drand\Client\FastestNodeClient;

$clients = [
    new HttpClient('https://api.drand.sh'),
    new HttpClient('https://drand.cloudflare.com'),
];
$fastest = DrandClient::createFastestNode($clients);
$beacon = $fastest->getLatestBeacon();
echo "Fastest node randomness: " . $beacon->getRandomness() . "\n";
```

---

Configuration Enums
-------------------

[](#configuration-enums)

This library uses modern PHP 8.2+ enums for configuration:

- **Network**: `Drand\Client\Network::MAINNET`, `TESTNET`, `DEVNET` — for selecting network and beaconID.
- **VerificationMode**: `Drand\Client\VerificationMode::ENABLED` or `DISABLED` — for enabling/disabling beacon signature verification.
- **CachePolicy**: `Drand\Client\CachePolicy::ENABLED` or `DISABLED` — for enabling/disabling HTTP response caching.

### Example: Creating a client with enums

[](#example-creating-a-client-with-enums)

```
use Drand\Client\DrandClient;
use Drand\Client\Network;
use Drand\Client\VerificationMode;
use Drand\Client\CachePolicy;

$client = DrandClient::createDefault(
    Network::MAINNET->getDefaultUrl(),
    [
        'verificationMode' => VerificationMode::ENABLED,
        'cachePolicy' => CachePolicy::ENABLED,
        // 'chainVerificationParams' => ['chainHash' => '...', 'publicKey' => '...'],
    ]
);
```

### Example: Multi-chain client

[](#example-multi-chain-client)

```
$mainnet = new HttpClient(Network::MAINNET->getDefaultUrl());
$testnet = new HttpClient(Network::TESTNET->getDefaultUrl());
$multi = DrandClient::createMultiChain([
    $mainnet,
    $testnet,
], [
    'verificationMode' => VerificationMode::ENABLED
]);
```

### Example: Fastest node client

[](#example-fastest-node-client)

```
$client = DrandClient::createFastestNode([
    new HttpClient(Network::MAINNET->getDefaultUrl()),
    new HttpClient(Network::TESTNET->getDefaultUrl()),
], [
    'verificationMode' => VerificationMode::ENABLED
]);
```

---

Configuration Files
-------------------

[](#configuration-files)

- `infection.json.dist`: Template for Infection mutation testing configuration. Copy to `infection.json` to customize locally. Do **not** commit your local `infection.json`.

```
cp infection.json.dist infection.json
```

---

Contributing
------------

[](#contributing)

We welcome contributions and pull requests from the community!

For detailed contribution and testing guidelines, see [CONTRIBUTING.md](CONTRIBUTING.md).

**How to contribute:**

- **Pull Requests:** Pull requests are welcome! Please fork the repository and submit your changes via a PR. Describe your changes and reference any related issues.
- **Code style:** Follow PSR-12 and the project's existing conventions.
- **First-class callables:** Use first-class callable syntax (`$obj->method(...)`) for passing methods as callables in PHP 8.2+.
- **Tests:** Add or update tests for any new features or bugfixes. Ensure all tests pass.
- **Commits:** Use clear, descriptive commit messages in English.
- **Documentation:** Update the README and code comments as needed.
- **No unnecessary dependencies:** Keep the project minimal and focused.
- **Respect security best practices:** Never commit secrets or unsafe code.

For major changes, please open an issue first to discuss your proposal.

We appreciate your help in making this project better!

---

License
-------

[](#license)

This project is dual-licensed under the MIT and Apache 2.0 licenses:

- MIT License ([LICENSE-MIT](LICENSE-MIT) or )
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or )

You may use this project under the terms of either license.

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance50

Moderate activity, may be stable

Popularity1

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

356d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/4558f5cf4b14d0716712f720f7df9454711546d3930ae34fac2446e75a4ec8ab?d=identicon)[dev404ai](/maintainers/dev404ai)

---

Top Contributors

[![dev404ai](https://avatars.githubusercontent.com/u/166488493?v=4)](https://github.com/dev404ai "dev404ai (13 commits)")

---

Tags

phpRNGgameslotteryblockchainbeaconverifiableblsrandomnessdrandpublic randomness

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Psalm

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/dev404ai-drand-client-php/health.svg)

```
[![Health](https://phpackages.com/badges/dev404ai-drand-client-php/health.svg)](https://phpackages.com/packages/dev404ai-drand-client-php)
```

###  Alternatives

[savvot/random

Deterministic pseudo-random generators library with dozens of useful functions and several sources of randomness

21243.7k5](/packages/savvot-random)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
