|
| 1 | +package randomness |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/hex" |
| 6 | + "fmt" |
| 7 | + |
| 8 | + "github.com/drand/go-clients/client" |
| 9 | + "github.com/drand/go-clients/client/http" |
| 10 | + "github.com/drand/go-clients/drand" |
| 11 | +) |
| 12 | + |
| 13 | +// drandProvider implements BeaconProvider by retrieving randomness from drand network. |
| 14 | +type drandProvider struct { |
| 15 | + client drand.Client |
| 16 | +} |
| 17 | + |
| 18 | +// newDrandProvider initializes the randomness module. It connects to the drand network, so random value can be |
| 19 | +// obtained with GetBeacon. |
| 20 | +func newDrandProvider() (*drandProvider, error) { |
| 21 | + httpClient, err := http.NewSimpleClient(apiHost, chainHash) |
| 22 | + if err != nil { |
| 23 | + panic(err) |
| 24 | + } |
| 25 | + chb, err := hex.DecodeString(chainHash) |
| 26 | + if err != nil { |
| 27 | + panic(err) |
| 28 | + } |
| 29 | + |
| 30 | + p := drandProvider{} |
| 31 | + p.client, err = client.New( |
| 32 | + client.From(httpClient), |
| 33 | + client.WithChainHash(chb), |
| 34 | + ) |
| 35 | + if err != nil { |
| 36 | + panic(err) |
| 37 | + } |
| 38 | + |
| 39 | + return &p, nil |
| 40 | +} |
| 41 | + |
| 42 | +// GetBeacon returns the 32 bytes of randomness. |
| 43 | +func (d *drandProvider) GetBeacon() []byte { |
| 44 | + const mostRecentKnownRound = 0 |
| 45 | + r, err := d.client.Get(context.Background(), mostRecentKnownRound) |
| 46 | + if err != nil { |
| 47 | + panic(err) |
| 48 | + } |
| 49 | + |
| 50 | + beacon := r.GetRandomness() |
| 51 | + if len(beacon) != 32 { |
| 52 | + panic(fmt.Errorf("randomness: expected 32 bytes, got %d", len(beacon))) |
| 53 | + } |
| 54 | + if beacon == nil { |
| 55 | + panic(fmt.Errorf("randomness: drand did not return randomness")) |
| 56 | + } |
| 57 | + |
| 58 | + return beacon |
| 59 | +} |
0 commit comments