Skip to content

sc: transfer bridge data to NillRollup #905

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 3 commits into
base: feature/nilrollup-deposit-count-enhancement
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
31 changes: 20 additions & 11 deletions nil/services/synccommittee/Makefile.inc
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ root_contracts = rollup-bridge-contracts/contracts

.PHONY: sync_committee_targets
sync_committee_targets: \
sync_committee_contract_abi \
sync_committee_types_stringer \
sync_committee_generate_mocks \
sync_committee_protobuf \
sync_committee_tracer_constants \
$(root_sc)/generate_fee_updater_abi
$(root_sc)/generate_rollup_contract_abi \
$(root_sc)/generate_fee_updater_abi \
$(root_sc)/compile_l2_bridge_state_getter_abi

.PHONY: $(root_sc)/compile_fee_updater_abi
$(root_sc)/compile_fee_updater_abi:
Expand All @@ -18,13 +19,21 @@ $(root_sc)/compile_fee_updater_abi:
$(root_sc)/generate_fee_updater_abi: $(root_sc)/compile_fee_updater_abi
cd $(root_sc)/core/feeupdater && go run github.com/ethereum/go-ethereum/cmd/abigen --abi IFeeStorage.abi --pkg=feeupdater --out=./i_fee_storage_contract_abi_generated.go

.PHONY: sync_committee_contract_abi
sync_committee_contract_abi: \
$(root_sc)/core/rollupcontract/rollupcontract_abi_generated.go
.PHONY: $(root_sc)/compile_rollup_contract_abi
$(root_sc)/compile_rollup_contract_abi:
solc $(root_contracts)/interfaces/INilRollup.sol --abi --overwrite -o $(root_sc)/core/rollupcontract --allow-paths .,$(root_contracts)/common/libraries --no-cbor-metadata --metadata-hash none --pretty-json

.PHONY: $(root_sc)/generate_rollup_contract_abi
$(root_sc)/generate_rollup_contract_abi: $(root_sc)/compile_rollup_contract_abi
cd $(root_sc)/core/rollupcontract && go run github.com/ethereum/go-ethereum/cmd/abigen --abi INilRollup.abi --pkg=rollupcontract --out=./i_rollup_contract_abi_generated.go

$(root_sc)/core/rollupcontract/rollupcontract_abi_generated.go: \
$(root_sc)/core/rollupcontract/abi.json
go generate $(root_sc)/core/rollupcontract/generate.go
.PHONY: $(root_sc)/compile_l2_bridge_state_getter_abi
$(root_sc)/compile_l2_bridge_state_getter_abi:
solc $(root_contracts)/bridge/l2/interfaces/IL2BridgeStateGetter.sol --abi --overwrite -o $(root_sc)/core/bridgecontract --allow-paths .,$(root_contracts)/common/libraries --no-cbor-metadata --metadata-hash none --pretty-json

$(root_sc)/core/rollupcontract/wrapper_generated_mock.go: \
$(root_sc)/generate_rollup_contract_abi
cd $(root_sc)/core/rollupcontract && ../../internal/scripts/generate_mock.sh Wrapper

$(root_sc)/internal/l1client/eth_client_generated_mock.go:
cd $(root_sc)/internal/l1client && bash ../../internal/scripts/generate_mock.sh EthClient
Expand Down Expand Up @@ -84,7 +93,7 @@ $(root_sc)/internal/api/task_state_change_handler_generated_mock.go: \
go generate $(root_sc)/internal/api/task_state_change_handler.go

$(root_sc)/core/state_reset_launcher_generated_mock.go: \
sync_committee_contract_abi \
$(root_sc)/generate_rollup_contract_abi \
$(root_sc)/core/task_state_change_handler.go
go generate $(root_sc)/core/task_state_change_handler.go

Expand All @@ -107,9 +116,9 @@ $(root_sc)/prover/tracer/storage_getter_setter_generated_mock.go: \
go generate $(root_sc)/prover/tracer

$(root_sc)/core/rollupcontract/wrapper_generated_mock.go: \
sync_committee_contract_abi \
$(root_sc)/generate_rollup_contract_abi \
$(root_sc)/core/rollupcontract/wrapper.go
go generate $(root_sc)/core/rollupcontract/generate.go
cd $(root_sc)/core/rollupcontract && bash ../../internal/scripts/generate_mock.sh Wrapper

$(root_sc)/core/feeupdater/contract_wrapper_generated_mock.go: \
$(root_sc)/core/feeupdater/contract_wrapper.go \
Expand Down
132 changes: 132 additions & 0 deletions nil/services/synccommittee/core/bridgecontract/bridge_state_getter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
package bridgecontract

import (
"context"
"fmt"
"math/big"

"github.com/NilFoundation/nil/nil/client"
"github.com/NilFoundation/nil/nil/common/hexutil"
"github.com/NilFoundation/nil/nil/internal/abi"
"github.com/NilFoundation/nil/nil/internal/types"
"github.com/NilFoundation/nil/nil/services/rpc/jsonrpc"
"golang.org/x/sync/errgroup"
)

type bytes32 = [32]uint8

type BridgeState struct {
L2toL1Root *big.Int
DepositNonce *big.Int
L1MessageHash *big.Int
}

type BridgeStateGetter interface {
GetBridgeState(ctx context.Context, blockID any) (*BridgeState, error)
}

type bridgeStateGetter struct {
nilClient client.Client
contractAddr types.Address
abi *abi.ABI
}

func NewBridgeStateGetter(
nilClient client.Client,
l2ContractAddr types.Address,
) *bridgeStateGetter {
return &bridgeStateGetter{
nilClient: nilClient,
contractAddr: l2ContractAddr,
abi: GetL2BridgeStateGetterABI(),
}
}

func (b *bridgeStateGetter) GetBridgeState(ctx context.Context, blockID any) (*BridgeState, error) {
eg, gCtx := errgroup.WithContext(ctx)

var l1MessageHash *big.Int
eg.Go(func() error {
ret, err := callContract[bytes32](gCtx, b.nilClient, blockID, b.contractAddr, b.abi, "l1MessageHash")
if err != nil {
return err
}
l1MessageHash = new(big.Int).SetBytes(ret[:])
return nil
})

var l2ToL1Root *big.Int
eg.Go(func() error {
ret, err := callContract[bytes32](gCtx, b.nilClient, blockID, b.contractAddr, b.abi, "getL2ToL1Root")
if err != nil {
return err
}
l2ToL1Root = new(big.Int).SetBytes(ret[:])
return nil
})

var depositNonce *big.Int
eg.Go(func() error {
ret, err := callContract[*big.Int](gCtx, b.nilClient, blockID, b.contractAddr, b.abi, "getLatestDepositNonce")
if err != nil {
return err
}
depositNonce = ret
return nil
})

if err := eg.Wait(); err != nil {
return nil, err
}

ret := &BridgeState{
L2toL1Root: l2ToL1Root,
DepositNonce: depositNonce,
L1MessageHash: l1MessageHash,
}
return ret, nil
}

func callContract[Ret any](
ctx context.Context,
c client.Client,
blockID any,
addr types.Address,
abi *abi.ABI,
method string,
args ...any,
) (Ret, error) {
var ret Ret
calldata, err := abi.Pack(method, args...)
if err != nil {
return ret, err
}

callArgs := &jsonrpc.CallArgs{
Data: (*hexutil.Bytes)(&calldata),
To: addr,
Fee: types.NewFeePackFromGas(100_000), // TODO(oclaw) which value to use here?
}

callRes, err := c.Call(ctx, callArgs, blockID, nil)
if err != nil {
return ret, err
}

res, err := abi.Unpack(method, callRes.Data)
if err != nil {
return ret, err
}

if len(res) != 1 {
return ret, fmt.Errorf("expected single return value, got %d", len(res))
}

var ok bool
ret, ok = res[0].(Ret)
if !ok {
return ret, fmt.Errorf("type mismatch for return value of method %s: expected %T got %T", method, ret, res[0])
}

return ret, nil
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package bridgecontract

import (
"bytes"
_ "embed"

"github.com/NilFoundation/nil/nil/common/check"
"github.com/NilFoundation/nil/nil/internal/abi"
)

//go:embed IL2BridgeStateGetter.abi
var l2BridgeStateGetterContractABIData []byte

var l2BridgeStateGetterContractABI *abi.ABI

func init() {
abi, err := abi.JSON(bytes.NewReader(l2BridgeStateGetterContractABIData))
check.PanicIfErr(err)
if err != nil {
panic(err)
}
l2BridgeStateGetterContractABI = &abi
}

func GetL2BridgeStateGetterABI() *abi.ABI {
return l2BridgeStateGetterContractABI
}
1 change: 1 addition & 0 deletions nil/services/synccommittee/core/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ type Config struct {
ContractWrapperConfig rollupcontract.WrapperConfig `yaml:",inline"`
L1FeeUpdateConfig feeupdater.Config `yaml:",inline"`
L1FeeUpdateContractConfig feeupdater.ContractWrapperConfig `yaml:",inline"`
L2BridgeMessegerAdddress string `yaml:"l2BridgeMessegerAdddress"`
Telemetry *telemetry.Config `yaml:",inline"`
}

Expand Down
22 changes: 18 additions & 4 deletions nil/services/synccommittee/core/proposer.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/NilFoundation/nil/nil/common"
"github.com/NilFoundation/nil/nil/common/concurrent"
"github.com/NilFoundation/nil/nil/common/logging"
"github.com/NilFoundation/nil/nil/services/synccommittee/core/bridgecontract"
"github.com/NilFoundation/nil/nil/services/synccommittee/core/reset"
"github.com/NilFoundation/nil/nil/services/synccommittee/core/rollupcontract"
"github.com/NilFoundation/nil/nil/services/synccommittee/internal/log"
Expand All @@ -35,6 +36,7 @@ type proposer struct {

storage ProposerStorage
resetter *reset.StateResetLauncher
bridgeStateGetter bridgecontract.BridgeStateGetter
rollupContractWrapper rollupcontract.Wrapper
metrics ProposerMetrics
logger logging.Logger
Expand All @@ -56,13 +58,15 @@ func NewDefaultProposerConfig() ProposerConfig {
func NewProposer(
config ProposerConfig,
storage ProposerStorage,
bridgeStateGetter bridgecontract.BridgeStateGetter,
contractWrapper rollupcontract.Wrapper,
resetter *reset.StateResetLauncher,
metrics ProposerMetrics,
logger logging.Logger,
) (*proposer, error) {
p := &proposer{
storage: storage,
bridgeStateGetter: bridgeStateGetter,
rollupContractWrapper: contractWrapper,
resetter: resetter,
metrics: metrics,
Expand Down Expand Up @@ -110,14 +114,24 @@ func (p *proposer) updateState(
ctx context.Context,
proposalData *scTypes.ProposalData,
) error {
// TODO: populate with actual data
// NOTE(oclaw) current impl assumes that L2BridgeMessenger is deployed at the main shard
// if it is not - we need to expilicitly set shard id and use latest block ref from it
lastestMainBlockRef := proposalData.NewProvedStateRoot
if lastestMainBlockRef == common.EmptyHash {
return errors.New("latest main block ref is empty")
}

bridgeData, err := p.bridgeStateGetter.GetBridgeState(ctx, lastestMainBlockRef)
if err != nil {
return fmt.Errorf("failed to get bridge state: %w", err)
}

updateStateData := scTypes.NewUpdateStateData(
proposalData,
[]byte{0x0A, 0x0B, 0x0C},
common.EmptyHash,
0,
common.EmptyHash,
common.BigToHash(bridgeData.L2toL1Root),
common.BigToHash(bridgeData.L1MessageHash),
bridgeData.DepositNonce,
)

log.NewStateUpdateEvent(p.logger, zerolog.InfoLevel, updateStateData).Msg("calling UpdateState L1 method")
Expand Down
18 changes: 18 additions & 0 deletions nil/services/synccommittee/core/proposer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/NilFoundation/nil/nil/internal/db"
"github.com/NilFoundation/nil/nil/internal/types"
"github.com/NilFoundation/nil/nil/services/rpc/jsonrpc"
"github.com/NilFoundation/nil/nil/services/synccommittee/core/bridgecontract"
"github.com/NilFoundation/nil/nil/services/synccommittee/core/fetching"
"github.com/NilFoundation/nil/nil/services/synccommittee/core/reset"
"github.com/NilFoundation/nil/nil/services/synccommittee/core/rollupcontract"
Expand Down Expand Up @@ -111,6 +112,8 @@ func (s *ProposerTestSuite) SetupSuite() {
)
s.Require().NoError(err)

l2BridgeMessengerContractAddr := types.HexToAddress("0x1234")

s.rpcClientMock = &client.ClientMock{
GetBlockFunc: func(_ context.Context, shardId types.ShardId, blockId any, _ bool) (*jsonrpc.RPCBlock, error) {
strId, ok := blockId.(string)
Expand All @@ -126,15 +129,30 @@ func (s *ProposerTestSuite) SetupSuite() {
block.Hash = blockHash
return block, nil
},
CallFunc: func(
ctx context.Context, args *jsonrpc.CallArgs, blockId any, stateOverride *jsonrpc.StateOverrides,
) (*jsonrpc.CallRes, error) {
switch {
case args.To.Equal(l2BridgeMessengerContractAddr):
ret := types.NewUint256(123).Bytes32()
return &jsonrpc.CallRes{
Data: ret[:],
}, nil
default:
return nil, fmt.Errorf("unexpected contract address: %s", args.To)
}
},
}

fetcher := fetching.NewFetcher(s.rpcClientMock, logger)
l1Syncer := syncer.NewStateRootSyncer(fetcher, contractWrapper, s.storage, logger, syncer.NewDefaultConfig())
resetLauncher := reset.NewResetLauncher(s.storage, l1Syncer, nil, logger)
bridgeStateGetter := bridgecontract.NewBridgeStateGetter(s.rpcClientMock, l2BridgeMessengerContractAddr)

s.proposer, err = NewProposer(
s.params,
s.storage,
bridgeStateGetter,
contractWrapper,
resetLauncher,
metricsHandler,
Expand Down
Loading