Skip to content
Draft
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
91 changes: 44 additions & 47 deletions packages/chain/chainmanager/chain_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,13 @@ package chainmanager
import (
"errors"
"fmt"
"slices"

"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/samber/lo"

"github.com/iotaledger/hive.go/ds/shrinkingmap"
"github.com/iotaledger/hive.go/log"

"github.com/iotaledger/wasp/v2/clients/iota-go/iotago"
"github.com/iotaledger/wasp/v2/clients/iota-go/iotasigner"
"github.com/iotaledger/wasp/v2/packages/chain/committeelog"
Expand Down Expand Up @@ -186,7 +186,7 @@ type committeeLogInst struct {
committeeAddr cryptolib.Address
dkShare tcrypto.DKShare
gpaInstance gpa.GPA
pendingMsgs []gpa.Message
pendingMsgs []gpa.MessageOut
}

type ChainMgr struct {
Expand Down Expand Up @@ -272,7 +272,7 @@ func (cmi *ChainMgr) AsGPA() gpa.GPA {
}

// Input implements the gpa.GPA interface.
func (cmi *ChainMgr) Input(input gpa.Input) gpa.OutMessages {
func (cmi *ChainMgr) Input(input gpa.Input) []gpa.MessageOut {
switch input := input.(type) {
case *inputAnchorConfirmed:
return cmi.handleInputAnchorConfirmed(input)
Expand All @@ -291,12 +291,12 @@ func (cmi *ChainMgr) Input(input gpa.Input) gpa.OutMessages {
}

// Message implements the gpa.GPA interface.
func (cmi *ChainMgr) Message(msg gpa.Message) gpa.OutMessages {
switch msg := msg.(type) {
func (cmi *ChainMgr) Message(msg gpa.MessageIn) []gpa.MessageOut {
switch msg.Payload.(type) {
case *msgCommitteeLog:
return cmi.handleMsgCommitteeLog(msg)
return cmi.handleMsgCommitteeLog(gpa.AsTypedMessageIn[*msgCommitteeLog](msg))
case *msgBlockProduced:
return cmi.handleMsgBlockProduced(msg)
return cmi.handleMsgBlockProduced(gpa.AsTypedMessageIn[*msgBlockProduced](msg))
}
panic(fmt.Errorf("unexpected message %T: %+v", msg, msg))
}
Expand All @@ -310,13 +310,13 @@ func (cmi *ChainMgr) Message(msg gpa.Message) gpa.OutMessages {
// > Send Suspend to Last Active CommitteeLog; HandleCommitteeLogOutput(LatestActiveCmt)
// > Set LatestActiveCmt <- NIL
// > Set NeedConsensus <- NIL
func (cmi *ChainMgr) handleInputAnchorConfirmed(input *inputAnchorConfirmed) gpa.OutMessages {
func (cmi *ChainMgr) handleInputAnchorConfirmed(input *inputAnchorConfirmed) []gpa.MessageOut {
cmi.log.LogDebugf("handleInputAnchorConfirmed: %+v", input)
//
// > Set LatestConfirmedAnchor <- ConfirmedAnchor
vsaTip, vsaUpdated := cmi.varAccessNodeState.BlockConfirmed(input.anchor)
cmi.latestConfirmedAnchor = input.anchor
msgs := gpa.NoMessages()
var msgs []gpa.MessageOut
committeeLog, err := cmi.ensureCommitteeLog(*input.stateController) // TODO: input.stateController.Key()
if errors.Is(err, ErrNotInCommittee) {
// > IF this node is in the committee THEN ... ELSE
Expand All @@ -325,7 +325,7 @@ func (cmi *ChainMgr) handleInputAnchorConfirmed(input *inputAnchorConfirmed) gpa
// > Set LatestActiveCmt <- NIL
// > Set NeedConsensus <- NIL
if cmi.latestActiveCommittee != nil {
msgs.AddAll(cmi.suspendCommittee(cmi.latestActiveCommittee))
msgs = slices.Concat(msgs, cmi.suspendCommittee(cmi.latestActiveCommittee))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How do you feel about these inline msgs.AddAll(doSometing), slices.Concat(msgs, stateMgr.Input(...)) etc?
Would you agree, that this style is very common in this code and that it decreases readbility? How about changing it to something like this:

res := cmi.suspendCommittee(cmi.latestActiveCommittee)
outmsgs = slices.Concat(msgs, resOutMsgs)

Because I personally loose focus when reading code like: msgs.AddAll(stateMgr.Input(NewInputThingyDone(inputArg))) :D

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Personally I don't find it so distracting, but I'm also not against splitting those lines if it improves readability! Let's do it.

cmi.committeeUpdatedCB(nil)
cmi.latestActiveCommittee = nil
}
Expand All @@ -343,7 +343,7 @@ func (cmi *ChainMgr) handleInputAnchorConfirmed(input *inputAnchorConfirmed) gpa
}
// > IF this node is in the committee THEN
// > Pass it to the corresponding CommitteeLog; HandleCommitteeLogOutput.
msgs.AddAll(cmi.handleCommitteeLogOutput(
msgs = slices.Concat(msgs, cmi.handleCommitteeLogOutput(
committeeLog,
committeeLog.gpaInstance.Input(committeelog.NewInputAnchorConfirmed(input.anchor)),
))
Expand All @@ -356,7 +356,7 @@ func (cmi *ChainMgr) handleInputAnchorConfirmed(input *inputAnchorConfirmed) gpa
// > Forward it to ChainMgr; HandleCommitteeLogOutput.
// > ELSE
// > NOP // Anchor has to be received as Confirmed Anchor.
func (cmi *ChainMgr) handleInputChainTxPublishResult(input *inputChainTxPublishResult) gpa.OutMessages {
func (cmi *ChainMgr) handleInputChainTxPublishResult(input *inputChainTxPublishResult) []gpa.MessageOut {
cmi.log.LogDebugf("handleInputChainTxPublishResult: %+v", input)
// > Clear the TX from the NeedPublishTX variable.
if cmi.needPublishTX.Has(input.txDigest.HashValue()) {
Expand All @@ -366,13 +366,13 @@ func (cmi *ChainMgr) handleInputChainTxPublishResult(input *inputChainTxPublishR
if input.confirmed {
// > If result.confirmed = false THEN ... ELSE
// > NOP // Anchor has to be received as Confirmed Anchor. // TODO: Not true, anymore.
return cmi.withCommitteeLog(input.committeeAddr, func(cl gpa.GPA) gpa.OutMessages {
return cmi.withCommitteeLog(input.committeeAddr, func(cl gpa.GPA) []gpa.MessageOut {
return cl.Input(committeelog.NewInputConsensusOutputConfirmed(input.anchor, input.logIndex))
})
}
// > If result.confirmed = false THEN
// > Forward it to ChainMgr; HandleCommitteeLogOutput.
return cmi.withCommitteeLog(input.committeeAddr, func(cl gpa.GPA) gpa.OutMessages {
return cmi.withCommitteeLog(input.committeeAddr, func(cl gpa.GPA) []gpa.MessageOut {
return cl.Input(committeelog.NewInputConsensusOutputRejected(input.anchor, input.logIndex))
})
}
Expand All @@ -382,9 +382,9 @@ func (cmi *ChainMgr) handleInputChainTxPublishResult(input *inputChainTxPublishR
// > Add ConsensusOutput.TX to NeedPublishTX
// > Forward the message to the corresponding CommitteeLog; HandleCommitteeLogOutput.
// > Update AccessNodes.
func (cmi *ChainMgr) handleInputConsensusOutputDone(input *inputConsensusOutputDone) gpa.OutMessages {
func (cmi *ChainMgr) handleInputConsensusOutputDone(input *inputConsensusOutputDone) []gpa.MessageOut {
cmi.log.LogDebugf("handleInputConsensusOutputDone: %+v", input)
msgs := gpa.NoMessages()
var msgs []gpa.MessageOut

baseAnchorRef := input.consensusResult.Transaction.FindInputByID(cmi.chainID.AsObjectID())
if baseAnchorRef == nil {
Expand All @@ -407,7 +407,7 @@ func (cmi *ChainMgr) handleInputConsensusOutputDone(input *inputConsensusOutputD
if lo.Contains(activeCommitteeNodes, activeAccessNodes[i]) {
continue
}
msgs.Add(NewMsgBlockProduced(cmi.nodeIDFromPubKey(activeAccessNodes[i]), input.consensusResult.Transaction, block))
msgs = append(msgs, NewMsgBlockProduced(cmi.nodeIDFromPubKey(activeAccessNodes[i]), input.consensusResult.Transaction, block))
}
}
if !cmi.needPublishTX.Has(txDigest.HashValue()) {
Expand All @@ -424,54 +424,54 @@ func (cmi *ChainMgr) handleInputConsensusOutputDone(input *inputConsensusOutputD
// > Forward the message to the corresponding CommitteeLog; HandleCommitteeLogOutput.
//
// TODO: This event is not needed anymore.
// msgs.AddAll(cmi.withCommitteeLog(input.committeeAddr, func(cl gpa.GPA) gpa.OutMessages {
// msgs.AddAll(cmi.withCommitteeLog(input.committeeAddr, func(cl gpa.GPA) []gpa.MessageOut {
// return cl.Input(cmtlog.NewInputConsensusOutputDone(input.logIndex, input.proposedBaseAnchor, input.consensusResult))
// }))
return msgs
}

// > UPON Reception of Consensus Output/SKIP:
// > Forward the message to the corresponding CommitteeLog; HandleCommitteeLogOutput.
func (cmi *ChainMgr) handleInputConsensusOutputSkip(input *inputConsensusOutputSkip) gpa.OutMessages {
return cmi.withCommitteeLog(input.committeeAddr, func(cl gpa.GPA) gpa.OutMessages {
func (cmi *ChainMgr) handleInputConsensusOutputSkip(input *inputConsensusOutputSkip) []gpa.MessageOut {
return cmi.withCommitteeLog(input.committeeAddr, func(cl gpa.GPA) []gpa.MessageOut {
return cl.Input(committeelog.NewInputConsensusOutputSkip(input.logIndex))
})
}

// > UPON Reception of Consensus Timeout:
// > Forward the message to the corresponding CommitteeLog; HandleCommitteeLogOutput.
func (cmi *ChainMgr) handleInputConsensusTimeout(input *inputConsensusTimeout) gpa.OutMessages {
func (cmi *ChainMgr) handleInputConsensusTimeout(input *inputConsensusTimeout) []gpa.MessageOut {
cmi.log.LogDebugf("handleInputConsensusTimeout: %+v", input)
return cmi.withCommitteeLog(input.committeeAddr, func(cl gpa.GPA) gpa.OutMessages {
return cmi.withCommitteeLog(input.committeeAddr, func(cl gpa.GPA) []gpa.MessageOut {
return cl.Input(committeelog.NewInputConsensusTimeout(input.logIndex))
})
}

func (cmi *ChainMgr) handleInputCanPropose() gpa.OutMessages {
func (cmi *ChainMgr) handleInputCanPropose() []gpa.MessageOut {
cmi.log.LogDebugf("handleInputCanPropose")
return cmi.withAllCommitteeLogs(func(cl gpa.GPA) gpa.OutMessages {
return cmi.withAllCommitteeLogs(func(cl gpa.GPA) []gpa.MessageOut {
return cl.Input(committeelog.NewInputCanPropose())
})
}

// > UPON Reception of CommitteeLog.NextLI message:
// > Forward it to the corresponding CommitteeLog; HandleCommitteeLogOutput.
func (cmi *ChainMgr) handleMsgCommitteeLog(msg *msgCommitteeLog) gpa.OutMessages {
func (cmi *ChainMgr) handleMsgCommitteeLog(msg gpa.TypedMessageIn[*msgCommitteeLog]) []gpa.MessageOut {
cmi.log.LogDebugf("handleMsgCommitteeLog: %+v", msg)
return cmi.withCommitteeLog(msg.committeeAddr, func(cl gpa.GPA) gpa.OutMessages {
return cl.Message(msg.wrapped)
return cmi.withCommitteeLog(msg.Payload.committeeAddr, func(cl gpa.GPA) []gpa.MessageOut {
return cl.Message(gpa.NewMessageIn(msg.Sender, msg.Payload.wrapped))
})
}

func (cmi *ChainMgr) handleMsgBlockProduced(msg *msgBlockProduced) gpa.OutMessages {
func (cmi *ChainMgr) handleMsgBlockProduced(msg gpa.TypedMessageIn[*msgBlockProduced]) []gpa.MessageOut {
cmi.log.LogDebugf("handleMsgBlockProduced: %+v", msg)
vsaTip, vsaUpdated, l1Commitment := cmi.varAccessNodeState.BlockProduced(msg.tx)
vsaTip, vsaUpdated, l1Commitment := cmi.varAccessNodeState.BlockProduced(msg.Payload.tx)
//
// Save the block, if it matches all the signatures by the current committee.
// This will save us a round-trip to query the block from the sender.
if l1Commitment != nil {
if msg.block.L1Commitment().Equals(l1Commitment) {
cmi.savePreliminaryBlockCB(msg.block)
if msg.Payload.block.L1Commitment().Equals(l1Commitment) {
cmi.savePreliminaryBlockCB(msg.Payload.block)
} else {
cmi.log.LogWarnf("Received msgBlockProduced, but publishedAnchor.l1Commitment != block.l1Commitment.")
}
Expand All @@ -497,11 +497,10 @@ func (cmi *ChainMgr) handleMsgBlockProduced(msg *msgBlockProduced) gpa.OutMessag
// > Suspend(LatestActiveCmt)
// > Set LatestActiveCmt <- cmt
// > Set NeedConsensus <- output.NeedConsensus
func (cmi *ChainMgr) handleCommitteeLogOutput(cli *committeeLogInst, cliMsgs gpa.OutMessages) gpa.OutMessages {
func (cmi *ChainMgr) handleCommitteeLogOutput(cli *committeeLogInst, cliMsgs []gpa.MessageOut) []gpa.MessageOut {
//
// > Wrap out messages.
msgs := gpa.NoMessages()
msgs.AddAll(cmi.wrapCommitteeLogMsgs(cli, cliMsgs))
msgs := cmi.wrapCommitteeLogMsgs(cli, cliMsgs)
outputUntyped := cli.gpaInstance.Output()
// > IF cmt == LatestActiveCmt || LatestActiveCmt == NIL THEN
// > Set LatestActiveCmt <- cmt
Expand All @@ -523,7 +522,7 @@ func (cmi *ChainMgr) handleCommitteeLogOutput(cli *committeeLogInst, cliMsgs gpa
return msgs
}
if !cmi.latestActiveCommittee.Equals(&cli.committeeAddr) {
msgs.AddAll(cmi.suspendCommittee(cmi.latestActiveCommittee))
msgs = slices.Concat(msgs, cmi.suspendCommittee(cmi.latestActiveCommittee))
cmi.committeeUpdatedCB(cli.dkShare)
cmi.latestActiveCommittee = &cli.committeeAddr
}
Expand Down Expand Up @@ -605,15 +604,13 @@ func (cmi *ChainMgr) StatusString() string { // TODO: Call it periodically. Show
////////////////////////////////////////////////////////////////////////////////
// Helper functions.

func (cmi *ChainMgr) wrapCommitteeLogMsgs(cli *committeeLogInst, outMsgs gpa.OutMessages) gpa.OutMessages {
wrappedMsgs := gpa.NoMessages()
outMsgs.MustIterate(func(msg gpa.Message) {
wrappedMsgs.Add(NewMsgCommitteeLog(cli.committeeAddr, msg))
func (cmi *ChainMgr) wrapCommitteeLogMsgs(cli *committeeLogInst, outMsgs []gpa.MessageOut) []gpa.MessageOut {
return lo.Map(outMsgs, func(msg gpa.MessageOut, _ int) gpa.MessageOut {
return gpa.NewMessageOut(msg.Recipient, NewMsgCommitteeLog(cli.committeeAddr, msg.Payload))
})
return wrappedMsgs
}

func (cmi *ChainMgr) suspendCommittee(committeeAddr *cryptolib.Address) gpa.OutMessages {
func (cmi *ChainMgr) suspendCommittee(committeeAddr *cryptolib.Address) []gpa.MessageOut {
for _, cli := range cmi.committeeLogs {
if !cli.committeeAddr.Equals(committeeAddr) {
continue
Expand All @@ -623,19 +620,19 @@ func (cmi *ChainMgr) suspendCommittee(committeeAddr *cryptolib.Address) gpa.OutM
return nil
}

func (cmi *ChainMgr) withCommitteeLog(committeeAddr cryptolib.Address, handler func(cl gpa.GPA) gpa.OutMessages) gpa.OutMessages {
func (cmi *ChainMgr) withCommitteeLog(committeeAddr cryptolib.Address, handler func(cl gpa.GPA) []gpa.MessageOut) []gpa.MessageOut {
cli, err := cmi.ensureCommitteeLog(committeeAddr)
if err != nil {
cmi.log.LogWarnf("cannot find committee: %v", committeeAddr)
return nil
}
return gpa.NoMessages().AddAll(cmi.handleCommitteeLogOutput(cli, handler(cli.gpaInstance)))
return cmi.handleCommitteeLogOutput(cli, handler(cli.gpaInstance))
}

func (cmi *ChainMgr) withAllCommitteeLogs(handler func(cl gpa.GPA) gpa.OutMessages) gpa.OutMessages {
msgs := gpa.NoMessages()
func (cmi *ChainMgr) withAllCommitteeLogs(handler func(cl gpa.GPA) []gpa.MessageOut) []gpa.MessageOut {
var msgs []gpa.MessageOut
for _, cli := range cmi.committeeLogs {
msgs.AddAll(cmi.handleCommitteeLogOutput(cli, handler(cli.gpaInstance)))
msgs = slices.Concat(msgs, cmi.handleCommitteeLogOutput(cli, handler(cli.gpaInstance)))
}
return msgs
}
Expand Down Expand Up @@ -687,7 +684,7 @@ func (cmi *ChainMgr) ensureCommitteeLog(committeeAddr cryptolib.Address) (*commi
committeeAddr: committeeAddr,
dkShare: dkShare,
gpaInstance: clGPA,
pendingMsgs: []gpa.Message{},
pendingMsgs: []gpa.MessageOut{},
}
cmi.committeeLogs[committeeAddr.Key()] = cli
return cli, nil
Expand Down
8 changes: 4 additions & 4 deletions packages/chain/chainmanager/msg.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ const (
msgTypeBlockProduced
)

func (cmi *ChainMgr) UnmarshalMessage(data []byte) (gpa.Message, error) {
return gpa.UnmarshalMessage(data, gpa.Mapper{
msgTypeCommitteeLog: func() gpa.Message { return new(msgCommitteeLog) },
msgTypeBlockProduced: func() gpa.Message {
func (cmi *ChainMgr) UnmarshalPayload(data []byte) (gpa.MessagePayload, error) {
return gpa.UnmarshalPayload(data, gpa.PayloadAllocator{
msgTypeCommitteeLog: func() gpa.MessagePayload { return new(msgCommitteeLog) },
msgTypeBlockProduced: func() gpa.MessagePayload {
msgBlock := new(msgBlockProduced)

// TODO: Validate if we ever have different block implementations.
Expand Down
14 changes: 6 additions & 8 deletions packages/chain/chainmanager/msg_block_produced.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,17 @@ import (
// This message is used to inform access nodes on new blocks
// produced so that they can update their active state faster.
type msgBlockProduced struct {
gpa.BasicMessage
tx *iotasigner.SignedTransaction `bcs:"export"`
block state.Block `bcs:"export"`
}

var _ gpa.Message = new(msgBlockProduced)
var _ gpa.MessagePayload = new(msgBlockProduced)

func NewMsgBlockProduced(recipient gpa.NodeID, tx *iotasigner.SignedTransaction, block state.Block) gpa.Message {
return &msgBlockProduced{
BasicMessage: gpa.NewBasicMessage(recipient),
tx: tx,
block: block,
}
func NewMsgBlockProduced(recipient gpa.NodeID, tx *iotasigner.SignedTransaction, block state.Block) gpa.MessageOut {
return gpa.NewMessageOut(recipient, &msgBlockProduced{
tx: tx,
block: block,
})
}

func (msg *msgBlockProduced) MsgType() gpa.MessageType {
Expand Down
3 changes: 0 additions & 3 deletions packages/chain/chainmanager/msg_block_produced_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,13 @@ import (

bcs "github.com/iotaledger/bcs-go"
"github.com/iotaledger/wasp/v2/clients/iota-go/iotasigner/iotasignertest"
"github.com/iotaledger/wasp/v2/packages/gpa"
"github.com/iotaledger/wasp/v2/packages/state"
"github.com/iotaledger/wasp/v2/packages/state/statetest"
)

func TestMsgBlockProducedSerialization(t *testing.T) {
randomSignedTransaction := iotasignertest.RandomSignedTransaction()
msg := &msgBlockProduced{
gpa.BasicMessage{},
&randomSignedTransaction,
statetest.RandomBlock(),
}
Expand All @@ -23,7 +21,6 @@ func TestMsgBlockProducedSerialization(t *testing.T) {
})

msg = &msgBlockProduced{
gpa.BasicMessage{},
&iotasignertest.TestSignedTransaction,
statetest.TestBlock(),
}
Expand Down
18 changes: 5 additions & 13 deletions packages/chain/chainmanager/msg_cmt_log.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ import (
// is by CommitteeID, not by integer index.
type msgCommitteeLog struct {
committeeAddr cryptolib.Address
wrapped gpa.Message
wrapped gpa.MessagePayload
}

var _ gpa.Message = new(msgCommitteeLog)
var _ gpa.MessagePayload = new(msgCommitteeLog)

func NewMsgCommitteeLog(committeeAddr cryptolib.Address, wrapped gpa.Message) gpa.Message {
func NewMsgCommitteeLog(committeeAddr cryptolib.Address, wrapped gpa.MessagePayload) gpa.MessagePayload {
return &msgCommitteeLog{
committeeAddr: committeeAddr,
wrapped: wrapped,
Expand All @@ -33,16 +33,8 @@ func (msg *msgCommitteeLog) String() string {
return fmt.Sprintf("{chainMgr.msgCommitteeLog, committeeAddr=%v, wrapped=%+v}", msg.committeeAddr.String(), msg.wrapped)
}

func (msg *msgCommitteeLog) Recipient() gpa.NodeID {
return msg.wrapped.Recipient()
}

func (msg *msgCommitteeLog) SetSender(sender gpa.NodeID) {
msg.wrapped.SetSender(sender)
}

func (msg *msgCommitteeLog) MarshalBCS(e *bcs.Encoder) error {
wrappedBytes, err := gpa.MarshalMessage(msg.wrapped)
wrappedBytes, err := gpa.MarshalPayload(msg.wrapped)
if err != nil {
return fmt.Errorf("marshaling wrapped message: %w", err)
}
Expand All @@ -58,7 +50,7 @@ func (msg *msgCommitteeLog) UnmarshalBCS(d *bcs.Decoder) error {
wrappedBytes := bcs.Decode[[]byte](d)

var err error
msg.wrapped, err = committeelog.UnmarshalMessage(wrappedBytes)
msg.wrapped, err = committeelog.UnmarshalPayload(wrappedBytes)
if err != nil {
return fmt.Errorf("unmarshaling wrapped message: %w", err)
}
Expand Down
Loading
Loading