Skip to content

Mar/drandexample #7

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,5 @@
*.out

.idea/

node_modules/
24 changes: 24 additions & 0 deletions drandexample/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# drandexample
Example on how to use Drand as a client

# What, Why, How?
Created a small script to show & describe how to get random numbers from the drand network.

Example: Imagine you are a full time L5 software engineer and have more important things to think about than what to get for lunch.
You decide to leave it up to randomness to choose your next meal. But you still have preferences.
You assign weights to your preferences such that items you would like to eat most often have heavier weights (chances of being chosen)
And things you don't want to eat as often, have smaller probability of being chosen.

Things to note:
Drand mainnet releases a random number every 30 seconds. The problem that arises is if you want to test if the biased randomness works or not, it would take a really long time to test.
There is work to shorten this time frame to 3 seconds, which is better, but its not as convenient as instant access of psuedo-random numbers like math.random() or crypto.getRandomValues().

This script shortens down a `randomness` value from the network and uses it as a probability for selecting an item.

### Requirements
Node 12 and up

# Run
1. `npm install`

2. `node bias.js`
70 changes: 70 additions & 0 deletions drandexample/bias.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import Client, { HTTP } from 'drand-client';
import fetch from 'node-fetch';
import AbortController from 'abort-controller';

global.fetch = fetch;
global.AbortController = AbortController;

const chainHash = '8990e7a9aaed2ffed73dbd7092123d6f289930540d7651336225dc172e51b2ce'; // Mainnet chain hash (hex encoded)
const urls = [
'https://api.drand.sh',
'https://drand.cloudflare.com'
]; // various endpoint options to access Drand network.

const HEX = 16;
const FoodOptions = { "pho": 0.3, "croquets": 0.29, "pizza": 0.28, "pasta": 0.07, "molé_verde": 0.03, "shrimp": .03 };

// This function takes in a list of items and the probablilty of them being selected.
// returns the number that is randomly selected
async function weightedRandom(prob) {
if (validateWeights(prob) != 1) {
return "Weights not equal to 1"
}
const options = { chainHash };

const client = await Client.wrap(HTTP.forURLs(urls, chainHash), options);

// e.g. use the client to get the latest randomness round:
const res = await client.get();

// Get a number between 0 and 100 from Drand.
const rand = randomPercentFrom(res.randomness);

// This for loop selects which key:pair to return
let sum = 0, r = rand;
for (let [key, value] of Object.entries(prob)) {
sum += value * 100;
if (r <= sum) {
return key;
}
}
}

//runs code above
weightedRandom(FoodOptions).then((lunch) => (console.log(lunch)))
// Press Ctrl + C to stop example!

// This function returns a number between 0 & 99.
function randomPercentFrom(randomness) {
var i = 0;
var randomDecimal = -1;
var rand;

while (randomDecimal <= 0 || randomDecimal > 100) {
// Grab only 2 digits from randomness, in a "sliding window" fashion
rand = randomness.slice(0 + i, 2 + i);
// Convert hexadecimal randomness value to decimal (base16 -> base10)
randomDecimal = parseInt(rand, HEX);
i++;
}
return randomDecimal;
}

// This function checks the user input to make sure all probabilities add up to 1
function validateWeights(probabilities) {
var sum = 0;
for (let [_, value] of Object.entries(probabilities)) {
sum += value;
}
return sum;
}
189 changes: 189 additions & 0 deletions drandexample/package-lock.json

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

21 changes: 21 additions & 0 deletions drandexample/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "drandexample",
"version": "1.0.0",
"type": "module",
"description": "Example on how to use Drand",
"main": "bias.js",
"scripts": {
"test": "node bias.js"
},
"keywords": [
"drand",
"example"
],
"author": "Marco Rodriguez-Salinas",
"license": "MIT",
"dependencies": {
"abort-controller": "^3.0.0",
"drand-client": "^0.2.0",
"node-fetch": "^3.2.10"
}
}