leader_election

package module
v0.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 4, 2022 License: AGPL-3.0 Imports: 5 Imported by: 2

README

leader-election

License

This library is used by Chainpoint Core to deterministically elect a peer from a list of peers, given an identical source of entropy for all peers. This method of leader election does not require excessive peer-to-peer coordination or an odd number of peers. The election does not even need to take place at the same time for all peers, so long as all peers have the same peer list and entropy- this ensures similar results in case of highly asynchronous operation or network latency.

Install

This package requires Go modules.

go get github.com/chainpoint/leader-election

Usage

  1. Ensure all peers on your network receive identical sources of entropy during your desired election period. This can be a blockhash, a drand signature, or some other data common to all peers.
  2. Ensure all peers have an identical list of active peers during your desired election period. Many p2p libraries maintain this for you.
  3. Run the code below on all peers during your desired election period.
package main

import (
    "encoding/binary"
    "errors"
    "math/rand"
    "reflect"
    "sync"
    "fmt"
    "github.com/chainpoint/leader-election"
)

func main() {
    entropy := "ajdlfjad;lfkjad;kfj"
    peerList := []string{"peer", "peer1", "peer2", "peer3"}
    desiredNumLeaders := 1
    myPeerNameIs := "peer"

    // Return array consisting of desiredNumLeaders number of peers from peerList, given an entropy string
    result := leaderelection.ElectLeaders(peerList, desiredNumLeaders, entropy)
    fmt.Println(result)
    if len(result) > 0 and myPeerNameIs == result[0] {
        fmt.Println("I am leader!")
    }
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ElectLeaders

func ElectLeaders(slice interface{}, numLeaders int, seed string) interface{}

func GetSeededRandFloat

func GetSeededRandFloat(seedBytes []byte) float32

GetSeededRandFloat : Given a seed return a random float

func GetSeededRandInt

func GetSeededRandInt(seedBytes []byte, upperBound int) int

GetSeededRandInt : Given a seed and a maximum size, generates a random int between 0 and upperBound

func RotateLeft

func RotateLeft(slice interface{}, by int) error

RotateLeft is an alias for Rotate

func RotateRight

func RotateRight(slice interface{}, by int) error

RotateRight is the analogue to RotateLeft

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL