Skip to content

Commit

Permalink
Auto funding script (#1543)
Browse files Browse the repository at this point in the history
* Adding is_transfer to the other sql init.

* Added deployment script.

* Added new scripts.

* Fix for test.

* short fixes

* Removed useless multiplication.

* Reduced funding to 0.5

* Added receive function.

* Removed hardcoded addresses.

* Expanded log.

* Fixed bad merge.

* Increased gas limit.

* Fixed known issues and added gas test that ensures network hasnt produced bad batches.

* patched up sim tests.

* Moved to hardcoded addresses.

* Added a time sleep that seems to be good enough for the tests to pass.

* Lint fixes.

* Attempt to fix tests.

* Fixed line that was overriding the cfg.

* Changed gas price for test.'

* Fix for faucet test.

* reversed change.

---------

Co-authored-by: StefanIliev545 <[email protected]>
  • Loading branch information
StefanIliev545 and StefanIliev545 authored Sep 28, 2023
1 parent ef3cef2 commit 816bccf
Show file tree
Hide file tree
Showing 22 changed files with 159 additions and 11 deletions.
1 change: 1 addition & 0 deletions contracts/config/networks.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"layer1" : "localGeth"
},
"deploy": [
"deployment_scripts/funding/layer1",
"deployment_scripts/messenger/layer1",
"deployment_scripts/messenger/layer2",
"deployment_scripts/bridge/",
Expand Down
39 changes: 39 additions & 0 deletions contracts/deployment_scripts/funding/layer1/001_fund_accounts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import {HardhatRuntimeEnvironment} from 'hardhat/types';
import {DeployFunction} from 'hardhat-deploy/types';


const func: DeployFunction = async function (hre: HardhatRuntimeEnvironment) {
const layer1 = hre.companionNetworks.layer1;

const {deployer} = await hre.getNamedAccounts();
const l1Accs = await layer1.getNamedAccounts();

const messageBusAddress = process.env.MESSAGE_BUS_ADDRESS!!

const messageBus = (await hre.ethers.getContractFactory('MessageBus')).attach(messageBusAddress)
const prefundAmount = hre.ethers.utils.parseEther("0.5");
const tx = await messageBus.populateTransaction.sendValueToL2(deployer, prefundAmount, {
value: prefundAmount
});


console.log(`Sending ${prefundAmount} to ${deployer}`);

const receipt = await layer1.deployments.rawTx({
from: l1Accs.deployer,
to: messageBusAddress,
value: prefundAmount,
data: tx.data,
log: true,
waitConfirmations: 1,
});
if (receipt.events?.length === 0) {
console.log(`Account prefunding status = FAILURE NO CROSS CHAIN EVENT`);
} else {
console.log(`Account prefunding status = ${receipt.status}`);
}
};

export default func;
func.tags = ['GasPrefunding', 'GasPrefunding_deploy'];
// No dependencies
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const func: DeployFunction = async function (hre: HardhatRuntimeEnvironment) {
const { deployer } = await hre.companionNetworks.layer1.getNamedAccounts();

// Read the message bus address from the management contract deployment.
const messageBusAddress : string = process.env.MESSAGE_BUS_ADDRESS || "0xa1fdA5f6Df55a326f5f4300F3A716317f0f03110"
const messageBusAddress : string = process.env.MESSAGE_BUS_ADDRESS!!
console.log(`Message Bus address ${messageBusAddress}`);

// Setup the cross chain messenger and point it to the message bus from the management contract to be used for validation
Expand All @@ -27,4 +27,4 @@ const func: DeployFunction = async function (hre: HardhatRuntimeEnvironment) {

export default func;
func.tags = ['CrossChainMessenger', 'CrossChainMessenger_deploy'];
func.dependencies = ['ManagementContract', 'HPERC20']; //TODO: Remove HPERC20, this is only to have matching addresses.
func.dependencies = ['ManagementContract', 'HPERC20', 'GasPrefunding']; //TODO: Remove HPERC20, this is only to have matching addresses.
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,14 @@ const func: DeployFunction = async function (hre: HardhatRuntimeEnvironment) {
await new Promise(async (resolve, fail)=> {
setTimeout(fail, 30_000)
const messageBusContract = (await hre.ethers.getContractAt('MessageBus', '0x526c84529b2b8c11f57d93d3f5537aca3aecef9b'));
const gasLimit = await messageBusContract.estimateGas.verifyMessageFinalized(messages[1], {
maxFeePerGas: 2,
})
try {
while (await messageBusContract.callStatic.verifyMessageFinalized(messages[1], {
maxFeePerGas: 2,
gasLimit: gasLimit.mul(2),
from: l2Accounts.deployer
}) != true) {
console.log(`Messages not stored on L2 yet, retrying...`);
await sleep(1_000);
Expand All @@ -108,8 +113,6 @@ const func: DeployFunction = async function (hre: HardhatRuntimeEnvironment) {
fail(err)
}



resolve(true);
});

Expand Down

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion contracts/generated/MessageBus/MessageBus.go

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion contracts/src/messaging/MessageBus.sol
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,6 @@ contract MessageBus is IMessageBus, Ownable {
}

receive() external payable {
revert("the Wormhole contract does not accept assets");
this.sendValueToL2{value: msg.value}(msg.sender, msg.value);
}
}
2 changes: 1 addition & 1 deletion go/enclave/components/batch_executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ func (executor *batchExecutor) payL1Fees(stateDB *state.StateDB, context *BatchE
continue
}
if accBalance.Cmp(cost) == -1 {
executor.logger.Info("insufficient account balance for tx", log.TxKey, tx.Hash(), "addr", sender.Hex())
executor.logger.Info(fmt.Sprintf("insufficient account balance for tx - want: %d have: %d", cost, accBalance), log.TxKey, tx.Hash(), "addr", sender.Hex())
continue
}
stateDB.SubBalance(*sender, cost)
Expand Down
2 changes: 1 addition & 1 deletion go/enclave/enclave_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ const _testEnclavePublicKeyHex = "034d3b7e63a8bcd532ee3d1d6ecad9d67fca7821981a04
// _successfulRollupGasPrice can be deterministically calculated when evaluating the management smart contract.
// It should change only when there are changes to the smart contract or if the gas estimation algorithm is modified.
// Other changes would mean something is broken.
const _successfulRollupGasPrice = 371816
const _successfulRollupGasPrice = 372008

var _enclavePubKey *ecies.PublicKey

Expand Down
2 changes: 1 addition & 1 deletion go/enclave/storage/init/edgelessdb/001_init.sql
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ create table if not exists obsdb.l1_msg
id INTEGER AUTO_INCREMENT,
message varbinary(1024) NOT NULL,
block binary(16) NOT NULL,
is_transfer boolean NOT NULL,
is_transfer boolean NOT NULL,
INDEX (block),
primary key (id)
);
Expand Down
9 changes: 9 additions & 0 deletions go/node/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,15 @@ type Config struct {
batchInterval string
rollupInterval string
l1ChainID int
obscuroGenesis string
}

func NewNodeConfig(opts ...Option) *Config {
defaultConfig := &Config{
batchInterval: "1s",
rollupInterval: "3s",
l1ChainID: 1337,
obscuroGenesis: "{}",
}

for _, opt := range opts {
Expand All @@ -84,6 +86,7 @@ func (c *Config) ToEnclaveConfig() *config.EnclaveConfig {
cfg.LogLevel = c.logLevel
cfg.Address = fmt.Sprintf("%s:%d", _localhost, c.enclaveWSPort)
cfg.DebugNamespaceEnabled = c.debugNamespaceEnabled
cfg.ObscuroGenesis = c.obscuroGenesis

if c.nodeType == "sequencer" && c.coinbaseAddress != "" {
cfg.GasPaymentAddress = gethcommon.HexToAddress(c.coinbaseAddress)
Expand Down Expand Up @@ -323,3 +326,9 @@ func WithL1ChainID(i int) Option {
c.l1ChainID = i
}
}

func WithObscuroGenesis(g string) Option {
return func(c *Config) {
c.obscuroGenesis = g
}
}
1 change: 1 addition & 0 deletions go/node/docker_node.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ func (d *DockerNode) startEnclave() error {
"-maxBatchSize=25600",
"-maxRollupSize=65536",
fmt.Sprintf("-logLevel=%d", d.cfg.logLevel),
"-obscuroGenesis", "{}",
)

if d.cfg.sgxEnabled {
Expand Down
5 changes: 5 additions & 0 deletions go/wallet/wallet.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ type Wallet interface {
Address() common.Address
// SignTransaction returns a signed transaction
SignTransaction(tx types.TxData) (*types.Transaction, error)
SignTransactionForChainID(tx types.TxData, chainID *big.Int) (*types.Transaction, error)

// SetNonce overrides the current nonce
// The GetTransactionCount is expected to be the next nonce to use in a transaction, not the current account GetTransactionCount
Expand Down Expand Up @@ -71,6 +72,10 @@ func (m *inMemoryWallet) SignTransaction(tx types.TxData) (*types.Transaction, e
return types.SignNewTx(m.prvKey, types.NewLondonSigner(m.chainID), tx)
}

func (m *inMemoryWallet) SignTransactionForChainID(tx types.TxData, chainID *big.Int) (*types.Transaction, error) {
return types.SignNewTx(m.prvKey, types.NewLondonSigner(chainID), tx)
}

// Address returns the current wallet address
func (m *inMemoryWallet) Address() common.Address {
return m.pubKeyAddr
Expand Down
1 change: 1 addition & 0 deletions integration/contractdeployer/contract_deployer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ func createObscuroNetwork(t *testing.T, startPort int) {
ERC20ContractLib: ethereummock.NewERC20ContractLibMock(),
Wallets: wallets,
StartPort: startPort,
WithPrefunding: true,
}
simStats := stats.NewStats(simParams.NumberOfNodes)
obscuroNetwork := network.NewNetworkOfSocketNodes(wallets)
Expand Down
2 changes: 1 addition & 1 deletion integration/eth2network/eth2_configs.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ func generateGenesis(blockTimeSecs int, chainID int, signerAddrs, prefundedAddrs

// add the prefunded prefundedAddrs
for _, account := range prefundedAddrs {
genesisJSON["alloc"].(map[string]interface{})[account] = map[string]string{"balance": "10000000000000000000000"}
genesisJSON["alloc"].(map[string]interface{})[account] = map[string]string{"balance": "7500000000000000000000000000000"}
}

// set the block prod speed
Expand Down
1 change: 1 addition & 0 deletions integration/faucet/faucet_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ func createObscuroNetwork(t *testing.T, startPort int) {
ERC20ContractLib: ethereummock.NewERC20ContractLibMock(),
Wallets: wallets,
StartPort: startPort,
WithPrefunding: true,
}

obscuroNetwork := network.NewNetworkOfSocketNodes(wallets)
Expand Down
4 changes: 4 additions & 0 deletions integration/networktest/userwallet/userwallet.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,10 @@ func (s *UserWallet) SignTransaction(tx types.TxData) (*types.Transaction, error
return types.SignNewTx(s.privateKey, types.NewLondonSigner(s.chainID), tx)
}

func (s *UserWallet) SignTransactionForChainID(tx types.TxData, chainID *big.Int) (*types.Transaction, error) {
return types.SignNewTx(s.privateKey, types.NewLondonSigner(chainID), tx)
}

func (s *UserWallet) GetNonce() uint64 {
return s.nonce
}
Expand Down
6 changes: 6 additions & 0 deletions integration/simulation/network/socket.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@ func (n *networkOfSocketNodes) Create(simParams *params.SimParams, _ *stats.Stat
isInboundP2PDisabled = i == simParams.NodeWithInboundP2PDisabled
}

genesis := "{}"
if simParams.WithPrefunding {
genesis = ""
}

// create the nodes
nodes[i] = noderunner.NewInMemNode(
node.NewNodeConfig(
Expand All @@ -100,6 +105,7 @@ func (n *networkOfSocketNodes) Create(simParams *params.SimParams, _ *stats.Stat
node.WithLogLevel(4),
node.WithDebugNamespaceEnabled(true),
node.WithL1BlockTime(simParams.AvgBlockDuration),
node.WithObscuroGenesis(genesis),
),
)

Expand Down
1 change: 1 addition & 0 deletions integration/simulation/params/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ type SimParams struct {

StoppingDelay time.Duration // How long to wait between injection and verification
NodeWithInboundP2PDisabled int
WithPrefunding bool
}

type L1SetupData struct {
Expand Down
16 changes: 16 additions & 0 deletions integration/simulation/params/wallet_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@ type SimToken struct {
L2ContractAddress *common.Address
}

type L1PrefundWallets struct {
HOC wallet.Wallet
POC wallet.Wallet
Faucet wallet.Wallet
}

type SimWallets struct {
MCOwnerWallet wallet.Wallet // owner of the management contract deployed on Ethereum
NodeWallets []wallet.Wallet // the keys used by the obscuro nodes to submit rollups to Eth
Expand All @@ -41,6 +47,8 @@ type SimWallets struct {
L2FaucetWallet wallet.Wallet // the wallet of the L2 faucet
L2FeesWallet wallet.Wallet
Tokens map[testcommon.ERC20]*SimToken // The supported tokens

PrefundedEthWallets L1PrefundWallets
}

func NewSimWallets(nrSimWallets int, nNodes int, ethereumChainID int64, obscuroChainID int64) *SimWallets {
Expand Down Expand Up @@ -100,6 +108,11 @@ func NewSimWallets(nrSimWallets int, nNodes int, ethereumChainID int64, obscuroC
testcommon.HOC: &hoc,
testcommon.POC: &poc,
},
PrefundedEthWallets: L1PrefundWallets{
HOC: datagenerator.RandomWallet(ethereumChainID),
POC: datagenerator.RandomWallet(ethereumChainID),
Faucet: datagenerator.RandomWallet(ethereumChainID),
},
}
}

Expand All @@ -109,6 +122,9 @@ func (w *SimWallets) AllEthWallets() []wallet.Wallet {
ethWallets = append(ethWallets, token.L1Owner)
}
ethWallets = append(ethWallets, w.GasBridgeWallet)
ethWallets = append(ethWallets, w.PrefundedEthWallets.POC)
ethWallets = append(ethWallets, w.PrefundedEthWallets.HOC)
ethWallets = append(ethWallets, w.PrefundedEthWallets.Faucet)
return append(append(append(w.NodeWallets, w.SimEthWallets...), w.MCOwnerWallet), ethWallets...)
}

Expand Down
60 changes: 60 additions & 0 deletions integration/simulation/simulation.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@ import (
"time"

"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/eth/filters"
"github.com/obscuronet/go-obscuro/contracts/generated/MessageBus"
"github.com/obscuronet/go-obscuro/go/common"
"github.com/obscuronet/go-obscuro/go/common/errutil"
"github.com/obscuronet/go-obscuro/go/common/log"
Expand Down Expand Up @@ -56,6 +58,7 @@ func (s *Simulation) Start() {
// Arbitrary sleep to wait for RPC clients to get up and running
time.Sleep(1 * time.Second)

s.bridgeFundingToObscuro()
s.trackLogs() // Create log subscriptions, to validate that they're working correctly later.
s.prefundObscuroAccounts() // Prefund every L2 wallet
s.deployObscuroERC20s() // Deploy the Obscuro HOC and POC ERC20 contracts
Expand Down Expand Up @@ -116,6 +119,63 @@ func (s *Simulation) waitForObscuroGenesisOnL1() {
}
}

func (s *Simulation) bridgeFundingToObscuro() {
if s.Params.IsInMem {
return
}

destAddr := s.Params.L1SetupData.MessageBusAddr
value, _ := big.NewInt(0).SetString("7400000000000000000000000000000", 10)

wallets := []wallet.Wallet{
s.Params.Wallets.PrefundedEthWallets.Faucet,
s.Params.Wallets.PrefundedEthWallets.HOC,
s.Params.Wallets.PrefundedEthWallets.POC,
}

receivers := []gethcommon.Address{
gethcommon.HexToAddress("0xA58C60cc047592DE97BF1E8d2f225Fc5D959De77"),
gethcommon.HexToAddress("0x987E0a0692475bCc5F13D97E700bb43c1913EFfe"),
gethcommon.HexToAddress("0xDEe530E22045939e6f6a0A593F829e35A140D3F1"),
}

ethClient := s.RPCHandles.RndEthClient()

busCtr, err := MessageBus.NewMessageBus(destAddr, ethClient.EthClient())
if err != nil {
panic(err)
}

for idx, wallet := range wallets {
opts, err := bind.NewKeyedTransactorWithChainID(wallet.PrivateKey(), wallet.ChainID())
if err != nil {
panic(err)
}
opts.Value = value

_, err = busCtr.SendValueToL2(opts, receivers[idx], value)
if err != nil {
panic(err)
}
}

time.Sleep(3 * time.Second)
// todo - fix the wait group, for whatever reason it does not find a receipt...
/*wg := sync.WaitGroup{}
for _, tx := range transactions {
wg.Add(1)
transaction := tx
go func() {
defer wg.Done()
err := testcommon.AwaitReceiptEth(s.ctx, s.RPCHandles.RndEthClient(), transaction.Hash(), 20*time.Second)
if err != nil {
panic(err)
}
}()
}
wg.Wait()*/
}

// We subscribe to logs on every client for every wallet.
func (s *Simulation) trackLogs() {
// In-memory clients cannot handle subscriptions for now.
Expand Down
1 change: 1 addition & 0 deletions testnet/launcher/l2contractdeployer/docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ func (n *ContractDeployer) Start() error {
"saveDeployments" : true,
"companionNetworks" : { "layer1" : "layer1" },
"deploy": [
"deployment_scripts/funding/layer1",
"deployment_scripts/messenger/layer1",
"deployment_scripts/messenger/layer2",
"deployment_scripts/bridge/",
Expand Down

0 comments on commit 816bccf

Please sign in to comment.