Skip to content
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

Auto funding script #1543

Merged
merged 28 commits into from
Sep 28, 2023
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
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
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 @@ -127,6 +127,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);
}
}
46 changes: 39 additions & 7 deletions 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 All @@ -107,6 +107,27 @@ func (executor *batchExecutor) payL1Fees(stateDB *state.StateDB, context *BatchE
return transactions, freeTransactions
}

func (executor *batchExecutor) refundL1Fees(stateDB *state.StateDB, context *BatchExecutionContext, transactions []*common.L2Tx) {
block, _ := executor.storage.FetchBlock(context.BlockPtr)
for _, tx := range transactions {
cost, err := executor.gasOracle.EstimateL1StorageGasCost(tx, block)
if err != nil {
executor.logger.Warn("Unable to get gas cost for tx", log.TxKey, tx.Hash(), log.ErrKey, err)
continue
}

sender, err := core.GetAuthenticatedSender(context.ChainConfig.ChainID.Int64(), tx)
if err != nil {
// todo @siliev - is this critical? Potential desync spot
executor.logger.Warn("Unable to extract sender for tx", log.TxKey, tx.Hash())
continue
}

stateDB.AddBalance(*sender, cost)
stateDB.SubBalance(context.Creator, cost)
}
}

func (executor *batchExecutor) ComputeBatch(context *BatchExecutionContext) (*ComputedBatch, error) {
defer executor.logger.Info("Batch context processed", log.DurationKey, measure.NewStopwatch())

Expand Down Expand Up @@ -159,12 +180,14 @@ func (executor *batchExecutor) ComputeBatch(context *BatchExecutionContext) (*Co

crossChainTransactions = append(crossChainTransactions, freeTransactions...)

successfulTxs, txReceipts, err := executor.processTransactions(batch, 0, transactionsToProcess, stateDB, context.ChainConfig, false)
successfulTxs, excludedTxs, txReceipts, err := executor.processTransactions(batch, 0, transactionsToProcess, stateDB, context.ChainConfig, false)
if err != nil {
return nil, fmt.Errorf("could not process transactions. Cause: %w", err)
}

ccSuccessfulTxs, ccReceipts, err := executor.processTransactions(batch, len(successfulTxs), crossChainTransactions, stateDB, context.ChainConfig, true)
executor.refundL1Fees(stateDB, context, excludedTxs)

ccSuccessfulTxs, _, ccReceipts, err := executor.processTransactions(batch, len(successfulTxs), crossChainTransactions, stateDB, context.ChainConfig, true)
if err != nil {
return nil, err
}
Expand All @@ -176,7 +199,7 @@ func (executor *batchExecutor) ComputeBatch(context *BatchExecutionContext) (*Co
// we need to copy the batch to reset the internal hash cache
copyBatch := *batch
copyBatch.Header.Root = stateDB.IntermediateRoot(false)
copyBatch.Transactions = append(transactionsToProcess, freeTransactions...)
copyBatch.Transactions = append(successfulTxs, freeTransactions...)
copyBatch.ResetHash()

if err = executor.populateOutboundCrossChainData(&copyBatch, block, txReceipts); err != nil {
Expand Down Expand Up @@ -362,28 +385,37 @@ func (executor *batchExecutor) verifyInboundCrossChainTransactions(transactions
return nil
}

func (executor *batchExecutor) processTransactions(batch *core.Batch, tCount int, txs []*common.L2Tx, stateDB *state.StateDB, cc *params.ChainConfig, noBaseFee bool) ([]*common.L2Tx, []*types.Receipt, error) {
func (executor *batchExecutor) processTransactions(
batch *core.Batch,
tCount int,
txs []*common.L2Tx,
stateDB *state.StateDB,
cc *params.ChainConfig,
noBaseFee bool,
) ([]*common.L2Tx, []*common.L2Tx, []*types.Receipt, error) {
var executedTransactions []*common.L2Tx
var excludedTransactions []*common.L2Tx
var txReceipts []*types.Receipt

txResults := evm.ExecuteTransactions(txs, stateDB, batch.Header, executor.storage, cc, tCount, noBaseFee, executor.logger)
for _, tx := range txs {
result, f := txResults[tx.Hash()]
if !f {
return nil, nil, fmt.Errorf("there should be an entry for each transaction")
return nil, nil, nil, fmt.Errorf("there should be an entry for each transaction")
}
rec, foundReceipt := result.(*types.Receipt)
if foundReceipt {
executedTransactions = append(executedTransactions, tx)
txReceipts = append(txReceipts, rec)
} else {
// Exclude all errors
excludedTransactions = append(excludedTransactions, tx)
executor.logger.Info("Excluding transaction from batch", log.TxKey, tx.Hash(), log.BatchHashKey, batch.Hash(), "cause", result)
}
}
sort.Sort(sortByTxIndex(txReceipts))

return executedTransactions, txReceipts, nil
return executedTransactions, excludedTransactions, txReceipts, nil
}

func allReceipts(txReceipts []*types.Receipt, depositReceipts []*types.Receipt) types.Receipts {
Expand Down
6 changes: 6 additions & 0 deletions go/enclave/evm/evm_facade.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,12 @@ func executeTransaction(
for _, l := range receipt.Logs {
l.BlockHash = batchHash
}

if header.Coinbase.Big().Cmp(gethcommon.Big0) != 0 {
gasUsed := big.NewInt(0).SetUint64(receipt.GasUsed)
executionGasCost := big.NewInt(0).Mul(gasUsed, header.BaseFee)
s.AddBalance(header.Coinbase, executionGasCost)
}
}

header.MixDigest = before
Expand Down
1 change: 0 additions & 1 deletion go/enclave/gas/gas.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ func (gp *ObscuroGasPool) ForTransaction(tx *types.Transaction) (*gethcore.GasPo
// CalculateL1GasUsed - calculates the gas cost of having a transaction on the l1.
func CalculateL1GasUsed(data []byte, overhead *big.Int) *big.Int {
reducedTxSize := uint64(len(data))
reducedTxSize = (reducedTxSize * 90) / 100
reducedTxSize = reducedTxSize * params.TxDataNonZeroGasEIP2028

l1Gas := new(big.Int).SetUint64(reducedTxSize)
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
1 change: 1 addition & 0 deletions go/node/docker_node.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,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 @@
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)

Check warning on line 23 in go/wallet/wallet.go

View workflow job for this annotation

GitHub Actions / lint

var-naming: interface method parameter chainId should be chainID (revive)

// 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 @@
return types.SignNewTx(m.prvKey, types.NewLondonSigner(m.chainID), tx)
}

func (m *inMemoryWallet) SignTransactionForChainID(tx types.TxData, chainId *big.Int) (*types.Transaction, error) {

Check warning on line 75 in go/wallet/wallet.go

View workflow job for this annotation

GitHub Actions / lint

var-naming: method parameter chainId should be chainID (revive)
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
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
18 changes: 14 additions & 4 deletions integration/networktest/actions/native_fund_actions.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@ import (
)

type SendNativeFunds struct {
FromUser int
ToUser int
Amount *big.Int
FromUser int
ToUser int
Amount *big.Int
GasLimit *big.Int
SkipVerify bool

user *userwallet.UserWallet
txHash *common.Hash
Expand All @@ -33,7 +35,11 @@ func (s *SendNativeFunds) Run(ctx context.Context, _ networktest.NetworkConnecto
if err != nil {
return ctx, err
}
txHash, err := user.SendFunds(ctx, target.Address(), s.Amount)
gas := uint64(1_000_000)
if s.GasLimit != nil {
gas = s.GasLimit.Uint64()
}
txHash, err := user.SendFunds(ctx, target.Address(), s.Amount, gas)
if err != nil {
return nil, err
}
Expand All @@ -43,6 +49,10 @@ func (s *SendNativeFunds) Run(ctx context.Context, _ networktest.NetworkConnecto
}

func (s *SendNativeFunds) Verify(ctx context.Context, _ networktest.NetworkConnector) error {
if s.SkipVerify {
return nil
}

receipt, err := s.user.AwaitReceipt(ctx, s.txHash)
if err != nil {
return fmt.Errorf("failed to fetch receipt - %w", err)
Expand Down
2 changes: 1 addition & 1 deletion integration/networktest/env/testnet.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ func (t *testnetConnector) GetValidatorNode(_ int) networktest.NodeOperator {
}

func (t *testnetConnector) AllocateFaucetFundsWithWallet(ctx context.Context, account gethcommon.Address) error {
txHash, err := t.faucetWallet.SendFunds(ctx, account, _defaultFaucetAmount)
txHash, err := t.faucetWallet.SendFunds(ctx, account, _defaultFaucetAmount, 1_000_000)
if err != nil {
return err
}
Expand Down
8 changes: 5 additions & 3 deletions integration/networktest/log.go
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
package networktest

import (
"os"

"github.com/ethereum/go-ethereum/log"
"github.com/obscuronet/go-obscuro/integration/common/testlog"
)

// EnsureTestLogsSetUp calls Setup if it hasn't already been called (some tests run tests within themselves, we don't want
// the log folder flipping around for every subtest, so we assume this is called for the top level test that is running
// and ignore subsequent calls
func EnsureTestLogsSetUp(testName string) {
func EnsureTestLogsSetUp(testName string) *os.File {
logger := testlog.Logger()
if logger != nil {
return // already setup, do not reconfigure
return nil // already setup, do not reconfigure
}
testlog.Setup(&testlog.Cfg{
return testlog.Setup(&testlog.Cfg{
// todo (@matt) - walk up the dir tree to find /integration/.build or find best practice solution
// bit of a hack - tests need to be in a package nested within /tests to get logs in the right place
LogDir: "../../../.build/networktest/",
Expand Down
5 changes: 3 additions & 2 deletions integration/networktest/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,13 @@
// networktest.Run(t, env.DevTestnet(), tests.smokeTest())
// networktest.Run(t, env.LocalDevNetwork(WithNumValidators(8)), traffic.RunnerTest(traffic.NativeFundsTransfers(), 30*time.Second)
func Run(testName string, t *testing.T, env Environment, action Action) {
EnsureTestLogsSetUp(testName)
logFile := EnsureTestLogsSetUp(testName)
network, envCleanup, err := env.Prepare()
if err != nil {
t.Fatal(err)
}
ctx, cancelCtx := context.WithCancel(context.Background())
initialCtx, cancelCtx := context.WithCancel(context.Background())
ctx := context.WithValue(initialCtx, "logFile", logFile)

Check warning on line 26 in integration/networktest/runner.go

View workflow job for this annotation

GitHub Actions / lint

context-keys-type: should not use basic type string as key in context.WithValue (revive)
defer func() {
envCleanup()
cancelCtx()
Expand Down
Loading
Loading