Skip to content
Snippets Groups Projects
Commit 7dabac21 authored by capossele's avatar capossele
Browse files

:ok_hand: Updates code due to code review changes

parent b9a3b3e3
No related branches found
No related tags found
No related merge requests found
Showing
with 204 additions and 291 deletions
......@@ -13,9 +13,10 @@ import (
"github.com/iotaledger/hive.go/marshalutil"
)
func (drng *Instance) Dispatch(issuer ed25519.PublicKey, timestamp time.Time, payload *payload.Payload) error {
switch payload.SubType() {
case header.CollectiveBeaconType():
// Dispatch parses a DRNG message and process it based on its subtype
func (drng *DRNG) Dispatch(issuer ed25519.PublicKey, timestamp time.Time, payload *payload.Payload) error {
switch payload.Header.PayloadType {
case header.TypeCollectiveBeacon:
// parse as CollectiveBeaconType
marshalUtil := marshalutil.New(payload.Bytes())
parsedPayload, err := cb.Parse(marshalUtil)
......@@ -26,11 +27,11 @@ func (drng *Instance) Dispatch(issuer ed25519.PublicKey, timestamp time.Time, pa
cbEvent := &events.CollectiveBeaconEvent{
IssuerPublicKey: issuer,
Timestamp: timestamp,
InstanceID: parsedPayload.Instance(),
Round: parsedPayload.Round(),
PrevSignature: parsedPayload.PrevSignature(),
Signature: parsedPayload.Signature(),
Dpk: parsedPayload.DistributedPK(),
InstanceID: parsedPayload.Header.InstanceID,
Round: parsedPayload.Round,
PrevSignature: parsedPayload.PrevSignature,
Signature: parsedPayload.Signature,
Dpk: parsedPayload.Dpk,
}
drng.Events.CollectiveBeacon.Trigger(cbEvent)
......@@ -45,7 +46,6 @@ func (drng *Instance) Dispatch(issuer ed25519.PublicKey, timestamp time.Time, pa
return nil
default:
//do other stuff
return errors.New("subtype not implemented")
}
}
......@@ -31,7 +31,7 @@ func init() {
dpkTest, _ = hex.DecodeString("a02fcd15edd52c8e134027491a43b597505b466d1679e88f70f927e57c45a93ae0765ff02fc2d015e3a02fd8748e2103")
timestampTest = time.Now()
rand, _ := collectiveBeacon.GetRandomness(signatureTest)
rand, _ := collectiveBeacon.ExtractRandomness(signatureTest)
randomnessTest = &state.Randomness{
Round: 1,
Randomness: rand,
......@@ -50,8 +50,8 @@ func init() {
}
func dummyPayload() *cbPayload.Payload {
header := header.New(header.CollectiveBeaconType(), 1)
return cbPayload.New(header.Instance(),
header := header.New(header.TypeCollectiveBeacon, 1)
return cbPayload.New(header.InstanceID,
1,
prevSignatureTest,
signatureTest,
......
......@@ -2,17 +2,23 @@ package drng
import (
"github.com/iotaledger/goshimmer/packages/binary/drng/state"
cbEvents "github.com/iotaledger/goshimmer/packages/binary/drng/subtypes/collectiveBeacon/events"
"github.com/iotaledger/hive.go/events"
)
type Instance struct {
State *state.State
Events *Event
// DRNG holds the state and events of a drng instance.
type DRNG struct {
State *state.State // The state of the DRNG.
Events *Event // The events fired on the DRNG.
}
// New creates a new DRNG instance.
func New(setters ...state.Option) *Instance {
return &Instance{
State: state.New(setters...),
Events: NewEvent(),
func New(setters ...state.Option) *DRNG {
return &DRNG{
State: state.New(setters...),
Events: &Event{
CollectiveBeacon: events.NewEvent(cbEvents.CollectiveBeaconReceived),
Randomness: events.NewEvent(randomnessReceived),
},
}
}
......@@ -2,20 +2,15 @@ package drng
import (
"github.com/iotaledger/goshimmer/packages/binary/drng/state"
cbEvents "github.com/iotaledger/goshimmer/packages/binary/drng/subtypes/collectiveBeacon/events"
"github.com/iotaledger/hive.go/events"
)
// Event holds the different events triggered by a DRNG instance.
type Event struct {
CollectiveBeacon cbEvents.CollectiveBeacon
Randomness *events.Event
}
func NewEvent() *Event {
return &Event{
CollectiveBeacon: cbEvents.NewCollectiveBeaconEvent(),
Randomness: events.NewEvent(randomnessReceived),
}
// Collective Beacon is triggered each time we receive a new CollectiveBeacon message.
CollectiveBeacon *events.Event
// Randomness is triggered each time we receive a new and valid CollectiveBeacon message.
Randomness *events.Event
}
func randomnessReceived(handler interface{}, params ...interface{}) {
......
......@@ -4,49 +4,38 @@ import (
"github.com/iotaledger/hive.go/marshalutil"
)
// Type defines the data model of a DRNG payload type
type Type = byte
type payloadType struct {
CollectiveBeacon Type
}
var drngTypes = &payloadType{
CollectiveBeacon: Type(1),
}
const (
// TypeCollectiveBeacon defines a CollectiveBeacon payload type
TypeCollectiveBeacon Type = 1
)
// Length defines the length of a DRNG header
const Length = 5
func CollectiveBeaconType() Type {
return drngTypes.CollectiveBeacon
}
// Header defines defines a DRNG payload header
type Header struct {
payloadType Type // message type
instanceID uint32 // identifier of the dRAND instance
PayloadType Type // message type
InstanceID uint32 // identifier of the DRNG instance
}
// New creates a new DRNG payload header for the given type and instance id.
func New(payloadType Type, instanceID uint32) Header {
return Header{
payloadType: payloadType,
instanceID: instanceID,
PayloadType: payloadType,
InstanceID: instanceID,
}
}
func (h Header) PayloadType() Type {
return h.payloadType
}
func (h Header) Instance() uint32 {
return h.instanceID
}
// Parse is a wrapper for simplified unmarshaling in a byte stream using the marshalUtil package.
func Parse(marshalUtil *marshalutil.MarshalUtil) (Header, error) {
if header, err := marshalUtil.Parse(func(data []byte) (interface{}, error, int) { return FromBytes(data) }); err != nil {
header, err := marshalUtil.Parse(func(data []byte) (interface{}, error, int) { return FromBytes(data) })
if err != nil {
return Header{}, err
} else {
return header.(Header), nil
}
return header.(Header), nil
}
// FromBytes unmarshals a header from a sequence of bytes.
......@@ -67,12 +56,12 @@ func FromBytes(bytes []byte, optionalTargetObject ...*Header) (result Header, er
marshalUtil := marshalutil.New(bytes)
// read payload type from bytes
if targetObject.payloadType, err = marshalUtil.ReadByte(); err != nil {
if targetObject.PayloadType, err = marshalUtil.ReadByte(); err != nil {
return
}
// read instance ID from bytes
if targetObject.instanceID, err = marshalUtil.ReadUint32(); err != nil {
if targetObject.InstanceID, err = marshalUtil.ReadUint32(); err != nil {
return
}
......@@ -85,13 +74,14 @@ func FromBytes(bytes []byte, optionalTargetObject ...*Header) (result Header, er
return
}
// Bytes returns the header in serialized bytes form.
func (header *Header) Bytes() (bytes []byte) {
// initialize helper
marshalUtil := marshalutil.New()
// marshal the payload specific information
marshalUtil.WriteByte(header.PayloadType())
marshalUtil.WriteUint32(header.Instance())
marshalUtil.WriteByte(header.PayloadType)
marshalUtil.WriteUint32(header.InstanceID)
bytes = marshalUtil.Bytes()
......
......@@ -8,7 +8,7 @@ import (
)
func TestParse(t *testing.T) {
header := New(CollectiveBeaconType(), 0)
header := New(TypeCollectiveBeacon, 0)
bytes := header.Bytes()
marshalUtil := marshalutil.New(bytes)
......
......@@ -9,33 +9,23 @@ import (
"github.com/iotaledger/hive.go/stringify"
)
// Payload defines a DRNG payload.
type Payload struct {
header header.Header
data []byte
header.Header
Data []byte
bytes []byte
bytesMutex sync.RWMutex
}
// New creates a new DRNG payload.
func New(header header.Header, data []byte) *Payload {
return &Payload{
header: header,
data: data,
Header: header,
Data: data,
}
}
func (p *Payload) SubType() header.Type {
return p.header.PayloadType()
}
func (payload *Payload) Instance() uint32 {
return payload.header.Instance()
}
func (payload *Payload) Data() []byte {
return payload.data
}
// Parse is a wrapper for simplified unmarshaling in a byte stream using the marshalUtil package.
func Parse(marshalUtil *marshalutil.MarshalUtil) (*Payload, error) {
if payload, err := marshalUtil.Parse(func(data []byte) (interface{}, error, int) { return FromBytes(data) }); err != nil {
......@@ -72,12 +62,12 @@ func FromBytes(bytes []byte, optionalTargetObject ...*Payload) (result *Payload,
}
// parse header
if result.header, err = header.Parse(marshalUtil); err != nil {
if result.Header, err = header.Parse(marshalUtil); err != nil {
return
}
// parse data
if result.data, err = marshalUtil.ReadBytes(int(len - header.Length)); err != nil {
if result.Data, err = marshalUtil.ReadBytes(int(len - header.Length)); err != nil {
return
}
......@@ -96,7 +86,7 @@ func (payload *Payload) Bytes() (bytes []byte) {
// return if bytes have been determined already
if bytes = payload.bytes; bytes != nil {
defer payload.bytesMutex.RUnlock()
payload.bytesMutex.RUnlock()
return
}
......@@ -114,9 +104,9 @@ func (payload *Payload) Bytes() (bytes []byte) {
// marshal the payload specific information
marshalUtil.WriteUint32(Type)
marshalUtil.WriteUint32(uint32(len(payload.data) + header.Length))
marshalUtil.WriteBytes(payload.header.Bytes())
marshalUtil.WriteBytes(payload.data[:])
marshalUtil.WriteUint32(uint32(len(payload.Data) + header.Length))
marshalUtil.WriteBytes(payload.Header.Bytes())
marshalUtil.WriteBytes(payload.Data[:])
bytes = marshalUtil.Bytes()
......@@ -125,9 +115,9 @@ func (payload *Payload) Bytes() (bytes []byte) {
func (payload *Payload) String() string {
return stringify.Struct("Payload",
stringify.StructField("type", uint64(payload.SubType())),
stringify.StructField("instance", uint64(payload.Instance())),
stringify.StructField("data", payload.Data()),
stringify.StructField("type", uint64(payload.Header.PayloadType)),
stringify.StructField("instance", uint64(payload.Header.InstanceID)),
stringify.StructField("data", payload.Data),
)
}
......@@ -158,7 +148,4 @@ func init() {
})
}
// define contract (ensure that the struct fulfills the corresponding interface)
var _ payload.Payload = &Payload{}
// // endregion ///////////////////////////////////////////////////////////////////////////////////////////////////////////
......@@ -9,7 +9,7 @@ import (
)
func dummyPayload() *Payload {
header := header.New(header.CollectiveBeaconType(), 0)
header := header.New(header.TypeCollectiveBeacon, 0)
data := []byte("test")
return New(header, data)
}
......@@ -22,9 +22,9 @@ func TestParse(t *testing.T) {
parsedPayload, err := Parse(marshalUtil)
require.NoError(t, err)
require.Equal(t, payload.SubType(), parsedPayload.SubType())
require.Equal(t, payload.Instance(), parsedPayload.Instance())
require.Equal(t, payload.Data(), parsedPayload.Data())
require.Equal(t, payload.Header.PayloadType, parsedPayload.Header.PayloadType)
require.Equal(t, payload.Header.InstanceID, parsedPayload.Header.InstanceID)
require.Equal(t, payload.Data, parsedPayload.Data)
}
func TestString(t *testing.T) {
......
package state
// Options define state options of a DRNG.
type Options struct {
Committee *Committee
// The initial committee of the DRNG.
Committee *Committee
// The initial randomness of the DRNG.
Randomness *Randomness
}
// Option is a function which sets the given option.
type Option func(*Options)
// SetCommittee sets the initial committee
......
......@@ -8,23 +8,34 @@ import (
"github.com/iotaledger/hive.go/crypto/ed25519"
)
// Randomness defines the current randomness state of a DRNG instance.
type Randomness struct {
Round uint64
// Round holds the current DRNG round.
Round uint64
// Randomness holds the current randomness as a slice of bytes.
Randomness []byte
Timestamp time.Time
// Timestamp holds the timestamp when the current randomness was received.
Timestamp time.Time
}
// Float64 returns a float64 [0.0,1.0) rapresentation of the randomness byte slice
// Float64 returns a float64 [0.0,1.0) representation of the randomness byte slice.
func (r Randomness) Float64() float64 {
return float64(binary.BigEndian.Uint64(r.Randomness[:8])>>11) / (1 << 53)
}
// Committee defines the current committee state of a DRNG instance.
type Committee struct {
InstanceID uint32
Threshold uint8
Identities []ed25519.PublicKey
// InstanceID holds the identifier of the dRAND instance.
InstanceID uint32
// Threshold holds the threshold of the secret sharing protocol.
Threshold uint8
// Identities holds the nodes' identities of the committee members.
Identities []ed25519.PublicKey
// DistributedPK holds the drand distributed public key.
DistributedPK []byte
}
// The state of the DRNG.
type State struct {
randomness *Randomness
committee *Committee
......@@ -32,6 +43,7 @@ type State struct {
mutex sync.RWMutex
}
// New creates a new State with the given optional options
func New(setters ...Option) *State {
args := &Options{}
......@@ -44,12 +56,14 @@ func New(setters ...Option) *State {
}
}
func (s *State) SetRandomness(r *Randomness) {
// UpdateRandomness updates the randomness of the DRNG state
func (s *State) UpdateRandomness(r *Randomness) {
s.mutex.Lock()
defer s.mutex.Unlock()
s.randomness = r
}
// Randomness returns the randomness of the DRNG state
func (s *State) Randomness() Randomness {
s.mutex.RLock()
defer s.mutex.RUnlock()
......@@ -59,12 +73,14 @@ func (s *State) Randomness() Randomness {
return *s.randomness
}
func (s *State) SetCommittee(c *Committee) {
// Update committee updates the committee of the DRNG state
func (s *State) UpdateCommittee(c *Committee) {
s.mutex.Lock()
defer s.mutex.Unlock()
s.committee = c
}
// Committee returns the committee of the DRNG state
func (s *State) Committee() Committee {
s.mutex.RLock()
defer s.mutex.RUnlock()
......
......@@ -32,12 +32,12 @@ func TestState(t *testing.T) {
// committee setters - getters
newCommittee := &Committee{1, 1, []ed25519.PublicKey{}, []byte{11}}
stateTest.SetCommittee(newCommittee)
stateTest.UpdateCommittee(newCommittee)
require.Equal(t, *newCommittee, stateTest.Committee())
// randomness setters - getters
newRandomness := &Randomness{1, []byte{123}, time.Now()}
stateTest.SetRandomness(newRandomness)
stateTest.UpdateRandomness(newRandomness)
require.Equal(t, *newRandomness, stateTest.Randomness())
}
......
......@@ -12,7 +12,16 @@ import (
"github.com/iotaledger/hive.go/crypto/ed25519"
)
// ProcessTransaction performs the following tasks:
var (
ErrDistributedPubKeyMismatch = errors.New("Distributed Public Key does not match")
ErrInvalidRound = errors.New("Invalid Round")
ErrInstanceIdMismatch = errors.New("InstanceID does not match")
ErrInvalidIssuer = errors.New("Invalid Issuer")
ErrNilState = errors.New("Nil state")
ErrNilData = errors.New("Nil data")
)
// ProcessBeacon performs the following tasks:
// - verify that we have a valid random
// - update drng state
func ProcessBeacon(drng *state.State, cb *events.CollectiveBeaconEvent) error {
......@@ -24,7 +33,7 @@ func ProcessBeacon(drng *state.State, cb *events.CollectiveBeaconEvent) error {
}
// update drng state
randomness, err := GetRandomness(cb.Signature)
randomness, err := ExtractRandomness(cb.Signature)
if err != nil {
//TODO: handle error
return err
......@@ -35,29 +44,36 @@ func ProcessBeacon(drng *state.State, cb *events.CollectiveBeaconEvent) error {
Timestamp: cb.Timestamp,
}
drng.SetRandomness(newRandomness)
drng.UpdateRandomness(newRandomness)
return nil
}
// VerifyCollectiveBeacon verifies against a given state that
// the given CollectiveBeaconEvent contains a valid beacon
// the given CollectiveBeaconEvent contains a valid beacon.
func VerifyCollectiveBeacon(state *state.State, data *events.CollectiveBeaconEvent) error {
if state == nil {
return ErrNilState
}
if data == nil {
return ErrNilData
}
if err := verifyIssuer(state, data.IssuerPublicKey); err != nil {
return err
}
if !bytes.Equal(data.Dpk, state.Committee().DistributedPK) {
return errors.New("Distributed Public Key does not match")
return ErrDistributedPubKeyMismatch
}
if data.Round <= state.Randomness().Round {
return errors.New("invalid Round")
return ErrInvalidRound
}
if data.InstanceID != state.Committee().InstanceID {
return errors.New("invalid instanceID")
return ErrInstanceIdMismatch
}
if err := verifySignature(data); err != nil {
......@@ -67,22 +83,18 @@ func VerifyCollectiveBeacon(state *state.State, data *events.CollectiveBeaconEve
return nil
}
// verifyIssuer checks the given issuer is a member of the committee
// verifyIssuer checks the given issuer is a member of the committee.
func verifyIssuer(state *state.State, issuer ed25519.PublicKey) error {
for _, member := range state.Committee().Identities {
if member == issuer {
return nil
}
}
return errors.New("Invalid Issuer")
return ErrInvalidIssuer
}
// verifySignature checks the current signature against the distributed public key
// verifySignature checks the current signature against the distributed public key.
func verifySignature(data *events.CollectiveBeaconEvent) error {
if data == nil {
return errors.New("nil data")
}
dpk := key.KeyGroup.Point()
if err := dpk.UnmarshalBinary(data.Dpk); err != nil {
return err
......@@ -97,8 +109,8 @@ func verifySignature(data *events.CollectiveBeaconEvent) error {
return nil
}
// GetRandomness returns the randomness from a given signature
func GetRandomness(signature []byte) ([]byte, error) {
// ExtractRandomness returns the randomness from a given signature.
func ExtractRandomness(signature []byte) ([]byte, error) {
hash := sha512.New()
if _, err := hash.Write(signature); err != nil {
return nil, err
......
......@@ -45,14 +45,12 @@ func init() {
}
func TestVerifySignature(t *testing.T) {
//payload := dkgShares(t, 5, 3)
err := verifySignature(eventTest)
require.NoError(t, err)
}
func TestGetRandomness(t *testing.T) {
//payload := dkgShares(t, 5, 3)
_, err := GetRandomness(eventTest.Signature)
_, err := ExtractRandomness(eventTest.Signature)
require.NoError(t, err)
}
......@@ -60,69 +58,3 @@ func TestProcessBeacon(t *testing.T) {
err := ProcessBeacon(stateTest, eventTest)
require.NoError(t, err)
}
// func dkgShares(t *testing.T, n, threshold int) *collectiveBeacon.Payload {
// var priPoly *share.PriPoly
// var pubPoly *share.PubPoly
// var err error
// // create shares and commitments
// for i := 0; i < n; i++ {
// pri := share.NewPriPoly(key.KeyGroup, threshold, key.KeyGroup.Scalar().Pick(random.New()), random.New())
// pub := pri.Commit(key.KeyGroup.Point().Base())
// if priPoly == nil {
// priPoly = pri
// pubPoly = pub
// continue
// }
// priPoly, err = priPoly.Add(pri)
// require.NoError(t, err)
// pubPoly, err = pubPoly.Add(pub)
// require.NoError(t, err)
// }
// shares := priPoly.Shares(n)
// secret, err := share.RecoverSecret(key.KeyGroup, shares, threshold, n)
// require.NoError(t, err)
// require.True(t, secret.Equal(priPoly.Secret()))
// msg := []byte("first message")
// sigs := make([][]byte, n, n)
// _, commits := pubPoly.Info()
// dkgShares := make([]*key.Share, n, n)
// // partial signatures
// for i := 0; i < n; i++ {
// sigs[i], err = key.Scheme.Sign(shares[i], msg)
// require.NoError(t, err)
// dkgShares[i] = &key.Share{
// Share: shares[i],
// Commits: commits,
// }
// }
// // reconstruct collective signature
// sig, err := key.Scheme.Recover(pubPoly, msg, sigs, threshold, n)
// require.NoError(t, err)
// // verify signature against distributed public key
// err = key.Scheme.VerifyRecovered(pubPoly.Commit(), msg, sig)
// require.NoError(t, err)
// msg = beacon.Message(sig, 1)
// sigs = make([][]byte, n, n)
// // partial signatures
// for i := 0; i < n; i++ {
// sigs[i], err = key.Scheme.Sign(shares[i], msg)
// require.NoError(t, err)
// }
// // reconstruct collective signature
// newSig, err := key.Scheme.Recover(pubPoly, msg, sigs, threshold, n)
// require.NoError(t, err)
// dpk, err := pubPoly.Commit().MarshalBinary()
// require.NoError(t, err)
// return collectiveBeacon.New(1, 1, sig, newSig, dpk)
// }
......@@ -4,25 +4,27 @@ import (
"time"
"github.com/iotaledger/hive.go/crypto/ed25519"
"github.com/iotaledger/hive.go/events"
)
type CollectiveBeacon = *events.Event
func NewCollectiveBeaconEvent() *events.Event {
return events.NewEvent(collectiveBeaconReceived)
}
// CollectiveBeaconEvent holds data about a collective beacon event.
type CollectiveBeaconEvent struct {
IssuerPublicKey ed25519.PublicKey // public key of the issuer
Timestamp time.Time // timestamp when the beacon was issued
InstanceID uint32 // instanceID of the beacon
Round uint64 // round of the current beacon
PrevSignature []byte // collective signature of the previous beacon
Signature []byte // collective signature of the current beacon
Dpk []byte // distributed public key
// Public key of the issuer.
IssuerPublicKey ed25519.PublicKey
// Timestamp when the beacon was issued.
Timestamp time.Time
// InstanceID of the beacon.
InstanceID uint32
// Round of the current beacon.
Round uint64
// Collective signature of the previous beacon.
PrevSignature []byte
// Collective signature of the current beacon.
Signature []byte
// The distributed public key.
Dpk []byte
}
func collectiveBeaconReceived(handler interface{}, params ...interface{}) {
// CollectiveBeaconReceived returns the data of a collective beacon event.
func CollectiveBeaconReceived(handler interface{}, params ...interface{}) {
handler.(func(*CollectiveBeaconEvent))(params[0].(*CollectiveBeaconEvent))
}
......@@ -11,7 +11,7 @@ import (
func TestCollectiveBeaconEvent(t *testing.T) {
var cbReceived *CollectiveBeaconEvent
eventTest := NewCollectiveBeaconEvent()
eventTest := events.NewEvent(CollectiveBeaconReceived)
eventTest.Attach(events.NewClosure(func(cb *CollectiveBeaconEvent) {
cbReceived = cb
......
package payload
const (
// BLS Signature size in bytes
// BLS Signature size in bytes.
SignatureSize = 96
// BLS Public Key size in bytes
// BLS Public Key size in bytes.
PublicKeySize = 48
)
......@@ -11,53 +11,34 @@ import (
"github.com/iotaledger/hive.go/marshalutil"
)
// Payload is a collective beacon payload.
type Payload struct {
//objectstorage.StorableObjectFlags
header header.Header
round uint64 // round of the current beacon
prevSignature []byte // collective signature of the previous beacon
signature []byte // collective signature of the current beacon
dpk []byte // distributed public key
bytes []byte
bytesMutex sync.RWMutex
header.Header
// Round of the current beacon
Round uint64
// Collective signature of the previous beacon
PrevSignature []byte
// Collective signature of the current beacon
Signature []byte
// The distributed public key
Dpk []byte
bytes []byte
bytesMutex sync.RWMutex
}
// New creates a new collective beacon payload.
func New(instanceID uint32, round uint64, prevSignature, signature, dpk []byte) *Payload {
return &Payload{
header: header.New(header.CollectiveBeaconType(), instanceID),
round: round,
prevSignature: prevSignature,
signature: signature,
dpk: dpk,
Header: header.New(header.TypeCollectiveBeacon, instanceID),
Round: round,
PrevSignature: prevSignature,
Signature: signature,
Dpk: dpk,
}
}
func (p *Payload) SubType() header.Type {
return p.header.PayloadType()
}
func (payload *Payload) Instance() uint32 {
return payload.header.Instance()
}
func (payload *Payload) Round() uint64 {
return payload.round
}
func (payload *Payload) PrevSignature() []byte {
return payload.prevSignature
}
func (payload *Payload) Signature() []byte {
return payload.signature
}
func (payload *Payload) DistributedPK() []byte {
return payload.dpk
}
// Parse is a wrapper for simplified unmarshaling in a byte stream using the marshalUtil package.
func Parse(marshalUtil *marshalutil.MarshalUtil) (*Payload, error) {
if payload, err := marshalUtil.Parse(func(data []byte) (interface{}, error, int) { return FromBytes(data) }); err != nil {
......@@ -92,27 +73,27 @@ func FromBytes(bytes []byte, optionalTargetObject ...*Payload) (result *Payload,
}
// parse header
if result.header, err = header.Parse(marshalUtil); err != nil {
if result.Header, err = header.Parse(marshalUtil); err != nil {
return
}
// parse round
if result.round, err = marshalUtil.ReadUint64(); err != nil {
if result.Round, err = marshalUtil.ReadUint64(); err != nil {
return
}
// parse prevSignature
if result.prevSignature, err = marshalUtil.ReadBytes(SignatureSize); err != nil {
if result.PrevSignature, err = marshalUtil.ReadBytes(SignatureSize); err != nil {
return
}
// parse current signature
if result.signature, err = marshalUtil.ReadBytes(SignatureSize); err != nil {
if result.Signature, err = marshalUtil.ReadBytes(SignatureSize); err != nil {
return
}
// parse distributed public key
if result.dpk, err = marshalUtil.ReadBytes(PublicKeySize); err != nil {
if result.Dpk, err = marshalUtil.ReadBytes(PublicKeySize); err != nil {
return
}
......@@ -131,7 +112,7 @@ func (payload *Payload) Bytes() (bytes []byte) {
// return if bytes have been determined already
if bytes = payload.bytes; bytes != nil {
defer payload.bytesMutex.RUnlock()
payload.bytesMutex.RUnlock()
return
}
......@@ -150,11 +131,11 @@ func (payload *Payload) Bytes() (bytes []byte) {
marshalUtil := marshalutil.New(marshalutil.UINT32_SIZE + marshalutil.UINT32_SIZE + payloadLength)
marshalUtil.WriteUint32(drngPayload.Type)
marshalUtil.WriteUint32(uint32(payloadLength))
marshalUtil.WriteBytes(payload.header.Bytes())
marshalUtil.WriteUint64(payload.Round())
marshalUtil.WriteBytes(payload.PrevSignature())
marshalUtil.WriteBytes(payload.Signature())
marshalUtil.WriteBytes(payload.DistributedPK())
marshalUtil.WriteBytes(payload.Header.Bytes())
marshalUtil.WriteUint64(payload.Round)
marshalUtil.WriteBytes(payload.PrevSignature)
marshalUtil.WriteBytes(payload.Signature)
marshalUtil.WriteBytes(payload.Dpk)
bytes = marshalUtil.Bytes()
......@@ -166,12 +147,12 @@ func (payload *Payload) Bytes() (bytes []byte) {
func (payload *Payload) String() string {
return stringify.Struct("Payload",
stringify.StructField("type", uint64(payload.SubType())),
stringify.StructField("instance", uint64(payload.Instance())),
stringify.StructField("round", payload.Round()),
stringify.StructField("prevSignature", payload.PrevSignature()),
stringify.StructField("signature", payload.Signature()),
stringify.StructField("distributedPK", payload.DistributedPK()),
stringify.StructField("type", uint64(payload.Header.PayloadType)),
stringify.StructField("instance", uint64(payload.Header.InstanceID)),
stringify.StructField("round", payload.Round),
stringify.StructField("prevSignature", payload.PrevSignature),
stringify.StructField("signature", payload.Signature),
stringify.StructField("distributedPK", payload.Dpk),
)
}
......@@ -191,16 +172,4 @@ func (payload *Payload) Unmarshal(data []byte) (err error) {
return
}
// func init() {
// payload.RegisterType(drngPayload.Type, func(data []byte) (payload payload.Payload, err error) {
// payload = &Payload{}
// err = payload.UnmarshalBinary(data)
// return
// })
// }
// define contract (ensure that the struct fulfills the corresponding interface)
var _ payload.Payload = &Payload{}
// // endregion ///////////////////////////////////////////////////////////////////////////////////////////////////////////
......@@ -9,8 +9,8 @@ import (
)
func dummyPayload() *Payload {
header := header.New(header.CollectiveBeaconType(), 0)
return New(header.Instance(),
header := header.New(header.TypeCollectiveBeacon, 0)
return New(header.InstanceID,
0,
[]byte("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"), // prevSignature
[]byte("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"), // signature
......@@ -25,12 +25,12 @@ func TestParse(t *testing.T) {
parsedPayload, err := Parse(marshalUtil)
require.NoError(t, err)
require.Equal(t, payload.SubType(), parsedPayload.SubType())
require.Equal(t, payload.Instance(), parsedPayload.Instance())
require.Equal(t, payload.Round(), parsedPayload.Round())
require.Equal(t, payload.PrevSignature(), parsedPayload.PrevSignature())
require.Equal(t, payload.Signature(), parsedPayload.Signature())
require.Equal(t, payload.DistributedPK(), parsedPayload.DistributedPK())
require.Equal(t, payload.Header.PayloadType, parsedPayload.Header.PayloadType)
require.Equal(t, payload.Header.InstanceID, parsedPayload.Header.InstanceID)
require.Equal(t, payload.Round, parsedPayload.Round)
require.Equal(t, payload.PrevSignature, parsedPayload.PrevSignature)
require.Equal(t, payload.Signature, parsedPayload.Signature)
require.Equal(t, payload.Dpk, parsedPayload.Dpk)
}
func TestString(t *testing.T) {
......
......@@ -15,7 +15,7 @@ var (
)
func parseCommitteeMembers() (result []ed25519.PublicKey, err error) {
for _, committeeMember := range config.Node.GetStringSlice(CFG_COMMITTEE_MEMBERS) {
for _, committeeMember := range config.Node.GetStringSlice(CfgDRNGCommitteeMembers) {
if committeeMember == "" {
continue
}
......
......@@ -5,15 +5,15 @@ import (
)
const (
CFG_INSTANCE_ID = "drng.instanceId"
CFG_THRESHOLD = "drng.threshold"
CFG_DISTRIBUTED_PUB_KEY = "drng.distributedPubKey"
CFG_COMMITTEE_MEMBERS = "drng.committeeMembers"
CfgDRNGInstanceID = "drng.instanceId"
CfgDRNGThreshold = "drng.threshold"
CfgDRNGDistributedPubKey = "drng.distributedPubKey"
CfgDRNGCommitteeMembers = "drng.committeeMembers"
)
func init() {
flag.Uint32(CFG_INSTANCE_ID, 1, "instance ID of the drng instance")
flag.Uint32(CFG_THRESHOLD, 3, "BLS threshold of the drng")
flag.String(CFG_DISTRIBUTED_PUB_KEY, "", "distributed public key of the committee (hex encoded)")
flag.StringSlice(CFG_COMMITTEE_MEMBERS, []string{}, "list of committee members of the drng")
flag.Uint32(CfgDRNGInstanceID, 1, "instance ID of the drng instance")
flag.Uint32(CfgDRNGThreshold, 3, "BLS threshold of the drng")
flag.String(CfgDRNGDistributedPubKey, "", "distributed public key of the committee (hex encoded)")
flag.StringSlice(CfgDRNGCommitteeMembers, []string{}, "list of committee members of the drng")
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment