From 3d367881955c770e6525274abccda04030846bc7 Mon Sep 17 00:00:00 2001 From: Agnar Song Date: Thu, 19 Nov 2026 03:56:44 +0000 Subject: [PATCH 01/23] finished devnet 1 --- contracts/hardhat.config.ts | 14 ++++ contracts/src/deploy-config/hoodidev.ts | 65 +++++++++++++++++++ contracts/src/deploy-utils.ts | 36 +++++++++- .../deploy-config/hoodidev-deploy-config.json | 60 +++++++++++++++++ 4 files changed, 172 insertions(+), 3 deletions(-) create mode 100644 contracts/src/deploy-config/hoodidev.ts create mode 100644 ops/l2-genesis/deploy-config/hoodidev-deploy-config.json diff --git a/contracts/hardhat.config.ts b/contracts/hardhat.config.ts index 02e5d030d..b913c4833 100644 --- a/contracts/hardhat.config.ts +++ b/contracts/hardhat.config.ts @@ -41,6 +41,13 @@ const QA_URL = process.env.QA_RPC_URL || 'http://127.0.0.1:8545' const SEPOLIA_URL = process.env.SEPOLIA_RPC_URL || 'http://127.0.0.1:8545' const HOLESKY_URL = process.env.HOLESKY_RPC_URL || 'http://127.0.0.1:8545' const HOODI_URL = process.env.HOODI_RPC_URL || 'http://127.0.0.1:8545' +// hoodidev: a private Morph L2 whose L1 is the public Ethereum Hoodi testnet. Unlike the networks above it does NOT +// fall back to the publicly known Anvil key: without DEPLOYER_PRIVATE_KEY (or with that public key) there is no +// signer, so a deployment fails instead of putting admin rights behind a key that anyone can use. +const PUBLIC_ANVIL_KEY = '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80' +const HOODIDEV_URL = process.env.HOODIDEV_RPC_URL || 'http://127.0.0.1:8545' +const HOODIDEV_PK = process.env.DEPLOYER_PRIVATE_KEY +const HOODIDEV_ACCOUNTS = HOODIDEV_PK && HOODIDEV_PK.toLowerCase() !== PUBLIC_ANVIL_KEY ? [HOODIDEV_PK] : [] module.exports = { defaultNetwork: 'hardhat', @@ -107,6 +114,13 @@ module.exports = { gas: 'auto', gasPrice: 'auto', accounts: [DEPLOYER_PK] + }, + hoodidev: { + url: HOODIDEV_URL, + chainId: 560048, + gas: 'auto', + gasPrice: 'auto', + accounts: HOODIDEV_ACCOUNTS } }, foundry: { diff --git a/contracts/src/deploy-config/hoodidev.ts b/contracts/src/deploy-config/hoodidev.ts new file mode 100644 index 000000000..99a215b91 --- /dev/null +++ b/contracts/src/deploy-config/hoodidev.ts @@ -0,0 +1,65 @@ +// hoodidev: a private Morph L2 (chain 53077) whose L1 is the public Ethereum Hoodi testnet (chain 560048). +// Derived from l1.ts (the local devnet). Do NOT reuse hoodi.ts: that is Morph's official Hoodi deployment. +const config = { + // Global configuration + contractAdmin: '0x2d66b081246b93caC31dEdC03421ee863AE0624D', + l1FeeVaultRecipient: '0x2d66b081246b93caC31dEdC03421ee863AE0624D', + + l1WETHAddress: "", + l1USDCAddress: "", + + // chainID config + l1ChainID: 560048, + l2ChainID: 53077, + + // L1MessageQueue config + l1MessageQueueMaxGasLimit: 30000000, + + // gasPriceOracle config + l2BaseFee: 0.1, // Gwei + + // verify contract config + programVkey: '0x0084f08a14f8199f87e7ae6011336724ec187b3656859184f04c7e8f382a2902', + // rollup contract config + // initialize config + finalizationPeriodSeconds: 10, + rollupProofWindow: 86400, + proofRewardPercent: 70, + rollupDelayPeriod: 86400, + + // challenge config + batchSubmitterAddresses: ['0x988709F4B219faC95440CEF25F2c50c554201008'], + rollupChallenger: '0x2d66b081246b93caC31dEdC03421ee863AE0624D', + // genesis config + // The genesis batch header comes out of the L2 genesis tool, so it is passed in through MORPH_BATCH_HEADER instead of + // being rewritten into this file (l1.ts is rewritten in place by the devnet's main.py). Empty means "not generated yet": + // the deploy driver refuses to run `initialize` without it. + batchHeader: process.env.MORPH_BATCH_HEADER || '', + + // submitter initialize config + submitterOwner: '0x2d66b081246b93caC31dEdC03421ee863AE0624D', + submitterChallengeDeposit: 0.01, // 0.01 ether (devnet: l1.ts uses 1) + submitterMinimumStake: 0.01, // 0.01 ether (devnet: l1.ts uses 1); `register` stakes this from the owner + submitterRewardPercentage: 100, + // register sequencers + l2SequencerAddresses: [ + "0x783698dCDEBdc96785c5c60ED96113612bA09c2b", + "0x310824AA27a29D269d2F9C0a8563C0e3C98dD226", + "0x343C5154FFe47c8a07DF5ea6846404e68E9809A2", + "0xaaC606d51De6A5aBF0d1B9dbd5ed5Ff2Ac2e521B" + ], + l2SequencerTmKeys: [ + "0x5280d0eee2a64d3ad29480d15ffd1b048ce5908f180b5ccd65cc3dcf00941abb", + "0xb798eb74c06721d54c659e9ea2bc232a7f95e96d234cc87186b2ab8f43db6935", + "0xecffad01129786ba9c6293aa664f952894dc4019762804799dfa1ffb6e4ed040", + "0x8d29695bb4157c6960adb486be1d9a0c9f728524d09bffcc4f8932ed15221c4a" + ], + l2SequencerBlsKeys: [ + "0x00000000000000000000000000000000095ad465c2895ee825c7d4f1b60a18734db57d4108369e47c6e3a94ee15846f825c06dad5d98f503bd31ece1d9f94b11000000000000000000000000000000000c5d6ba04bc9b9674dd2acbfc5caed3976c1b8be2ec90a03d78dffe924648b4fba82225aff43c744310c6a60185b75ac000000000000000000000000000000000fce6be001c871a11b9db1c6c15f0a6999de5646941a74486206dc784f0b3ffe11799212f3f44ef754b4a0f1ecf85639000000000000000000000000000000000b2f06634e5ea719682c30911c94dfb560f0b7656b5c34a871ea035e3fe7b041885420f8fe1e251f1cce5cdb7514869e", + "0x0000000000000000000000000000000010173aeac4ff317e8e60493f962b91dbd27614e1f6594e17d18a02968bd1fd698b6703092ab8622cd22d6948d9421156000000000000000000000000000000000801aea15697ab4d7a808be45377e4f0d2f54857fdc04031e476402ff16c66a6cbcc5f09a84bf85400c8afbabed006600000000000000000000000000000000015fc71b2c4e81148274e6169c9c9aace8c34fa6030547650242b6c32527dd23a996416e32640bce4f495a0afabc7dbb900000000000000000000000000000000088c4a0dffccc96bce47aef0e176b129457a5f3ae1651b132ddb418e9f7b5850a38c6fec1be6d169eb88dc1619648bf4", + "0x0000000000000000000000000000000003fd9468a8ceffc1b696874517777ef8bfdc9a1bade95c480ee2624903e648c1caf01c65de5b4fda8876a3a0e8d9f0890000000000000000000000000000000004c02f3609a0f61d12fe737dcbb047d5253bd3ff905b55c0e0f932b476fd77d172a58b72ef0f506407870988dd6038220000000000000000000000000000000017fa5765899f60f7a58f8ccdaaa295cde55992231710672692ba6a71a4faa9572f728f438ded65576a570d57e19fd304000000000000000000000000000000001226138813bde98af3464ed03649d8c731bc4e5cb3d26b53bf7483f4105d18bbb3f19e23905119e156e7d003d2fd125c", + "0x00000000000000000000000000000000109bf02a2636c0dc1968b0a50db77251eb090c3e9f51e2a2bc60c4ac72213f41f01f0a34e92c2e0625bd62e28e27edb500000000000000000000000000000000139969bd92522113c0615659874d1fae311ad8152d0584c7b57ffc14927067486dcf86413c5684fccc1163ee2d45c1c1000000000000000000000000000000000f172603f70a0730d100ad6d28bde477195987062e8ade83b82d093935d956ff20ca768c26263577b094f1cb756adc400000000000000000000000000000000010dde3acca00b4ff1b4976500a8f97e92246f43f78cadc95c4993dfc4f4c501c33d42a4bf52587f4931287b59623149c" + ], +} + +export default config diff --git a/contracts/src/deploy-utils.ts b/contracts/src/deploy-utils.ts index ddb59efe5..4d2138a9b 100644 --- a/contracts/src/deploy-utils.ts +++ b/contracts/src/deploy-utils.ts @@ -5,6 +5,36 @@ import { ethers } from 'ethers' const fs = require("fs") +// Public RPC endpoints sit behind several nodes: a read issued right after a mined write can reach a node that has not +// seen the block yet and fail (empty return data) or return stale state. Retrying the read is opt-in: with +// MORPH_READ_RETRIES unset (the default) behaviour is exactly as before, so local devnets are unaffected. +const READ_RETRIES = Number(process.env.MORPH_READ_RETRIES || 0) +const READ_RETRY_DELAY_MS = Number(process.env.MORPH_READ_RETRY_DELAY_MS || 2000) + +const matchesExpected = (actual: any, expected: any): boolean => { + if (ethers.utils.isAddress(expected)) { + return typeof actual === 'string' && actual.toLowerCase() === expected.toLowerCase() + } + return actual === expected || !!(actual && actual.eq && actual.eq(expected)) +} + +// Calls `read` until it succeeds and (if `expected` is given) matches, at most READ_RETRIES extra times. +// The final attempt is returned/thrown as-is so the caller's own assertion reports the real problem. +const readWithRetry = async (read: () => Promise, expected?: any): Promise => { + for (let attempt = 0; ; attempt++) { + const last = attempt >= READ_RETRIES + try { + const actual = await read() + if (last || expected === undefined || matchesExpected(actual, expected)) { + return actual + } + } catch (e) { + if (last) throw e + } + await sleep(READ_RETRY_DELAY_MS) + } +} + /** * Helper function for asserting that a contract variable is set to the expected value. * @@ -28,9 +58,9 @@ export const assertContractVariable = async ( if (caller === null || !ethers.utils.isAddress(caller)) { caller = ethers.constants.AddressZero } - const actual = await temp.callStatic[variable]({ + const actual = await readWithRetry(() => temp.callStatic[variable]({ from: caller, - }) + }), expected) if (ethers.utils.isAddress(expected)) { assert( @@ -60,7 +90,7 @@ export const assertContractVariableWithSigner = async ( contract.signer, ) - const actual = await temp.callStatic[variable]() + const actual = await readWithRetry(() => temp.callStatic[variable](), expected) if (ethers.utils.isAddress(expected)) { assert( diff --git a/ops/l2-genesis/deploy-config/hoodidev-deploy-config.json b/ops/l2-genesis/deploy-config/hoodidev-deploy-config.json new file mode 100644 index 000000000..a1c700acd --- /dev/null +++ b/ops/l2-genesis/deploy-config/hoodidev-deploy-config.json @@ -0,0 +1,60 @@ +{ + "l1ChainID": 560048, + "l2ChainID": 53077, + "finalSystemOwner": "0x2d66b081246b93caC31dEdC03421ee863AE0624D", + "proxyAdminOwner": "0x2d66b081246b93caC31dEdC03421ee863AE0624D", + "BLOCK_SIGNER_ADDRESS": "0xaEcFF2a7E677cEFa56643Ff0aD06e233a3FdC402", + "l1FeeVaultRecipient": "0x2d66b081246b93caC31dEdC03421ee863AE0624D", + "sequencerFeeVaultRecipient": "0x2d66b081246b93caC31dEdC03421ee863AE0624D", + "l2BridgeFeeVaultRecipient": "0x2d66b081246b93caC31dEdC03421ee863AE0624D", + "fundDevAccounts": true, + "l1StartingBlockTag": "REPLACE_WITH_HOODI_START_BLOCK_HEX", + "maxTxPerBlock": 1000, + "maxTxPayloadBytesPerBlock": 737280, + "gasPriceOracleOverhead": 2500, + "gasPriceOracleScalar": 1000000000, + "gasPriceOracleOwner": "0x2d66b081246b93caC31dEdC03421ee863AE0624D", + "govVotingDuration": 1000, + "govBatchBlockInterval": 200, + "govBatchTimeout": 600, + "govRollupEpoch": 100, + "recordOracleAddress": "0x2d66b081246b93caC31dEdC03421ee863AE0624D", + "recordNextBatchSubmissionIndex": 1, + "morphTokenName": "Morph Token", + "morphTokenSymbol": "Morph", + "morphTokenOwner": "0x2d66b081246b93caC31dEdC03421ee863AE0624D", + "morphTokenInitialSupply": 1000000000, + "morphTokenDailyInflationRate": 1, + "morph203Time": 0, + "viridianTime": 0, + "emeraldTime": 0, + "celadonTime": 0, + "l2StakingSequencerMaxSize": 4, + "l2StakingUnDelegatedLockEpochs": 2, + "l2StakingRewardStartTime": 1728000000, + "l2StakingPks": [ + "0xd99870855d97327d20c666abc78588f1449b1fac76ed0c86c1afb9ce2db85f32", + "0x0890c388c3bf5e04fee1d8f3c117e5f44f435ced7baf7bfd66c10e1f3a3f4b10", + "0x6fd437eef7a83c486bd2e0a802ae071b3912d125ac31ac08f60841fd891559ae", + "0x9ae53aecdaebe4dcbfec96f3123a2a8c53f9596bf4b3d5adc9a388ccb361b4c0" + ], + "l2StakingAddresses": [ + "0x783698dCDEBdc96785c5c60ED96113612bA09c2b", + "0x310824AA27a29D269d2F9C0a8563C0e3C98dD226", + "0x343C5154FFe47c8a07DF5ea6846404e68E9809A2", + "0xaaC606d51De6A5aBF0d1B9dbd5ed5Ff2Ac2e521B" + ], + "l2StakingTmKeys": [ + "0x5280d0eee2a64d3ad29480d15ffd1b048ce5908f180b5ccd65cc3dcf00941abb", + "0xb798eb74c06721d54c659e9ea2bc232a7f95e96d234cc87186b2ab8f43db6935", + "0xecffad01129786ba9c6293aa664f952894dc4019762804799dfa1ffb6e4ed040", + "0x8d29695bb4157c6960adb486be1d9a0c9f728524d09bffcc4f8932ed15221c4a" + ], + "l2StakingBlsKeys": [ + "0x00000000000000000000000000000000095ad465c2895ee825c7d4f1b60a18734db57d4108369e47c6e3a94ee15846f825c06dad5d98f503bd31ece1d9f94b11000000000000000000000000000000000c5d6ba04bc9b9674dd2acbfc5caed3976c1b8be2ec90a03d78dffe924648b4fba82225aff43c744310c6a60185b75ac000000000000000000000000000000000fce6be001c871a11b9db1c6c15f0a6999de5646941a74486206dc784f0b3ffe11799212f3f44ef754b4a0f1ecf85639000000000000000000000000000000000b2f06634e5ea719682c30911c94dfb560f0b7656b5c34a871ea035e3fe7b041885420f8fe1e251f1cce5cdb7514869e", + "0x0000000000000000000000000000000010173aeac4ff317e8e60493f962b91dbd27614e1f6594e17d18a02968bd1fd698b6703092ab8622cd22d6948d9421156000000000000000000000000000000000801aea15697ab4d7a808be45377e4f0d2f54857fdc04031e476402ff16c66a6cbcc5f09a84bf85400c8afbabed006600000000000000000000000000000000015fc71b2c4e81148274e6169c9c9aace8c34fa6030547650242b6c32527dd23a996416e32640bce4f495a0afabc7dbb900000000000000000000000000000000088c4a0dffccc96bce47aef0e176b129457a5f3ae1651b132ddb418e9f7b5850a38c6fec1be6d169eb88dc1619648bf4", + "0x0000000000000000000000000000000003fd9468a8ceffc1b696874517777ef8bfdc9a1bade95c480ee2624903e648c1caf01c65de5b4fda8876a3a0e8d9f0890000000000000000000000000000000004c02f3609a0f61d12fe737dcbb047d5253bd3ff905b55c0e0f932b476fd77d172a58b72ef0f506407870988dd6038220000000000000000000000000000000017fa5765899f60f7a58f8ccdaaa295cde55992231710672692ba6a71a4faa9572f728f438ded65576a570d57e19fd304000000000000000000000000000000001226138813bde98af3464ed03649d8c731bc4e5cb3d26b53bf7483f4105d18bbb3f19e23905119e156e7d003d2fd125c", + "0x00000000000000000000000000000000109bf02a2636c0dc1968b0a50db77251eb090c3e9f51e2a2bc60c4ac72213f41f01f0a34e92c2e0625bd62e28e27edb500000000000000000000000000000000139969bd92522113c0615659874d1fae311ad8152d0584c7b57ffc14927067486dcf86413c5684fccc1163ee2d45c1c1000000000000000000000000000000000f172603f70a0730d100ad6d28bde477195987062e8ade83b82d093935d956ff20ca768c26263577b094f1cb756adc400000000000000000000000000000000010dde3acca00b4ff1b4976500a8f97e92246f43f78cadc95c4993dfc4f4c501c33d42a4bf52587f4931287b59623149c" + ], + "l1StakingProxy": "0x000000000000000000000000000000000000dEaD" +} From 4d87c3583d2d2c80bc6731e29eadda9823610927 Mon Sep 17 00:00:00 2001 From: Agnar Song Date: Thu, 19 Nov 2026 11:25:15 +0000 Subject: [PATCH 02/23] ops: run Morph L2 with native processes on public Hoodi (no Docker) --- ops/native-hoodi/.gitignore | 11 + ops/native-hoodi/README.md | 119 +++++++ ops/native-hoodi/RUNBOOK.md | 123 ++++++++ ops/native-hoodi/env/hoodi.env.example | 17 + ops/native-hoodi/notes/budget.md | 38 +++ ops/native-hoodi/notes/config-audit.md | 43 +++ ops/native-hoodi/notes/hoodi-probe-raw.txt | 19 ++ ops/native-hoodi/notes/hoodi-probe.md | 32 ++ ops/native-hoodi/notes/issues.md | 248 +++++++++++++++ ops/native-hoodi/notes/versions.md | 47 +++ ops/native-hoodi/scripts/add-node2.py | 100 ++++++ ops/native-hoodi/scripts/build-all.sh | 22 ++ ops/native-hoodi/scripts/check-no-secrets.sh | 21 ++ ops/native-hoodi/scripts/deploy-l1.sh | 264 ++++++++++++++++ ops/native-hoodi/scripts/deposit-test.sh | 34 ++ ops/native-hoodi/scripts/dryrun-fork.sh | 49 +++ ops/native-hoodi/scripts/export-deployment.sh | 36 +++ ops/native-hoodi/scripts/init-secrets.sh | 29 ++ ops/native-hoodi/scripts/l2-bootstrap.sh | 52 ++++ ops/native-hoodi/scripts/lib/env.sh | 40 +++ ops/native-hoodi/scripts/morph-native.sh | 290 ++++++++++++++++++ ops/native-hoodi/scripts/probe-hoodi.sh | 73 +++++ ops/native-hoodi/scripts/reset-env.sh | 165 ++++++++++ ops/native-hoodi/scripts/restart-test.sh | 119 +++++++ .../scripts/rpc-consistency-proxy.js | 227 ++++++++++++++ .../scripts/rpc-consistency-proxy.selftest.js | 63 ++++ ops/native-hoodi/scripts/send-tx.js | 30 ++ ops/native-hoodi/scripts/setup-nodes.py | 131 ++++++++ ops/native-hoodi/scripts/sweep-submitter.sh | 20 ++ ops/native-hoodi/scripts/verify-l1.sh | 92 ++++++ .../scripts/withdraw-proof.selftest.js | 24 ++ ops/native-hoodi/scripts/withdraw-test.js | 128 ++++++++ ops/native-hoodi/scripts/withdraw-test.sh | 12 + 33 files changed, 2718 insertions(+) create mode 100644 ops/native-hoodi/.gitignore create mode 100644 ops/native-hoodi/README.md create mode 100644 ops/native-hoodi/RUNBOOK.md create mode 100644 ops/native-hoodi/env/hoodi.env.example create mode 100644 ops/native-hoodi/notes/budget.md create mode 100644 ops/native-hoodi/notes/config-audit.md create mode 100644 ops/native-hoodi/notes/hoodi-probe-raw.txt create mode 100644 ops/native-hoodi/notes/hoodi-probe.md create mode 100644 ops/native-hoodi/notes/issues.md create mode 100644 ops/native-hoodi/notes/versions.md create mode 100755 ops/native-hoodi/scripts/add-node2.py create mode 100755 ops/native-hoodi/scripts/build-all.sh create mode 100755 ops/native-hoodi/scripts/check-no-secrets.sh create mode 100755 ops/native-hoodi/scripts/deploy-l1.sh create mode 100755 ops/native-hoodi/scripts/deposit-test.sh create mode 100755 ops/native-hoodi/scripts/dryrun-fork.sh create mode 100755 ops/native-hoodi/scripts/export-deployment.sh create mode 100755 ops/native-hoodi/scripts/init-secrets.sh create mode 100755 ops/native-hoodi/scripts/l2-bootstrap.sh create mode 100644 ops/native-hoodi/scripts/lib/env.sh create mode 100755 ops/native-hoodi/scripts/morph-native.sh create mode 100755 ops/native-hoodi/scripts/probe-hoodi.sh create mode 100755 ops/native-hoodi/scripts/reset-env.sh create mode 100755 ops/native-hoodi/scripts/restart-test.sh create mode 100755 ops/native-hoodi/scripts/rpc-consistency-proxy.js create mode 100755 ops/native-hoodi/scripts/rpc-consistency-proxy.selftest.js create mode 100755 ops/native-hoodi/scripts/send-tx.js create mode 100755 ops/native-hoodi/scripts/setup-nodes.py create mode 100755 ops/native-hoodi/scripts/sweep-submitter.sh create mode 100755 ops/native-hoodi/scripts/verify-l1.sh create mode 100755 ops/native-hoodi/scripts/withdraw-proof.selftest.js create mode 100755 ops/native-hoodi/scripts/withdraw-test.js create mode 100755 ops/native-hoodi/scripts/withdraw-test.sh diff --git a/ops/native-hoodi/.gitignore b/ops/native-hoodi/.gitignore new file mode 100644 index 000000000..372357b5e --- /dev/null +++ b/ops/native-hoodi/.gitignore @@ -0,0 +1,11 @@ +# runtime data, binaries, secrets: never commit +/bin/ +/run/ +/deployments/ +/env/secrets.env +/env/archive/ +*.out +journal.rlp +submitter-leveldb/ +__pycache__/ +*.pyc diff --git a/ops/native-hoodi/README.md b/ops/native-hoodi/README.md new file mode 100644 index 000000000..2c6b58279 --- /dev/null +++ b/ops/native-hoodi/README.md @@ -0,0 +1,119 @@ +# Morph L2 on native processes, with public Ethereum Hoodi as L1 + +Run a private Morph L2 (chain id 53077) **without Docker**: every component is a native process, and the L1 is the +public Ethereum **Hoodi** testnet (chain id 560048), so you do not run an L1 yourself. The Rollup contracts are +deployed on Hoodi, and L2 batches are submitted there as EIP-4844 blob transactions. + +``` + public Hoodi: execution RPC (ethpandaops, fallbacks 0xrpc.io / publicnode) + beacon RPC + ▲ + l1-proxy (127.0.0.1:18546, scripts/rpc-consistency-proxy.js): every process reaches L1 through it + ▲ + ┌──────┴───────────────────────────────────────────────────────────────────────┐ + │ morph-el-0 ◀▶ node-0 block producer (tendermint, single validator, sequencer key) + │ morph-el-1 ◀▶ node-1 "layer1" verify mode: re-derives the chain from L1 blobs, no tendermint + │ morph-el-2 ◀▶ node-2 full node with tendermint, no sequencer key; required so node-0 can restart + │ tx-submitter submits batches to the Rollup on Hoodi and finalizes them + │ gas-price-oracle writes L1 fees into the L2 GasPriceOracle + └──────────────────────────────────────────────────────────────────────────────┘ +``` + +Why it is shaped like this, and every problem met on the way: `notes/issues.md`. How to operate it: `RUNBOOK.md`. + +## 1. What this changes in the Morph repo + +Four small, already-committed changes on this branch (everything else is in this directory): + +- `contracts/hardhat.config.ts`: a `hoodidev` network (chain 560048, RPC from `HOODIDEV_RPC_URL`, key from `DEPLOYER_PRIVATE_KEY`) +- `contracts/src/deploy-config/hoodidev.ts`: deploy config for it +- `ops/l2-genesis/deploy-config/hoodidev-deploy-config.json`: L2 genesis config for it +- `contracts/src/deploy-utils.ts`: optional read retries (`MORPH_READ_RETRIES`), used because public RPCs are read-after-write inconsistent + +## 2. What you need + +| | | +|---|---| +| OS / CPU / disk | Linux x86_64; ~10 GB free for builds (Rust target dir ~1.3 GB, node_modules ~0.7 GB) and chain data | +| Build tools | Go ≥ 1.24 (tested 1.25.7), Rust (tested 1.95; needs OpenSSL headers + pkg-config), Node + yarn 1.x (tested Node 24, yarn 1.22), make, gcc | +| Runtime tools | Node ≥ 18, Python ≥ 3.9, curl, Foundry `cast` and `anvil` (tested 1.9.0) | +| Network | outbound HTTPS to the Hoodi RPC and beacon endpoints (no inbound ports) | +| **Hoodi ETH** | **about 1.5 ETH in your deployer account**: ~0.07 for gas, 1 ETH is passed on to the batch submitter (which then spends ~0.09 ETH/day). Faucet: https://hoodi.ethpandaops.io | +| A deployer key | one private key you control and fund. Other keys are generated for you | + +If your tools are not on `PATH` by default, put the `PATH`/build settings in a file and `export MORPH_ENV_FILE=/path/to/that/file`; +every script sources it first (`scripts/lib/env.sh`) and prints exactly what is missing if a tool is absent. + +Ports used on 127.0.0.1 (stop other local devnets first): 18546, 8545/8546/8551, 8645/8646/8651, 8745/8746/8751, +30303-30305, 26656/26657/26660, 26666/26667/26670, 27660, 6160-6162, 6070, 8060. + +## 3. From zero to a running chain + +All commands from this directory (`ops/native-hoodi/`). + +```bash +# 1. build all binaries into ./bin (about 5-10 minutes the first time) +scripts/build-all.sh + +# 2. keys: your funded deployer key + three generated ones. Prints addresses only. Then fund the DEPLOYER address. +DEPLOYER_PRIVATE_KEY=0x... scripts/init-secrets.sh + +# 3. (optional, free) rehearse the whole L1 deployment on a local anvil fork of Hoodi (~5 minutes when the RPC behaves). +# It reads state from the public RPC, so a hiccup there can make it hang or fail to start: stop it (Ctrl-C) and run it +# again, or point it at another node with FORK_URL=https://... +scripts/dryrun-fork.sh + +# 4. deploy the L1 contracts to Hoodi and generate the L2 genesis. IRREVERSIBLE, spends testnet ETH. About 20-45 minutes +# (public RPCs are slow; it is resumable: re-running skips finished steps) +source env/secrets.env +RPC_URL="$L1_ETH_RPC" RUN_DIR="$PWD/run/l1" WAIT_FINALIZED=1 SUBMITTER_FUND_ETH=1 scripts/deploy-l1.sh +RPC_URL="$L1_ETH_RPC" scripts/verify-l1.sh # reads the chain: expect "53 passed, 0 failed" + +# 5. create the node directories, start everything, bootstrap L2 balances and the gas-oracle permission +scripts/morph-native.sh setup +scripts/morph-native.sh up +scripts/l2-bootstrap.sh +scripts/morph-native.sh status +``` + +Do not trust a hardhat task's exit code: they often print an error and exit 0. `verify-l1.sh` reads the actual on-chain state. + +## 4. Check that it works + +```bash +scripts/morph-native.sh status # 9 processes running; el-0 and el-2 heights equal and rising +cast block-number --rpc-url http://127.0.0.1:8545 # run twice a few seconds apart: it grows +H=$(( $(cast block-number --rpc-url http://127.0.0.1:8645) - 1 )) # node-1 lags up to one batch; compare below its tip +for p in 8545 8645 8745; do cast block $H --field hash --rpc-url http://127.0.0.1:$p; done # three equal hashes +# batches on L1 (ROLLUP = Proxy__Rollup address in run/l1/deployment/hoodidev.json); both numbers keep rising +cast call $ROLLUP 'lastCommittedBatchIndex()(uint256)' --rpc-url "$L1_ETH_RPC" +cast call $ROLLUP 'lastFinalizedBatchIndex()(uint256)' --rpc-url "$L1_ETH_RPC" +``` + +End-to-end tests (each uses a few mETH; read the header of each script): + +| script | what it proves | time | +|---|---|---| +| `scripts/deposit-test.sh` | L1 → L2 deposit arrives on both L2 nodes | ~8 min | +| `scripts/withdraw-test.sh` | L2 → L1 withdrawal: Merkle proof built locally, relayed on L1 | ~10 min | +| `scripts/restart-test.sh` (then `restart-test.sh T7`) | crash/restart recovery of every component | ~35 min | +| `scripts/rpc-consistency-proxy.selftest.js`, `scripts/withdraw-proof.selftest.js` | offline unit checks | seconds | + +## 5. Daily use, reset, export + +| | | +|---|---| +| `scripts/morph-native.sh status|up|down|logs NAME|kill NAME|start NAME` | operate the stack; `down` keeps chain data | +| `scripts/reset-env.sh plan|run|restore|list` | move run data (and with `--with-build` the binaries, with `--new-keys` the keys) into `run/archive/`; nothing is deleted. A new L2 genesis needs a new L1 deployment | +| `scripts/sweep-submitter.sh` | send the submitter's remaining Hoodi ETH back to the deployer (stack must be down) | +| `scripts/export-deployment.sh NAME` | save contract addresses, genesis files and test outputs (no private keys) to `deployments/NAME/` | +| `scripts/check-no-secrets.sh` | run before committing: fails if anything looks like a private key | + +`bin/`, `run/`, `env/secrets.env`, `env/archive/` and `deployments/` are git-ignored. **Never commit or paste private keys.** + +## 6. Limits worth knowing + +- Do not remove node-2: after a restart node-0 only resumes block production if it has a tendermint peer (`notes/issues.md` I-028). +- Resetting the L2 means redeploying L1: the Rollup on Hoodi is bound to this chain's batches. Old deployments stay on Hoodi as orphan contracts. +- Deposit gas limits must be generous (use ≥ 400000), see `RUNBOOK.md` section 7. +- Not covered: HA sequencer cluster, reth, multi-day soak, several withdrawals in one batch. +- L2 chain id 53077 is shared with other Morph-style devnets; do not join them. diff --git a/ops/native-hoodi/RUNBOOK.md b/ops/native-hoodi/RUNBOOK.md new file mode 100644 index 000000000..d358c74c5 --- /dev/null +++ b/ops/native-hoodi/RUNBOOK.md @@ -0,0 +1,123 @@ +# 运行手册:Morph L2(原生进程)+ 公共 Hoodi 作为 L1 + +这份手册讲**怎么用**这套环境。想了解**为什么这样设计、中间踩过什么坑**,看 `PLAN.md` 和 `notes/issues.md`。 + +## 1. 它是什么 + +在本机用原生进程(不用 Docker)跑一条私有的 Morph L2(链 ID 53077),它的 L1 是**公共的以太坊 Hoodi 测试网**(链 ID 560048)。合约部署在 Hoodi 上,批次以 EIP-4844 blob 交易提交到 Hoodi。 + +``` + 公共 Hoodi:执行层 RPC(主 ethpandaops,备 0xrpc.io / publicnode)+ 信标 RPC(ethpandaops / publicnode) + ▲ + l1-proxy(本机 127.0.0.1:18546,rpc-consistency-proxy.js)——所有进程访问 L1 都经过它 + ▲ + ┌──────┴────────────────────────────────────────────────────────────────────────┐ + │ morph-el-0 ◀▶ node-0 出块节点(tendermint 单验证者,持有出块密钥) │ + │ morph-el-1 ◀▶ node-1 layer1 校验模式:不跑 tendermint,独立从 L1 的 blob 还原 │ + │ morph-el-2 ◀▶ node-2 全节点:跑 tendermint,没有出块密钥。**只为让 node-0 能重启** │ + │ tx-submitter 把 L2 批次提交到 Hoodi 的 Rollup,并最终化 │ + │ gas-price-oracle 把 L1 费用写入 L2 的 GasPriceOracle │ + └────────────────────────────────────────────────────────────────────────────────┘ +``` + +## 2. 前置条件 + +- 构建环境见 README 第 2 节。所有脚本通过 `scripts/lib/env.sh` 检查工具链;工具不在 PATH 上时,用环境变量 `MORPH_ENV_FILE` 指向一个设置 PATH 的文件。手工调用 `cast` 时需要自己保证它在 PATH 上。 +- 二进制在 `bin/`:`morph-geth/geth`、`morphnode/morphnode`、`morphnode/tendermint`、`tx-submitter/tx-submitter`、`gas-oracle/app`(构建方法见 `notes/versions.md` 和 `TODO.md` 的 P1)。 +- 密钥在 `env/secrets.env`(权限 600,**不要提交、不要贴到任何地方**),模板是 `env/hoodi.env.example`。4 个角色:deployer、sequencer、batch submitter、gas oracle。 + +## 3. 日常操作 + +全部通过 `scripts/morph-native.sh`: + +| 命令 | 作用 | +|---|---| +| `status` | 9 个进程、三个 L2 的高度、Hoodi 高度、代理统计、Rollup 已提交批次 | +| `up [NAME...]` | 启动全部或指定进程(按依赖顺序) | +| `down` | 停止全部进程,**保留链数据** | +| `kill NAME` / `start NAME` | 停 / 启动单个进程(`kill` 后不会被自动重启) | +| `logs NAME` | 跟随某个进程的日志(文件在 `run/l2/logs/`) | +| `setup` | 用 `deploy-l1.sh` 产出的创世文件生成运行目录(含 node-2) | +| `clean logs` / `clean l2` | **不删除**,只把数据挪到 `run/archive/`。`clean l2` 有重要后果,见第 7 节 | + +进程名:`l1-proxy morph-el-0 node-0 morph-el-1 node-1 morph-el-2 node-2 tx-submitter gas-price-oracle`。每个进程都在一个自动重启的守护外壳里,崩溃后 2 秒内被拉起。 + +## 4. 端口(全部 127.0.0.1) + +| 进程 | HTTP | WS | 引擎 | p2p | metrics | +|---|---|---|---|---|---| +| morph-el-0 | 8545 | 8546 | 8551 | 30303 | 6160 | +| morph-el-1 | 8645 | 8646 | 8651 | 30304 | 6161 | +| morph-el-2 | 8745 | 8746 | 8751 | 30305 | 6162 | +| node-0(tendermint) | | | | 26656 | 26660;tendermint rpc 26657 | +| node-1 | | | | 不跑 tendermint | 27660 | +| node-2(tendermint) | | | | 26666 | 26670;tendermint rpc 26667 | +| tx-submitter | | | | | 8060 | +| gas-price-oracle | | | | | 6070 | +| l1-proxy | 18546(`/stats` 看统计) | | | | | + +geth 的 metrics 端口用 6160 起,是因为有些环境里 6060 已被占用。**这些端口(8545、8551、30303 等)与其他本地以太坊 devnet 常用端口相同**,不能同时跑;先 `down` 或换端口。 + +## 5. 从零开始的流程 + +1. `scripts/build-all.sh`:编译全部二进制、安装合约依赖(P1)。 +2. 生成密钥(`cast wallet new`),写入 `env/secrets.env`;给 **deployer** 和 **batch submitter** 在 Hoodi 上领测试币。 +3. 部署 L1 合约并生成 L2 创世: + ```bash + RPC_URL=https://rpc.hoodi.ethpandaops.io RUN_DIR=$PWD/run/l1 WAIT_FINALIZED=1 SUBMITTER_FUND_ETH=1 scripts/deploy-l1.sh + RPC_URL=https://rpc.hoodi.ethpandaops.io scripts/verify-l1.sh # 读链上状态核对,不信退出码 + ``` + 约 20 分钟(其中约 13 分钟是等 Hoodi finalized)。**在公共链上花测试币、不可撤销。** +4. `scripts/morph-native.sh setup`,然后 `up`。 +5. `scripts/l2-bootstrap.sh`:给 deployer 和 oracle 在 L2 上转余额,并把 oracle 密钥加入 GasPriceOracle 白名单(否则 gas-price-oracle 没权限更新)。 +6. 用第 6 节的脚本验证。 + +## 6. 验证脚本 + +| 脚本 | 验证什么 | 耗时 | +|---|---|---| +| `scripts/verify-l1.sh` | 读 Hoodi 上的合约状态:owner、互相引用、创世批次、submitter 质押、所有代理的 implementation 与 admin、第一个序列器(53 项) | 1 分钟 | +| `scripts/deposit-test.sh` | L1→L2 存款到一个全新地址,等两个节点都到账 | 约 7 分钟 | +| `scripts/withdraw-test.sh` | L2→L1 提款:本地生成默克尔证明,在 L1 上领取 | 约 10 分钟 | +| `scripts/restart-test.sh` | 崩溃与重启恢复(T1 到 T8,T7 需单独指定) | 约 35 分钟 | +| `scripts/rpc-consistency-proxy.selftest.js` | 代理的 6 项行为(不碰网络) | 10 秒 | +| `scripts/withdraw-proof.selftest.js` | 默克尔证明算法与合约逐行一致(210 组) | 5 秒 | +| `scripts/probe-hoodi.sh` | 公共 RPC 的限流探测 | 1 分钟 | + +比较 node-1 与 node-0 是否一致,用 `cast block N --field hash --rpc-url http://127.0.0.1:8545 / 8645 / 8745` 逐块比对(已在三个节点间比过 0 到 7562 共 7563 个块,0 个不一致)。 + +## 7. 必须知道的限制和坑 + +1. **node-2 不能去掉。** 出块节点 node-0 重启后,必须有至少一个 tendermint 对端它才会恢复出块;没有时它静默停转(进程在、RPC 在、日志无错误、高度冻结)。node-1 是 layer1 校验模式,不算 tendermint 对端。见 `notes/issues.md` I-028。 +2. **L2 和 L1 上的 Rollup 是一一绑定的。** L1 上已提交的批次绑定着当前这条 L2 链。把 L2 清空重新从创世出块,新区块与旧批次对不上,tx-submitter 无法继续。**重置 L2 必须同时重新部署 L1 合约**(新的 `RUN_DIR`),所以 `clean l2` 只是把数据挪走。 +3. **存款的 gas 上限要给够。** 仓库示例里的 `110000` 在这套部署上会让 L2 上的执行失败(钱锁在 L1 网关里)。`deposit-test.sh` 默认 400000。 +4. **公共 RPC 不可靠。** 背后是多个节点:刚上链的区块可能读不到,偶尔限流。`l1-proxy` 解决这两件事,所有进程都应经过它,不要直接连 Hoodi。 +5. **node-1 不是实时的。** 它按批次推进,批次提交到 L1 后才前进,所以总会落后几百个块(约一个批次)。 +6. **不要把 `hardhat` 任务的退出码当成功。** 它们出错时常常只打印一行然后退出码为 0。部署后用 `verify-l1.sh` 读链上状态。 +7. **改动在 git 里。** 对上游仓库的改动只有 4 个文件:`contracts/hardhat.config.ts`(加网络 `hoodidev`)、`contracts/src/deploy-config/hoodidev.ts`、`ops/l2-genesis/deploy-config/hoodidev-deploy-config.json`、`contracts/src/deploy-utils.ts`(可选的读重试)。 + +## 8. 成本(实测) + +| 项目 | 数值 | +|---|---| +| L1 合约部署 | 77 笔交易、5130 万 gas;按 1 gwei 约 0.06 ETH(含 0.01 ETH 的 submitter 质押) | +| tx-submitter 运行 | 约 0.0004 ETH / 批次;批次约每 7 分钟一个,约 0.09 ETH / 天 | +| 部署期间的损耗 | 前几次失败遗留的孤儿合约,合计不到 0.2 ETH | + +## 9. 故障排查 + +| 现象 | 可能原因与做法 | +|---|---| +| L2 高度不动,进程都在 | 先看 node-0 日志是否停在 `derivation skipped: sequencer mode`:node-2 没跑,或没连上。`status` 看 node-2,日志里应有 `Added peer` | +| node-1 高度不涨 | 正常:等下一个批次提交。`status` 里 `lastCommittedBatchIndex` 在涨就没问题 | +| `failed to fetch L1 messages ... beyond current head` | 落后的 L1 后端;代理会重试。偶发无需处理 | +| gas-price-oracle 报 `ErrCallerNotAllowed` | 没跑 `l2-bootstrap.sh`,oracle 不在白名单 | +| 存款后 L2 没到账,但 L1 消息已入队 | 在 L2 上找类型 `0x7e` 的交易看回执:状态 0 通常是 `_gasLimit` 太小 | +| 起不来,端口被占 | 先 `scripts/morph-native.sh down`;本机上别的 devnet 或节点在用同样的端口也会冲突(`ss -ltn` 查) | + +## 10. 重置与部署记录(2026-11-19 新增,已用这套流程完整重做过一次) + +- `scripts/reset-env.sh plan|run|restore|list`:把运行数据(和可选的构建产物 `--with-build`、密钥 `--new-keys`)用 `mv` 归档到 `run/archive/<时间戳>/`,`restore` 可原样挪回。不删除任何东西。submitter 在 L1 上余额高于 0.02 ETH 时拒绝执行,先用 `scripts/sweep-submitter.sh`(要先 `down`)把钱转回 deployer。 +- `scripts/export-deployment.sh NAME`:把一次部署的合约地址、创世文件、账户地址(无私钥)、版本、测试输出存到 `deployments/NAME/`。重置之前先导出。 +- 已有记录:`deployments/devnet-1/`(旧)、`deployments/devnet-2/`(当前)。 +- 重做顺序:sweep → export 旧部署 → reset-env run --with-build --new-keys → build-all → deploy-l1(约 43 分钟,其中 `s30_initialize` 约 20 分钟)→ verify-l1 → setup → up → l2-bootstrap → 存款/提款/重启测试。 diff --git a/ops/native-hoodi/env/hoodi.env.example b/ops/native-hoodi/env/hoodi.env.example new file mode 100644 index 000000000..0171452ba --- /dev/null +++ b/ops/native-hoodi/env/hoodi.env.example @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# Template for env/secrets.env (the real file is git-ignored; never commit it). Easiest way to create it: +# DEPLOYER_PRIVATE_KEY=0x... scripts/init-secrets.sh # generates the three other keys for you +# The scripts derive everything else (contract addresses, start block) from the deployment output. + +# ---- L1 = public Ethereum Hoodi (chain id 560048) ---- +export L1_ETH_RPC="https://rpc.hoodi.ethpandaops.io" +# fallbacks the local l1-proxy switches to on rate limits (comma separated; override with RPC_FALLBACK_URLS) +# export RPC_FALLBACK_URLS="https://0xrpc.io/hoodi,https://ethereum-hoodi-rpc.publicnode.com" +# beacon endpoints: morphnode accepts a comma separated list; gas-price-oracle uses the first one only +export L1_BEACON_RPC="https://beacon.hoodi.ethpandaops.io,https://ethereum-hoodi-beacon-api.publicnode.com" + +# ---- private keys (cast wallet new). Never use the public Anvil key. ---- +export DEPLOYER_PRIVATE_KEY="" +export SEQUENCER_PRIVATE_KEY="" +export BATCH_SUBMITTER_PRIVATE_KEY="" +export L2_GAS_ORACLE_PRIVATE_KEY="" diff --git a/ops/native-hoodi/notes/budget.md b/ops/native-hoodi/notes/budget.md new file mode 100644 index 000000000..13f57b9b8 --- /dev/null +++ b/ops/native-hoodi/notes/budget.md @@ -0,0 +1,38 @@ +# 资金预算(P2-5 的结果) + +依据:在 Hoodi 的 anvil 分叉上把 `scripts/deploy-l1.sh` 完整干跑了一遍(`run/dryrun-1/`),**所有步骤成功**。分叉里的交易不花公共 Hoodi 的任何币。 + +## 实测 + +| 项 | 数值 | +|---|---| +| deployer 发出的交易数 | **77** | +| 总 gas | **51,304,680**(最大的一笔 4,780,806,远低于区块 gas 上限 6000 万) | +| submitter 质押(由 deployer 代付) | 0.01 ETH(配置里调低过,默认是 1 ETH) | +| 干跑时 deployer 实际花费 | 0.0179 ETH(= 约 0.0079 ETH gas + 0.01 ETH 质押),对应分叉里约 0.15 gwei 的 gas 价格 | +| 耗时 | 部署约 2 分钟,初始化约 2 分钟,总共约 4 分钟(分叉里无需等待确认) | + +## 按不同 gas 价格换算 deployer 的需求 + +(51,304,680 gas × 价格 + 0.01 ETH 质押) + +| Hoodi gas 价格 | deployer 需要 | +|---|---| +| 0.15 gwei | 约 0.018 ETH | +| 0.5 gwei | 约 0.036 ETH | +| 1 gwei(我 09:19 测到的 1.08 gwei) | 约 0.061 ETH | +| 2 gwei | 约 0.113 ETH | +| 5 gwei | 约 0.267 ETH | + +**建议 deployer 备 0.2 ETH**(覆盖 gas 涨到约 3 gwei,并留余量)。真正部署前再查一次当时的 gas 价格。 + +## submitter + +- 这次**没有实测**:干跑里 submitter 没发交易(批次提交要等 L2 跑起来)。 +- 它每个批次要发一笔 blob 交易。blob 费用本身很低(Hoodi 当时 blob base fee 约 0.05 gwei),主要成本是执行 gas。 +- 批次间隔由配置决定(`govBatchBlockInterval=200` 个块 / `govBatchTimeout=600` 秒),大致每 10 分钟一个批次(L2 有交易时更快)。 +- **估算(未实测):** 先备 **0.1 ETH**,P6 跑起来后按实际消耗再调;`TX_SUBMITTER_TX_FEE_LIMIT` 要调低。 + +## 结论 + +**所需的测试币比我最初担心的少很多:合计约 0.3 ETH 量级就够。** 水龙头单次通常能领到这个数量级,所以 R2(领不到足够测试币)的风险下降,但领币本身还没有验证过。 diff --git a/ops/native-hoodi/notes/config-audit.md b/ops/native-hoodi/notes/config-audit.md new file mode 100644 index 000000000..a0c12cf6b --- /dev/null +++ b/ops/native-hoodi/notes/config-audit.md @@ -0,0 +1,43 @@ +# 配置审计(P3-4 ~ P3-7) + +结论先行:**Hoodi 上不需要给任何 staking 地址或 BLOCK_SIGNER 打币;但 deployer 要多备一笔 submitter 的质押。** + +## 1. 配置里的密钥与地址 + +| 配置项 | 性质 | 在哪里用 | Hoodi 上怎么办 | +|---|---|---|---| +| `BLOCK_SIGNER_PRIVATE_KEY` | **Anvil 公开私钥** | 只在 `ops/devnet-morph/devnet/__init__.py:190`,用来在 devnet 的 L1 上给 `l2StakingAddresses` 打 10 ETH;Go 创世工具**完全不读它** | 删除 | +| `BLOCK_SIGNER_ADDRESS` | 地址 | 代码里没有任何读取 | 保留字段,换成 sequencer 地址,无实际作用 | +| `l2StakingAddresses / Pks / TmKeys / BlsKeys` | 地址与**公钥** | 只进入 **L2 创世**(`immutables.go`,L2Staking 合约的序列器集合);从不在 L1 发交易 | 沿用;**不需要在 Hoodi 上给它们打币** | +| `finalSystemOwner / proxyAdminOwner / gasPriceOracleOwner / recordOracleAddress / morphTokenOwner` | L2 合约的 owner | L2 创世 | 全部换成 deployer 地址 | +| `l1FeeVaultRecipient / sequencerFeeVaultRecipient / l2BridgeFeeVaultRecipient` | 费用接收地址 | L2 创世 | 换成 deployer 地址 | + +## 2. `l1StartingBlockTag`(P3-5) + +- 格式:geth 的 `rpc.BlockNumberOrHash`,可以是 `"earliest"` / `"latest"` 等标签、十六进制块号字符串(如 `"0x3da3eb"`),或 `{"blockHash": ...}`。 +- 创世工具(`cmd/genesis/cmd.go`)用 `BlockByNumber` / `BlockByHash` 取这个 L1 区块,取其**哈希、高度、时间戳**写进 `rollup.json`(`L2Time = l1StartBlock.Time()`)。 +- 默认 `earliest` = Hoodi 第 0 块,会让 rollup.json 的 L1 起点是 2025 年 3 月的创世块。 +- **取值方式:** 部署第一笔交易之前,取当时 Hoodi 的最新块号(十六进制),写进配置后再跑创世工具。 +- 当前文件里放的是**故意无法解析**的占位符 `REPLACE_WITH_HOODI_START_BLOCK_HEX`,忘记替换会立刻报错,而不会静默用错值。 +- 节点的 `MORPH_NODE_SYNC_START_HEIGHT` 也用这个块号。 + +## 3. main.py 运行时注入的字段(我们的 driver 要自己处理) + +| main.py 写入的字段 | 实际是否有效 | 我们怎么做 | +|---|---|---| +| `l1GenesisBlockTimestamp` | **无效**。`DeployConfig` 结构里没有这个字段,会被忽略 | 不写 | +| `l1StartingBlockTag = earliest` | 有效,但不适合 Hoodi | 部署时替换为起始块号 | +| `l1StakingProxy = 0x...dEaD` | **必需**。为 0 时 `config.go` 先去找已部署的 L1Staking,找不到就报错;L1Staking 已退役 | 直接写进 `hoodidev-deploy-config.json`(已写) | + +## 4. `register` 与质押(P3-6) + +- `hardhat register`(`contracts/deploy/021-SubmitterRegister.ts`):owner 先 `addSubmitter(submitter)`,再调用 `stake(submitter, {value: minimumStake - currentStake})`。 +- **质押的钱由 owner(deployer)付**,不是 submitter。 +- 配置里 `submitterMinimumStake`、`submitterChallengeDeposit` 默认都是 **1 ETH**。合约只要求它们大于 0。 +- 我们改成 **0.01 ETH**(`hoodidev.ts` 里),所以 deployer 额外只需要约 0.01 ETH 的质押。 +- 这个小数值能否被 `parseEther` 之类的换算正确处理,会在 anvil 分叉干跑时实测。 + +## 5. `hardhat fund`(P3-7) + +- 会给每个 `batchSubmitterPks` 里的账户转 **100 ETH**(余额低于约 10 ETH 时)。Hoodi 上不可行。 +- **driver 不调用它。** 需要时手动向 submitter 转小额(额度由 P2-5 的干跑确定)。 diff --git a/ops/native-hoodi/notes/hoodi-probe-raw.txt b/ops/native-hoodi/notes/hoodi-probe-raw.txt new file mode 100644 index 000000000..541939615 --- /dev/null +++ b/ops/native-hoodi/notes/hoodi-probe-raw.txt @@ -0,0 +1,19 @@ +== 并发 20 × 3 轮 +EL https://0xrpc.io/hoodi 200x60 avg=0.92s max=1.25s n=60 +EL https://rpc.hoodi.ethpandaops.io 200x60 avg=0.39s max=0.63s n=60 +BEACON https://beacon.hoodi.ethpandaops.io 200x60 avg=0.46s max=0.71s n=60 +BEACON https://ethereum-hoodi-beacon-api.publicnode.com 200x60 avg=0.06s max=0.19s n=60 + +== eth_getLogs:区间上限(Morph 的 L1 同步会用) + https://0xrpc.io/hoodi span=1000 ok + https://0xrpc.io/hoodi span=5000 ok + https://0xrpc.io/hoodi span=10000 Request contains invalid block params + https://0xrpc.io/hoodi span=50000 Request contains invalid block params + https://rpc.hoodi.ethpandaops.io span=1000 ok + https://rpc.hoodi.ethpandaops.io span=5000 ok + https://rpc.hoodi.ethpandaops.io span=10000 ok + https://rpc.hoodi.ethpandaops.io span=50000 getLogs request exceeded max allowed range + +== 信标:近期 slot 的 blob_sidecars 连续取 5 个 + https://beacon.hoodi.ethpandaops.io head_slot=4398552 ok=4 fail=1 + https://ethereum-hoodi-beacon-api.publicnode.com head_slot=4398552 ok=4 fail=1 diff --git a/ops/native-hoodi/notes/hoodi-probe.md b/ops/native-hoodi/notes/hoodi-probe.md new file mode 100644 index 000000000..07e1f797c --- /dev/null +++ b/ops/native-hoodi/notes/hoodi-probe.md @@ -0,0 +1,32 @@ +# Hoodi 公共端点探测结果(P2-1、P2-2) + +探测时间:2026-11-18。脚本:`scripts/probe-hoodi.sh`(并发 20 × 3 轮,只读,对公共服务只做小规模并发)。原始输出:`notes/hoodi-probe-raw.txt`。 + +## 限流 + +| 端点 | 类型 | 60 个请求的结果 | 平均延迟 | +|---|---|---|---| +| `https://0xrpc.io/hoodi` | EL | 全部 200 | 0.92 秒 | +| `https://rpc.hoodi.ethpandaops.io` | EL | 全部 200 | 0.39 秒 | +| `https://beacon.hoodi.ethpandaops.io` | 信标 | 全部 200 | 0.46 秒 | +| `https://ethereum-hoodi-beacon-api.publicnode.com` | 信标 | 全部 200 | 0.06 秒 | + +**这个并发量下没有任何限流。** 更高并发或长时间持续的上限没有测。 + +## eth_getLogs 区间上限 + +| 端点 | 1000 | 5000 | 10000 | 50000 | +|---|---|---|---|---| +| 0xrpc.io | ok | ok | 报 `invalid block params` | 报 `invalid block params` | +| ethpandaops | ok | ok | ok | 报 `exceeded max allowed range` | + +**Morph 的 L1 同步每次只拉 100 个块**(`node/sync/config.go` 的 `DefaultFetchBlockRange = 100`),远低于两者的上限,不受影响。 + +## 信标 blob_sidecars + +两个信标端点对近期 slot 都能返回 sidecar。第一次连取 5 个 slot 时各有 1 个失败,第二次复查 5 个全部成功,推测是某个 slot 没有区块或没有 blob,属偶发。对 Morph 的影响:取 blob 失败会按序回退到下一个端点,见 `node/derivation/beacon.go`。 + +## 结论 + +- EL 主用 **ethpandaops**(延迟低、getLogs 上限高);0xrpc.io 作备用。**这与最初计划里"主用 0xrpc.io"相反**,`env/hoodi.env.example` 与 `env/secrets.env` 同步调整。 +- 信标 morphnode 配两个(ethpandaops 在前、publicnode 在后);gas-oracle 只能配一个。 diff --git a/ops/native-hoodi/notes/issues.md b/ops/native-hoodi/notes/issues.md new file mode 100644 index 000000000..b36cbb980 --- /dev/null +++ b/ops/native-hoodi/notes/issues.md @@ -0,0 +1,248 @@ +# 问题与处理记录 + +按时间顺序,每条记录:现象 → 原因 → 处理 → 对计划的影响。 + +--- + +## 2026-11-18 + +### I-001 morph-geth 按计划里的命令编译失败 — 已解决 + +- **现象:** `cd repos/morph/go-ethereum && go run build/ci.go install ./cmd/geth` 报 + `build/ci.go:63:2: use of internal package github.com/morph-l2/go-ethereum/internal/build not allowed` +- **原因:** `go-ethereum` 目录位于 Morph 仓库内,仓库根有 `go.work`,但 `go.work` 没把 `./go-ethereum` 列进去。Go 于是把 `github.com/morph-l2/go-ethereum` 当成**下载的外部依赖**,而不是本地目录,`internal` 包就不允许访问。Docker 版没这个问题,是因为它把 `go-ethereum` 单独拷到 `/go-ethereum`,上面没有 `go.work`。 +- **处理:** 加 `GOWORK=off`。Morph 自己顶层 Makefile 的 `geth` 目标也是这么写的(`env GO111MODULE=on GOWORK=off go run build/ci.go install ./cmd/geth`)。我当初是从 Dockerfile 抄的命令,漏了这一点。 +- **结果:** 编译成功,23 秒;`geth version` 显示 `Version: 2.2.8-mainnet`,与子模块 tag `morph-v2.2.8` 一致。 +- **对计划的影响:** TODO P1-2 的命令已改。 + +### I-002 morphnode 不支持 `--version` + +- **现象:** `morphnode --version` 报 `flag provided but not defined: -version`。 +- **处理:** 版本用 `morphnode --help` 确认可运行,用 `tendermint version`(0.37.0-alpha.1)确认 tendermint。tx-submitter 支持 `--version`,输出 `v1.0.0-2.2.8-mainnet-ae987b15-...`。 +- **对计划的影响:** 无。P1 的验收标准里"能打印版本"对 morphnode 改为"`--help` 正常输出"。 + +### I-003 tx-submitter 的版本串带 `mainnet` + +- **现象:** `tx-submitter version v1.0.0-2.2.8-mainnet-ae987b15-...`;morph-geth 也是 `2.2.8-mainnet`。 +- **说明:** 这只是构建标签,不是说它们要连主网。运行时的链由配置和 genesis 决定(`TX_SUBMITTER_BUILD_ENV=dev`、`--networkid=53077`)。记录在此,避免以后看到 `mainnet` 字样产生误会。 + +### I-004 gas-oracle 启动即 panic:日志目录无写权限 — 已找到处理方式 + +- **现象:** 直接运行 `bin/gas-oracle/app`,在 `src/main.rs:58` panic,`OutputIo(PermissionDenied)`。 +- **原因:** 日志目录默认是 `/data/logs/morph-gas-price-oracle`(`main.rs` 的 `setup_logging`)。Docker 里以 root 运行,这个路径可写;本机没有 root,`/data` 不可写。 +- **处理:** 设置环境变量 `GAS_ORACLE_LOG_DIR` 指向可写目录(计划用 `run/logs/gas-oracle/`)。设置后程序正常启动,打印 `Starting update gas oracle...`,随后因缺少 `L2_GAS_ORACLE_PRIVATE_KEY` 而 panic,这是预期行为。 +- **对计划的影响:** P6-3 的 gas-oracle 环境变量清单要加上 `GAS_ORACLE_LOG_DIR`。 + +### I-005 gas-oracle 的信标地址只支持单个 — 已确认 + +- **现象/依据:** `gas_price_oracle.rs:36` 里 `l1_beacon_rpc: String`;`da_scalar/blob_client.rs` 里把它当 URL 前缀直接拼接 `/eth/v1/beacon/blob_sidecars/`,没有任何逗号拆分或回退。 +- **结论:** `GAS_ORACLE_L1_BEACON_RPC` **不能**配逗号分隔的多个端点,只能配一个。这与 morphnode(支持多个、按序回退)不同。 +- **处理:** gas-oracle 用 `https://beacon.hoodi.ethpandaops.io`;morphnode 配两个。 +- **对计划的影响:** 这就是 TODO P6-3 里"待确认"的那一项,现已确认,`env/hoodi.env.example` 的注释同步修正。 + +### I-006 合约工具链在 Node 24 上可用 — 风险 R8 解除 + +- **结果:** `yarn hardhat compile` 与完整的 `yarn build` 都在 Node v24.19.0 上通过。 +- **对计划的影响:** TODO P1-6 里"若失败则装 Node 18/20"的备选不再需要。PLAN 风险 R8 可关闭。 + +### I-007 node-1 不运行 tendermint,只有 node-0 运行 — 简化了 P5 + +- **依据:** `ops/devnet-morph/devnet/setup_nodes.py` 的注释:"node-1 runs with `MORPH_NODE_DERIVATION_VERIFY_MODE=layer1` and never starts tendermint; node-2 has no compose service at all"。`TENDERMINT_PEERS = ("node0", "ha-node0", "ha-node1", "ha-node2")`,不含 node1。 +- **结论:** 单序列器模式下,只有 node-0 是 tendermint 节点;node-1 完全靠 L1 的批次和 blob 还原区块。因此 PBFT 对端的 `persistent_peers` 在这个模式下基本用不上。 +- **对计划的影响:** PLAN 第 6 节端口表里 node-1 去掉 tendermint 端口;TODO P5-1 缩小范围。这也意味着 **node-1 能否与 node-0 一致,完全取决于信标链 blob 是否取得到**,P7-2 因此更关键。 + +### I-008 setup_nodes.py 只用标准库 — P1-8 通过 + +- **结果:** 依赖只有 `base64 hashlib json os re shutil subprocess sys`,Python 3.12.3 可直接运行,无需 `pip install`。 +- **注意:** 脚本开头会检查 PATH 里有没有 `tendermint`,没有就调用 `make install-tendermint`。我们的 driver 复制其逻辑时,要直接用 `bin/morphnode/tendermint` 的全路径,不依赖 PATH。 + +### I-009 git 提交被 GPG 签名拦下 — 改为暂存区加补丁 + +- **现象:** `git commit` 报 `gpg failed to sign the data ... Operation cancelled`。 +- **原因:** 该仓库的 git 配置强制提交签名,而当前环境没有可交互的 GPG 签名。 +- **处理:** 我**没有**为了提交去关闭签名(那是你的签名策略)。三个改动文件保留在 **git 暂存区**,并导出补丁到 `patches/0001-hoodidev-config.patch`(166 行)。 +- **核对:** 补丁里没有出现我们的任何私钥;公开 Anvil 私钥只出现一次,在 `hardhat.config.ts` 的"禁止使用"判断常量里。 +- **需要你做:** 如果要在 `native-hoodi` 分支上留下提交,请你自己提交一次(能走你的签名),或告诉我允许对这个分支临时不签名。 + +### I-010 原计划里 P3 的几个"待确认"现已全部确认 + +见 `notes/config-audit.md`。最重要的两条:`BLOCK_SIGNER_PRIVATE_KEY` 只用于 devnet 给 staking 地址打币,Hoodi 上直接删除;`register` 的质押由 deployer 代付,已把额度从 1 ETH 降到 0.01 ETH。 + +### I-011 干跑脚本里 `printf '%x'` 对 1e20 溢出 — 已修 + +- **现象:** `printf: warning: 100000000000000000000: Numerical result out of range`,给分叉里的账户设置的余额被截成 2^64-1(约 18.4 ETH)。 +- **原因:** bash 的 `printf` 只处理 64 位整数。 +- **处理:** 改用 `cast to-hex`。对这次干跑没有影响(18.4 ETH 足够),只是余额不是原本想设的 100 ETH。 + +### I-012 分叉里的 gas 价格比我实测的低很多 + +- **现象:** 我 09:19 直接问 Hoodi 得到 `eth_gasPrice ≈ 1.08 gwei`,而干跑里 deployer 的实际 gas 开销折算出约 0.15 gwei。 +- **原因(推测,未验证):** anvil 分叉按分叉点的区块 base fee 起算,而 Hoodi 的 gas 价格本身会波动。 +- **处理:** 预算按总 gas(这个才是确定的)乘以多档价格,见 `notes/budget.md`。正式部署前再查一次实时价格。 + +### I-013 干跑后分叉被关闭,无法对链上状态做抽样核对 + +- **说明:** `dryrun-fork.sh` 结束时会停掉自己启动的 anvil,所以干跑后没法再 `cast call` 检查 Rollup / L1Sequencer 的状态(TODO P4-11)。 +- **已有的保证:** 每一步都成功退出;`s11_verify_deploy` 检查了所有部署的合约都有代码;`s32` 检查了 L1Sequencer 的 owner 等于 deployer。 +- **建议:** 正式部署后再做 P4-11 的抽样核对;或者另起一个**保持运行**的分叉,在上面继续做 P5~P7 的彩排(见下)。 + +### I-014 `tendermint testnet --n` 是**非验证者**数量,不是总数 — 已修 + +- **现象:** `tendermint testnet --v 1 --n 2 --hostname ... --hostname ...` 报 `testnet needs precisely 3 hostnames (number of validators plus non-validators)`。 +- **原因:** 主机名个数 = `--v` + `--n`。上游用 `--v 1 --n 5` 配 6 个主机名,我误把 `--n` 当成总数。 +- **处理:** 改成 `--v 1 --n 1`(1 个验证者 node0 + 1 个非验证者 node1)。 +- **验证:** 用干跑留下的创世文件在 `run/nodes-test/` 里跑通 `scripts/setup-nodes.py`:两个 geth 初始化出的创世块哈希 `be3cbc..5540f9` 与干跑 `rollup.json` 里的 L2 创世哈希一致;node0 配置里 rpc/p2p/abci 为 26657/26656/26658,prometheus 为 26660,`block_sync=true`、`pex=false`、`persistent_peers=""`;node1 没有验证者密钥;创世里的验证者公钥与 node0 的 `priv_validator_key` 匹配。 +- **注意:** `run/nodes-test/` 只是测试产物(用的是干跑的 L1 起点),**不能**用于正式运行;正式运行时用 `--run-dir run/l2`,并传入真实部署产出的 `genesis-l2.json`。 + +### I-015 三个进程的 metrics 端口默认值会互相冲突 — 已在 morph-native.sh 里分开 + +| 进程 | 默认 | 冲突对象 | 处理 | +|---|---|---|---| +| gas-oracle | `GAS_ORACLE_METRIC_ADDRESS` 默认 `0.0.0.0:6060` | morph-el-0 的 metrics 6060 | 设为 `127.0.0.1:6070` | +| morphnode(node-1,layer1 校验模式) | `MORPH_NODE_METRICS_PORT` 默认 26660 | node-0 的 tendermint prometheus 26660 | 设 `MORPH_NODE_METRICS_SERVER_ENABLE=true`、`MORPH_NODE_METRICS_PORT=27660` | +| tx-submitter | metrics 默认关闭(compose 里也没开) | — | 启用并设 `TX_SUBMITTER_METRICS_PORT=8060`,方便观测 | + +### I-016 `scripts/morph-native.sh` 已写好并做了无副作用测试 + +- **已测:** 语法、无参数用法、`status`(无进程时)、部署前 `up` 会拒绝、未知进程名、从干跑的部署文件里读合约地址。 +- **未测:** 真正启动进程。原因:本机上另一个 devnet 还占着 8545 和 8551(`status` 里 `el-0 :8545` 读到的是别的链的高度,恰好证实了这个冲突)。要等它停掉,且 L1 部署完成后才能端到端验证。 + +### I-017 deployer 换成用户自带的账户 + +- **背景:** 用户提供了自己的 deployer 私钥(不记录),在 Hoodi 上有 36 ETH。 +- **提醒过:** 私钥最好不要经过对话。用户仍通过对话给出了私钥,所以该私钥已出现在对话记录里。它是测试网账户;**建议今后把它当作"已暴露"**,不要用它持有真实资产,也不要在主网复用。 +- **处理:** 写入权限 600 的 `env/secrets.env`;核对推导出的地址与所给地址一致;把 `hoodidev.ts`(4 处)和 `hoodidev-deploy-config.json`(8 处)里的旧 deployer 地址全部换成新地址,重新暂存并导出补丁。补丁里 0 处私钥。 +- **影响:** 所有合约的 owner 都是用户的这个账户。旧的生成账户 `0x0129…1A2c` 从未收到过币,作废。 +- **从 deployer 向 submitter 转 1 ETH** 作为批次提交的运行资金(`SUBMITTER_FUND_ETH=1`)。 + +### I-018 真实部署第一次失败:公共 RPC 上"刚上链就读不到" — 已加固,重跑 + +- **现象:** 在真实 Hoodi 上部署的第 1 个合约(ProxyAdmin)已经上链(交易 `0xbbcab7c1…`),但紧接着的 `owner()` 调用返回空数据(`CALL_EXCEPTION, data="0x"`),部署脚本退出。anvil 分叉上同一套脚本完全正常。 +- **验证:** 失败后立刻再查,这个合约有代码(2059 字节)、`owner()` 就是 deployer —— 合约本身没问题,是读请求早了一步。 +- **原因(部分验证):** 部署代码对每个合约都是 `await contract.deployed()` 后立刻 `assertContractVariable(...)` 读状态。公共 RPC 背后是多个节点,确认上链的节点和接着处理读请求的节点可能不同。我探测到 `0xrpc.io` 的区块高度会在相邻两个值之间跳动(符合这个模型);ethpandaops 在我的 30 次快速探测里很稳,所以**这个机制是推断,不是对失败那一次的直接证明**。 +- **处理:** 在 `contracts/src/deploy-utils.ts` 给两个断言函数(共 51 处调用)加**默认关闭**的重试:`MORPH_READ_RETRIES`(默认 0=原样)、`MORPH_READ_RETRY_DELAY_MS`(默认 2000)。`deploy-l1.sh` 默认设为 15 次、每次 2 秒。读不到或值不匹配都会重试,最后一次的结果原样抛出,断言报的仍是真实问题。 +- **副作用:** 失败的那次留下了一个孤儿合约 `0x2637…EEF45`(ProxyAdmin),deployer nonce 为 1。重跑会重新部署一套,孤儿合约不用管,花费只有几美分级别的测试币。 +- **局限:** 只覆盖断言函数里的读。`register` 步骤里还有几处别的读(如 `registered()`),如果在那里再遇到同类问题,需要同样处理。 + +### I-019 第二次真实部署失败 + 改用请求层的一致性代理 — 已重跑 + +- **现象:** 加了断言重试后再跑,失败点换到 `deploy/013-DeployProxys.ts:27/227` 的 `console.log(await IProxyContract.admin())`(一个调试打印)。这次已经部署了 9 笔交易(到 `Proxy__L1GatewayRouter`)。同一个根因的第二个读点;后面的 `register` 等步骤还有更多读点,逐个补不是办法。 +- **处理:** 写了 `scripts/rpc-consistency-proxy.js`(约 100 行,无依赖),放在 hardhat / 创世工具 / cast 与公共 RPC 之间: + 1. 记住"已经见过的最高区块"(来自收据和 `eth_blockNumber`),叫 floor; + 2. 把所有对 `latest`/`pending` 的状态读改写成 floor 这个具体块号; + 3. 上游还没同步到时,等待并重试(500 毫秒一次,最多 30 秒); + 4. 写交易、显式指定块号的请求、其余方法原样透传。 +- **一个必须验证才发现的细节:** 这个上游对"还没同步到的块"**不报错,而是返回 `result: null`**(`eth_call`、`getBalance`、`getCode`、`getTransactionCount`、`getStorageAt`、`getBlockByNumber` 都是;只有 `eth_estimateGas` 报 `header not found`)。我的第一版只认错误文字,等于没修。已改成:对被改写过的读,`null` 结果也视为"还没同步到"。 +- **验证:** (1) 透传、改写、`eth_blockNumber` 单调递增、批量请求都正常;(2) 用测试钩子让代理以为自己见过 head+2:`owner()` 被拦住 17 秒(21 次重试)后返回正确的 deployer 地址,之后的读 276 毫秒;(3) 显式块号的请求立即返回,不受影响。 +- **接入:** `deploy-l1.sh` 对 `https://` 的 RPC 默认启用(`USE_CONSISTENCY_PROXY=auto`),对本地 anvil 不启用;退出时自动停掉代理。 +- **局限:** 这是针对我们实测到的行为(`null`/`header not found`)写的。换一个上游,其"未同步"的表现可能不同;代理只保证单调的读,不保证在重组(reorg)时的正确性,对 devnet 部署够用。 +- **残留:** 前两次失败留下约 10 笔孤儿交易(几个孤儿合约),deployer 余额 35.99 ETH,影响可以忽略。 + +### I-020 第三次真实部署失败:上游返回 `rate-limit exceeded` — 代理加了退避与备用端点 + +- **现象:** 经一致性代理后部署推进了约 100 秒,在 `eth_call`(`admin()`)上收到 `ProviderError: rate-limit exceeded`,被 ethers 当作 `CALL_EXCEPTION` 抛出,部署退出。代理日志里没有一次读重试,说明这次不是读不一致,而是限流。 +- **排查:** 单独用 `curl` 连续发请求:`eth_blockNumber`、`eth_call`、`eth_estimateGas`、`eth_getTransactionCount`、`eth_getTransactionReceipt`、`eth_getBlockByNumber` 各 150 个,加上另两个端点各 150 个 `eth_blockNumber`,**全部没有被限流**。所以限流不是按"持续请求数"或"某个方法"稳定触发的,更像是公共服务的**瞬时限流**(共享额度)。这是推断,没有对那一次的直接证明。 +- **处理:** 代理新增: + 1. 限流(HTTP 429/503,或错误信息含 rate limit / too many requests / quota / exceeded)与网络错误时,**立刻切换到下一个上游**;所有上游都拒绝时,按 0.5→1→2→4→8 秒指数退避,最多 8 轮; + 2. 支持备用上游(逗号分隔);`deploy-l1.sh` 默认备用 `0xrpc.io` 和 `publicnode`; + 3. `/stats` 里按方法统计请求数、限流次数、故障切换次数,方便以后看流量构成。 +- **验证(用本地假上游):** (A) 主上游一直限流、备用是真实 Hoodi:332 毫秒内完成故障切换,返回正确的链 ID 和余额;(B) 单上游前 3 次限流后恢复:退避 0.5+1+2 秒,总耗时 3568 毫秒后成功。 +- **风险:** 多个上游的区块头可能略有先后。读请求已经被 floor 钉在具体块号上,落后的节点会返回 null 并被重试,所以这个风险被覆盖;发送交易可能去到任意一个上游,收据则由客户端轮询,最终一致。 +- **残留:** 三次失败共留下约 20 笔孤儿交易;deployer 余额 35.98 ETH,约花了 0.017 ETH。 + +### I-021 第四次真实部署卡死在 `initialize`:一致性代理的 floor 冻结 — 代理的 bug,已修 + +- **现象:** `s10_deploy`(部署)一次通过,`s11`、`s20`(创世)、`s21` 也通过,随后 `s30_initialize` 在 "Upgrading the L1CrossDomainMessenger proxy..." 上卡了 18 分钟以上。进程几乎不占 CPU;代理统计里 `rateLimited=0`、`retries=0`、`eth_sendRawTransaction` 停在 38,而 `eth_call` 和 `eth_chainId` 在缓慢增加。 +- **根因(已通过自测复现):** `deploy/015-MessengerInit.ts` 的写法是:发送 `upgradeToAndCall` 交易但**不等收据**,然后每 3 秒轮询 `implementation()` 等它变成新地址。我的代理把对 `latest` 的读钉在 floor 上,而 floor 只有在客户端调用 `eth_blockNumber` 或取到收据时才更新——这里两样都没有,floor 冻结在升级交易**之前**的区块,轮询永远读到旧状态。**这是我写的代理的 bug,不是 RPC 或链的问题。** +- **修复:** + 1. 每次处理被改写的读之前,最多每秒向上游问一次最新高度并更新 floor(`PROXY_HEAD_REFRESH_MS`,默认 1000); + 2. `pending` 的 nonce 单独处理:取"上游 pending"、"floor 区块的计数"、"代理自己记录的已发送交易下一个 nonce"三者的最大值,避免漏掉已发出但未打包的交易导致 nonce 重用; + 3. 新增可选节流 `PROXY_MIN_INTERVAL_MS`(默认 0=关),对应"限流时在请求之间加 sleep"的需求。 +- **验证:** `scripts/rpc-consistency-proxy.selftest.js` 用一条每秒出块的假链复现了这个 bug:关闭刷新后轮询 12 秒仍读到旧值(FAIL);开启后在链越过变化块后 3 秒读到新值。四项全部通过(floor 跟随链、pending nonce、latest nonce 不被污染、显式块号透传)。 +- **关于加 sleep:** 第四次运行里代理统计显示 `rateLimited=0`、`failovers=0`,**没有触发限流**,所以这次不需要在合约部署之间加 sleep。如果以后触发限流,打开 `PROXY_MIN_INTERVAL_MS`(例如 300)即可,不用改部署代码。 +- **善后:** 卡住的那次运行目录保留在 `run/l1-attempt4-stuck/`。它已部署的合约和升级交易留在链上成为孤儿合约;因为 `initialize` 会重新部署实现合约、创世文件又嵌入了合约地址,不能原地续跑,所以整套重来。 +- **另一个观察:** deployer 余额在此期间从 35.98 ETH 变成 68.93 ETH(不是我转的),看起来有人又转了币进来。 + +### I-022 `cast send` 不读 `ETH_PRIVATE_KEY`,且步骤运行器吞错误 — `setFirstSequencer` 一度没发出去,已修并核对 + +- **现象:** `s33_fund_submitter` 报 `Error accessing local wallet`;追查发现 `s32_first_sequencer` 其实**同样失败**,却在 0 秒内被标成 "ok"。链上 `getSequencer()` 仍是 `no sequencer configured`。 +- **根因 1:** 这个 cast 版本(Foundry 1.9.0)的 `cast send` 不会读 `ETH_PRIVATE_KEY` 环境变量(之前我只在 `cast wallet address` 上测过,并错误地把结论推广到 `cast send`)。 +- **根因 2:** `step()` 里 `if ! "${fn}" ...` 调用步骤函数。bash 在 `if` 条件上下文里**会关闭 `set -e`**,所以函数中间的命令失败不会中止,只有最后一条命令的状态决定结果;`s32` 的最后一条是 `echo`,于是"成功"。 +- **修复:** (1) 新增 `scripts/send-tx.js`,用 ethers 发送交易,私钥只经环境变量 `KEY` 传入,不出现在命令行;(2) `step()` 改为 `set +e; ( set -e; fn ) ...; rc=$?; set -e`,让 errexit 在步骤内真正生效;(3) `s32`、`s33` 在步骤内**读回链上结果**再判成功。 +- **教训:** 不能只看退出码。hardhat 任务出错时常常只打印一行然后 `return`,退出码仍是 0。所以新增 `scripts/verify-l1.sh`,完全不看步骤退出码,直接读链上状态与预期比对。 +- **结果:** 修复后续跑,`s32`、`s33`、`s40` 全部成功;`verify-l1.sh` **53 项通过、0 失败**(Rollup/Messenger/MessageQueue/Submitter/L1Sequencer 的 owner 与互相引用、Rollup 的 L2 链 ID 与创世批次、submitter 登记与质押、所有 21 个代理的 implementation 与 admin、第一个序列器)。 +- **善后:** 错误的 `s32` 标记保留为 `run/l1/state/s32_first_sequencer.done.WRONG-nothing-was-sent`。 + +### I-023 deployer 余额又增加了约 32 ETH + +- 部署期间 deployer 余额从 68.93 ETH 变成 100.87 ETH(`deploy-l1.sh` 的 summary 里"spent"显示为负数,是因为用的是第一次尝试前记录的余额)。不是我转的,应该是你又转了币。仅记录。 + +### I-024 6060 端口被 Coder 工作区代理占用 — morph-geth 的 metrics 改到 6160/6161 + +- **现象:** 检查 Morph 要用的端口时,6060 被工作区自身的 agent 占用,不能动。所以 geth 的 metrics 端口改用 6160 起。 +- **处理:** `morph-native.sh` 里 morph-geth 的 metrics 端口从 6060/6061 改为 6160/6161;PLAN 第 6 节端口表同步修改。 +- **提醒:** 这也是 geth 的默认 metrics 端口,以后在这台机器上起 geth 类进程都要避开 6060。 + +### I-025 oracle 密钥没有权限更新 GasPriceOracle — 上游 devnet 里 owner 与 oracle 是同一个账户,我们拆开了 + +- **现象(启动 oracle 前发现):** L2 创世里 `gasPriceOracleOwner` 是用户的 deployer,而 oracle 进程用我另外生成的 `L2_GAS_ORACLE_PRIVATE_KEY`。链上读到 `GasPriceOracle.owner()` 是 deployer,oracle 密钥 `isAllowed=false`、L2 余额为 0。所有更新函数(`setL1BaseFee…`)是 `onlyAllowed`(owner 或白名单)。 +- **原因:** 上游 devnet 里 `gasPriceOracleOwner` 和 `L2_GAS_ORACLE_PRIVATE_KEY` 是同一个 Anvil #0 账户,所以没人注意到这个耦合。 +- **处理:** `scripts/l2-bootstrap.sh`:用 L2 创世里预置了余额的开发账户(公开的 Anvil #0 密钥,仅在这个只监听 127.0.0.1 的本机私有 L2 上使用)给 deployer 转 100 ETH、给 oracle 转 10 ETH,再由 deployer 调 `setAllowList([oracle],[true])`,读回 `isAllowed=true`。 +- **结果:** oracle 随后第一次更新就成功(L2 交易 `0x7fa3…`)。 + +### I-026 node-1 对 L1 的扫描节奏只有每 15 秒 1~2 个块 + +- **现象:** node-1(layer1 校验模式)的日志里,每 15 秒拉取一次 L1 的 1~2 个区块(`derivation start pull rollupData form l1 startBlock=… end=…`)。Hoodi 每 12 秒一个块,即约 1.25 块/15 秒,而它每轮处理 1~2 块,追赶余量很小。 +- **影响:** 批次在 L1 区块 4043361,node-1 在 4043352,约 2 分钟后才追上并还原出区块。不影响正确性,但**还原延迟随 L1 出块时间和这个轮询节奏而定**,不是实时的。 +- **未做:** 没有去调轮询间隔或范围参数(未确认对应的 flag)。如果需要更低的还原延迟,这里是调优点。 + +### I-027 第一次 L1→L2 存款失败:L1 消息已被打包,但在 L2 上执行失败(状态 0) + +- **现象:** `scripts/deposit-test.sh` 第一次运行:L1 存款交易在 Hoodi 区块 4043381 成功(状态 1,gas 241464),消息入队(`L1MessageQueue.nextCrossDomainMessageIndex = 1`)。但 L2 上全新接收地址 `0x50d3…831b` 的余额 10 分钟内始终为 0,脚本超时失败。 +- **排查过程:** + 1. node-0 日志里只有 2 条 `failed to fetch L1 messages … block range extends beyond current head block`(见 I-026 之后加固代理的那一项),看起来像是读取问题; + 2. 但 node-0 的指标 `morphnode_syncer_message_count = 1`、`morphnode_executor_next_l1_message_queue_index = 1` 说明消息**已经被读到并被打进了区块**; + 3. 扫描 L2 全部区块,找到唯一一笔类型 `0x7e`(L1 消息)的交易,在 **L2 区块 342**:`to` 是 L2CrossDomainMessenger(`0x5300…0007`),`gas` 110000,**回执状态 0**,`gasUsed` 108798,0 条日志,调用的是 `relayMessage`。 +- **结论(推断,待第二次存款验证):** 我沿用了仓库示例任务 `deposit-l1-eth` 里的 `_gasLimit = 110000`,在这套合约上 `relayMessage` 的整个调用链把 gas 用到 98.9% 就失败了,基本是 **gas 不足**。**不是 L1 消息没送到,也不是 L2 没打包。** +- **第一次存款的 0.01 ETH:** 已经锁在 L1 的网关里,L2 上没到账。这是测试币。Morph 的 L1 Messenger 有 `replayMessage`(可用更大的 gas 重放),本次没有去做重放。 +- **另一个教训(我自己的):** 存款脚本我接了 `| cut`,输出被缓冲到脚本结束才显示,让我在等待的 10 分钟里看不到进展;已改成直接写文件。 +- **对计划的影响:** `deposit-test.sh` 的默认 gas 上限改为 400000,可用 `GAS_LIMIT` 覆盖。第二次存款的结果见下一条。 + +#### I-027 结论(第二次存款,gas 上限 400000)— 已证实 + +- 在 Hoodi 区块 4043433 存入 0.01 ETH 到新地址 `0xA2ac…6357`(L1 gas 224386)。**node-0 上约 25 秒后到账**;**node-1 在 391 秒后到账**(它要等包含该 L2 区块的批次 4 提交到 L1,再从 blob 还原)。 +- 所以第一次失败确实是 **`_gasLimit = 110000` 不足**,不是链路或配置问题。仓库示例任务里的 110000 在这套部署上不能用,存款至少给到几十万。 +- 之后把 node-1 已有的全部区块(0 到 796)逐个与 node-0 比对哈希:**0 个不一致**。这个范围同时包含区块 342(含失败的 L1 消息交易)和成功存款所在的区块,说明两条路径下 node-1 还原的结果也和 node-0 一致。 +- **未做:** 第一次失败存款的 0.01 ETH 的 `replayMessage` 重放(测试币,金额小)。 + +### I-028 出块节点 node-0 重启后永远不再出块 — 单个 tendermint 节点的拓扑不可重启(重启测试 T5 失败) + +- **现象:** `scripts/restart-test.sh` 的 T5(停 15 秒再起 node-0):进程是 running、RPC 能答、日志没有任何错误,但 L2 高度冻结(7675),**链停了**。重启前的区块哈希不变(T5b 通过,没有分叉)。 +- **日志特征(与 Morph `ops/README.md` 描述的"静默停转"一致):** `ABCI Handshake height=7675` → `Reactor waitSync=true` → `Already upgraded to sequencer mode, consensus reactor will not start height=3 upgradeHeight=2` → 最后一行是 `derivation skipped: sequencer mode`,**之后没有任何输出**,没有启动出块例程。 +- **根因(已在代码里确认,不是猜测):** + 1. 出块例程只在 `blocksync/reactor.go` 里 `if bcR.pool.IsCaughtUp()` 之后才 `StartSequencerRoutines()`(没有任何配置能绕开); + 2. `blocksync/pool.go` 的 `IsCaughtUp()` 第一条是 `if len(pool.peers) == 0 { return false }`("Need at least 1 peer to be considered caught up"); + 3. 我们的拓扑里 node-0 是**唯一**运行 tendermint 的节点(node-1 是 layer1 校验模式,不启动 tendermint),`persistent_peers` 为空,pool 没有对端。 + 4. 首次启动能出块,是因为从高度 0 开始,靠单验证者先跑 PBFT 阶段、升级进入出块模式,不走这条路径;**重启后高度已超过升级高度,必须走 block pool,于是卡死。** +- **这是这个拓扑的固有限制,不是原生运行引入的:** Morph 的 `ops/README.md` 第 3 条前置条件写着"至少需要两个运行 tendermint 的节点,layer1 校验模式的节点不算",上游 docker 版的单序列器拓扑(node-0 + layer1 的 node-1)应有同样的限制。**我没有在 docker 版上验证过,这一句是按代码推断的。** +- **处理:** 新增 `scripts/add-node2.py`,在现有运行目录上追加一个标准全节点 **node-2(带 morph-el-2,没有出块密钥)**,它运行 tendermint,是 node-0 的 block pool 里永远存在的对端;node-0 的 `persistent_peers` 加入 node-2。**保留 node-1 不变**,因为它的"独立从 L1 blob 还原"验证我不想丢。端口:node-2 的 tendermint 26666/26667/26670,morph-el-2 的 8745/8746/8751/30305/6162。 +- **此前的结论需要修正:** 我之前汇报"主线验证完成"时没有包含重启恢复,这正是当时列在"未验证"里的那一项,现在证明它确实有问题。 + +#### I-028 结论(加入 node-2 后重跑完整重启测试) + +- `scripts/restart-test.sh`(T1~T6、T8)**19 项全部通过、0 失败**: + - T1 `kill -9` node-1:5 秒内被守护外壳拉起,继续还原,tip 哈希一致; + - T2 / T3 重启 morph-el-1 / node-1:继续还原,哈希一致; + - T4 停 L1 代理 20 秒:L1 同步恢复、node-0 没停、所有进程都没退出; + - **T5 重启出块节点 node-0:24 秒内恢复出块(原先永远停转),重启前的区块哈希不变,无分叉;** + - T6 重启 morph-el-0:node-0 恢复出块; + - T8 全部 down 再 up:高度从 8196 继续(不是从 0),历史区块哈希不变,所有进程在运行,node-1 tip 哈希一致。 +- 恢复期间三个节点已有的 7563 个区块哈希逐个比对,0 个不一致:那次停转没有造成分叉。 +- 测试脚本里一处文字("all 7 processes")在加入 node-2 后过时,检查本身用的是完整进程清单,已改文字。 +- T7(重启 tx-submitter 并等下一批)单独跑,见下一条。 + +### 验证记录:L2→L1 提款(P7-5)通过 + +- `scripts/withdraw-test.sh`:L2 区块 8341 发起 0.005 ETH 提款(叶子下标 0,`from` 为 L2 的 ETH 网关,`to` 为 L1 的 ETH 网关);343 秒后 L1 Rollup 列出包含它的 withdrawal root;本地从 L2 的全部 `AppendMessage` 事件重建深度 32 的稀疏默克尔树,**重建的根与链上一致**;L1 `proveAndRelayMessage`(区块 4044651,状态 1,gas 167527)发出 `RelayedMessage`;新的 L1 接收地址余额 0.0 → 0.005 ETH。 +- 证明算法的离线自测(`scripts/withdraw-proof.selftest.js`):逐行复刻合约的 `_appendMessageHash` / `getTreeRoot` / `verifyMerkleProof`,210 组(叶子数 1~20 × 每个下标)全部一致。 +- 只验证了**一笔**提款(树里只有一个叶子)。多笔提款时证明的兄弟节点会包含真实叶子,算法已被离线自测覆盖,但链上还没有用多笔提款实测。 diff --git a/ops/native-hoodi/notes/versions.md b/ops/native-hoodi/notes/versions.md new file mode 100644 index 000000000..e34fc4604 --- /dev/null +++ b/ops/native-hoodi/notes/versions.md @@ -0,0 +1,47 @@ +# 版本记录(P1-9) + +记录日期:2026-11-18 + +## 源码 + +| 项目 | 版本 | +|---|---| +| Morph 仓库 | `ae987b15`(2026-11-11,"add reproduceable code for CICD (#1088)"),工作分支 `native-hoodi` | +| go-ethereum 子模块 | `1c528b351`(2026-11-09),tag `morph-v2.2.8` | + +## 构建环境 + +| 工具 | 版本 | +|---|---| +| Go | 1.25.7(Morph 的 `go.work` 要求 ≥ 1.24.0,满足) | +| Rust | 1.95.0(Docker 版用 1.88) | +| Node | v24.19.0 | +| yarn | 1.22.22 | +| Foundry(cast / forge) | 1.9.0 | +| gcc | 13 | +| solc(hardhat 自动下载) | 0.8.24,evm target cancun | + +## 二进制(`ops/native-hoodi/bin/`) + +| 路径 | 版本输出 | 大小 | 编译耗时 | +|---|---|---|---| +| `morph-geth/geth` | `Version: 2.2.8-mainnet` | 53 MB | 23 秒 | +| `morphnode/morphnode` | `--help` 正常(不支持 `--version`) | 52 MB | 35 秒(与 tendermint 一起) | +| `morphnode/tendermint` | `0.37.0-alpha.1` | 41 MB | | +| `tx-submitter/tx-submitter` | `v1.0.0-2.2.8-mainnet-ae987b15-1794400668` | 35 MB | 19 秒 | +| `gas-oracle/app` | 需要环境变量才能运行(见 I-004) | 25 MB | 2 分 20 秒 | + +合计约 197 MB。 + +## 合约工具链 + +| 步骤 | 结果 | +|---|---| +| `yarn install --frozen-lockfile`(在 `contracts/`) | 安装 1039 个包,49 秒 | +| `yarn hardhat compile` | 223 个 Solidity 文件通过,31 秒,Node 24 可用 | +| `yarn build`(完整,即 `main.py` 部署前跑的那条) | 通过,37 秒;含 `autogen:artifacts`、`build:ts`、`typechain`、`go build` 差异测试工具 | +| 编译后 `git status` | 干净(产物都被 `.gitignore` 忽略) | + +## 日志 + +所有构建日志在 `run/build-logs/`:`p1-2-morph-geth.log`、`p1-3-node.log`、`p1-4-tx-submitter.log`、`p1-5-gas-oracle.log`、`p1-6-yarn-install.log`、`p1-6-hardhat-compile.log`、`p1-6-yarn-build.log`。 diff --git a/ops/native-hoodi/scripts/add-node2.py b/ops/native-hoodi/scripts/add-node2.py new file mode 100755 index 000000000..0b9294770 --- /dev/null +++ b/ops/native-hoodi/scripts/add-node2.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""add-node2.py — add a second tendermint-running node (node-2 + morph-el-2) to an existing L2 run directory. + +Why: after node-0 (the only tendermint node) is restarted it can never resume block production. Its block pool must +report "caught up" before it starts the sequencer routines, and blocksync/pool.go IsCaughtUp() returns false while the +pool has no peer. node-1 runs in layer1 verify mode and does not run tendermint, so it does not count. Morph's own +ops/README.md says the same: "At least one other node running tendermint, i.e. two nodes minimum". + +node-2 is an ordinary full node: it runs tendermint, follows node-0 over P2P, executes blocks on its own morph-geth, and +holds NO sequencer key (only one node may hold it unless HA is enabled). + +It leaves everything that exists untouched, except that node-0's persistent_peers gains node-2 (so a restarted node-0 +dials it at once). It refuses to overwrite an existing node2 / el2. + +Usage: add-node2.py --morph REPO --run-dir run/l2 --tendermint BIN --geth BIN +""" +import argparse, base64, hashlib, json, os, re, shutil, subprocess, sys, tempfile + +N2_P2P, N2_RPC, N2_PROM = 26666, 26667, 26670 # node-2 tendermint ports (node-0 uses 26656/26657/26660) +EL2_P2P = 30305 # morph-el-2 p2p; the other ports follow morph-native.sh's formula + + +def node_id(path): + with open(path) as f: + priv = json.load(f)["priv_key"]["value"] + return hashlib.sha256(base64.b64decode(priv)[32:]).hexdigest()[:40] + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--morph", required=True) + ap.add_argument("--run-dir", required=True) + ap.add_argument("--tendermint", required=True) + ap.add_argument("--geth", required=True) + a = ap.parse_args() + docker_dir = os.path.join(a.morph, "ops", "docker") + run_dir = os.path.abspath(a.run_dir) + nodes = os.path.join(run_dir, "nodes") + n2, el2 = os.path.join(nodes, "node2"), os.path.join(run_dir, "el2") + for p in (n2, el2): + if os.path.exists(p): + sys.exit(f"{p} already exists; refusing to overwrite") + for p in (os.path.join(nodes, "node0", "config", "config.toml"), os.path.join(run_dir, "el0")): + if not os.path.exists(p): + sys.exit(f"{p} not found: run setup first") + + # ---- node-2's tendermint home: take the skeleton of a 1-validator + 2-non-validator testnet, keep only node2 + tmp = tempfile.mkdtemp(prefix="node2-skel-") + subprocess.run([a.tendermint, "testnet", "--v", "1", "--n", "2", "--o", tmp, "--populate-persistent-peers", + "--hostname", "127.0.0.1", "--hostname", "127.0.0.1", "--hostname", "127.0.0.1"], + check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + shutil.copytree(os.path.join(tmp, "node2"), n2) + cfg_dir = os.path.join(n2, "config") + shutil.copyfile(os.path.join(docker_dir, "node2", "node_key.json"), os.path.join(cfg_dir, "node_key.json")) + shutil.copyfile(os.path.join(docker_dir, "tendermint-devnet-genesis.json"), os.path.join(cfg_dir, "genesis.json")) + # not a genesis validator: it must not hold a validator key (a node holding the sole genesis key gets block sync disabled) + for f in (os.path.join(cfg_dir, "priv_validator_key.json"), os.path.join(n2, "data", "priv_validator_state.json")): + if os.path.exists(f): + os.remove(f) + + id0 = node_id(os.path.join(nodes, "node0", "config", "node_key.json")) + id2 = node_id(os.path.join(cfg_dir, "node_key.json")) + path = os.path.join(cfg_dir, "config.toml") + c = open(path).read() + for old, new in [('create_empty_blocks_interval = "0s"', 'create_empty_blocks_interval = "5s"'), + ('peer_gossip_sleep_duration = "100ms"', 'peer_gossip_sleep_duration = "10ms"'), + ('flush_throttle_timeout = "100ms"', 'flush_throttle_timeout = "10ms"'), + ('max_packet_msg_payload_size = 1024', 'max_packet_msg_payload_size = 10485760'), + ('send_rate = 5120000', 'send_rate = 52428800'), ('recv_rate = 5120000', 'recv_rate = 102428800'), + ('block_sync = false', 'block_sync = true'), ('prometheus = false', 'prometheus = true'), + ('pex = true', 'pex = false')]: + c = c.replace(old, new) + c = re.sub(r'persistent_peers\s*=\s*".*?"', f'persistent_peers = "{id0}@127.0.0.1:26656"', c) + c = re.sub(r'proxy_app\s*=\s*"[^"]*"', 'proxy_app = "tcp://127.0.0.1:26668"', c, count=1) + c = re.sub(r'(\[rpc\][\s\S]*?laddr\s*=\s*)"[^"]*"', rf'\1"tcp://127.0.0.1:{N2_RPC}"', c, count=1) + c = re.sub(r'(\[p2p\][\s\S]*?laddr\s*=\s*)"[^"]*"', rf'\1"tcp://127.0.0.1:{N2_P2P}"', c, count=1) + c = re.sub(r'prometheus_listen_addr\s*=\s*"[^"]*"', f'prometheus_listen_addr = "127.0.0.1:{N2_PROM}"', c) + open(path, "w").write(c) + + # ---- node-0 dials node-2 as soon as it starts + p0 = os.path.join(nodes, "node0", "config", "config.toml") + c0 = open(p0).read() + c0, n = re.subn(r'persistent_peers\s*=\s*".*?"', f'persistent_peers = "{id2}@127.0.0.1:{N2_P2P}"', c0) + assert n == 1 + open(p0, "w").write(c0) + + # ---- morph-el-2: same genesis as the others, nodekey2, static peers to el-0 / el-1 (loopback ports from morph-native.sh) + genesis = os.path.join(run_dir, "..", "l1", "genesis", "genesis-l2.json") + os.makedirs(os.path.join(el2, "geth")) + shutil.copyfile(os.path.join(docker_dir, "nodekey2"), os.path.join(el2, "geth", "nodekey")) + subprocess.run([a.geth, "--verbosity=3", "init", f"--datadir={el2}", os.path.abspath(genesis)], check=True, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + shutil.copyfile(os.path.join(run_dir, "el1", "geth", "static-nodes.json"), os.path.join(el2, "geth", "static-nodes.json")) + print("node-2 id :", id2) + print("node-0 id :", id0) + print("added :", n2, "and", el2) + + +if __name__ == "__main__": + main() diff --git a/ops/native-hoodi/scripts/build-all.sh b/ops/native-hoodi/scripts/build-all.sh new file mode 100755 index 000000000..ced85def2 --- /dev/null +++ b/ops/native-hoodi/scripts/build-all.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# build-all.sh — build every binary and the contracts toolchain into bin/ (steps from TODO.md P1). Logs: run/build-logs/. +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +MORPH="${MORPH:-$(cd "${ROOT}/../.." && pwd)}" +source "${ROOT}/scripts/lib/env.sh" +require_build_tools +L="${ROOT}/run/build-logs"; mkdir -p "${L}" "${ROOT}"/bin/{morph-geth,morphnode,tx-submitter,gas-oracle} +step() { echo "$(date +%H:%M:%S) build: $1"; } +step morph-geth; ( cd "${MORPH}/go-ethereum" && env GO111MODULE=on GOWORK=off go run build/ci.go install ./cmd/geth ) >"${L}/p1-2-morph-geth.log" 2>&1 +cp "${MORPH}/go-ethereum/build/bin/geth" "${ROOT}/bin/morph-geth/geth" +step node; ( cd "${MORPH}/node" && make build ) >"${L}/p1-3-node.log" 2>&1 +cp "${MORPH}/node/build/bin/morphnode" "${MORPH}/node/build/bin/tendermint" "${ROOT}/bin/morphnode/" +step tx-submitter; ( cd "${MORPH}/tx-submitter" && make build ) >"${L}/p1-4-tx-submitter.log" 2>&1 +cp "${MORPH}/tx-submitter/tx-submitter" "${ROOT}/bin/tx-submitter/" +step gas-oracle; ( cd "${MORPH}/gas-oracle" && make build ) >"${L}/p1-5-gas-oracle.log" 2>&1 +cp "${MORPH}/gas-oracle/app/target/release/app" "${ROOT}/bin/gas-oracle/" +step contracts; ( cd "${MORPH}/contracts" && yarn install --frozen-lockfile && yarn build ) >"${L}/p1-6-contracts.log" 2>&1 +step done +"${ROOT}/bin/morph-geth/geth" version | sed -n 1,2p; "${ROOT}/bin/morphnode/tendermint" version +ls -la "${ROOT}"/bin/*/ | grep -v '^total' +git -C "${MORPH}" status --short diff --git a/ops/native-hoodi/scripts/check-no-secrets.sh b/ops/native-hoodi/scripts/check-no-secrets.sh new file mode 100755 index 000000000..5d6f7dcc6 --- /dev/null +++ b/ops/native-hoodi/scripts/check-no-secrets.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# check-no-secrets.sh — run before committing: fails if a tracked-or-untracked, non-ignored file in this directory +# contains something that looks like a private key (0x + 64 hex digits) or a secrets file. +set -uo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/.." +bad=0 +# well-known PUBLIC values: Anvil/Hardhat account #0 dev key, EIP-1967 implementation / admin storage slots +ALLOW='ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80|360894a13ba1a3210667c828492db98dca3e2076cc373|b53127684a568b3173ae13b9f8a6016e243e63b6e8ee' +PAT='(^|[^0-9a-fA-F])(0x)?[0-9a-fA-F]{64}([^0-9a-fA-F]|$)' +hits() { grep -nE "${PAT}" "$1" | grep -vE "${ALLOW}"; } +while IFS= read -r f; do + [[ -f "$f" ]] || continue + if hits "$f" >/dev/null 2>&1; then + echo "possible 32-byte hex value in: $f" + hits "$f" | cut -c1-60 | sed 's/^/ /' + bad=1 + fi +done < <(git ls-files -co --exclude-standard -- .) +case "$(git ls-files -co --exclude-standard -- env | tr '\n' ' ')" in *secrets*) echo "a secrets file is not ignored"; bad=1;; esac +[[ $bad -eq 0 ]] && echo "ok: nothing that looks like a private key" +exit $bad diff --git a/ops/native-hoodi/scripts/deploy-l1.sh b/ops/native-hoodi/scripts/deploy-l1.sh new file mode 100755 index 000000000..50c3517e3 --- /dev/null +++ b/ops/native-hoodi/scripts/deploy-l1.sh @@ -0,0 +1,264 @@ +#!/usr/bin/env bash +# +# deploy-l1.sh — 在 L1(公共 Hoodi,或其 anvil 分叉)上部署 Morph 合约,并生成 L2 创世。 +# +# 对应上游 ops/devnet-morph/devnet/__init__.py 的 devnet_deploy(),但: +# - 不调用 docker compose,不改写仓库里被 git 跟踪的 .env / l1.ts(batchHeader 走环境变量 MORPH_BATCH_HEADER) +# - 不调用 `hardhat fund`(它会转 100 ETH);提交者资金由 SUBMITTER_FUND_ETH 控制,默认不转 +# - 每一步幂等:成功后在 $RUN_DIR/state/ 落标记文件,重跑会跳过已完成的步骤 +# - 私钥只通过环境变量传递,不出现在命令行参数或输出里 +# +# 必需环境变量: +# RPC_URL L1 执行层 RPC(Hoodi 或 anvil 分叉),链 ID 必须是 560048 +# RUN_DIR 本次运行的输出目录(部署产物、创世文件、日志、状态) +# 可选: +# SECRETS 密钥文件,默认 env/secrets.env +# WAIT_FINALIZED 1(默认)= 部署完等 L1 finalized 越过当前块;分叉干跑设 0 +# FINALIZED_TIMEOUT_SEC 等待 finalized 的超时,默认 1800(Hoodi 约需 13 分钟) +# SUBMITTER_FUND_ETH 向 batch submitter 转多少 ETH(默认 0 = 不转) +# STOP_AFTER 执行到指定步骤后停止,如 s21_batchheader(用于分段验证) +# USE_CONSISTENCY_PROXY auto(默认:RPC 是 https 就启用)/ 1 / 0。启用时在本机起 rpc-consistency-proxy.js, +# 所有读都经它转发,解决公共 RPC 多节点造成的"刚上链就读不到"(见 notes/issues.md I-018、I-019) +# PROXY_PORT 代理端口,默认 18546 +# RPC_FALLBACK_URLS 代理的备用上游(逗号分隔),主上游限流或不可达时自动切换。 +# 默认 0xrpc.io 与 publicnode;设为空字符串则不用备用 +# +# 退出码:0 成功;1 某步骤失败(日志路径会打印)。 + +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +MORPH="${MORPH:-$(cd "${ROOT}/../.." && pwd)}" +: "${RPC_URL:?set RPC_URL (Hoodi EL RPC or an anvil fork of it)}" +: "${RUN_DIR:?set RUN_DIR}" +SECRETS="${SECRETS:-${ROOT}/env/secrets.env}" +WAIT_FINALIZED="${WAIT_FINALIZED:-1}" +FINALIZED_TIMEOUT_SEC="${FINALIZED_TIMEOUT_SEC:-1800}" +SUBMITTER_FUND_ETH="${SUBMITTER_FUND_ETH:-0}" +STOP_AFTER="${STOP_AFTER:-}" +EXPECT_L1_CHAIN_ID=560048 + +STATE="${RUN_DIR}/state" +LOGS="${RUN_DIR}/logs" +DEPLOY_DIR="${RUN_DIR}/deployment" +GENESIS_DIR="${RUN_DIR}/genesis" +DEPLOY_JSON="${DEPLOY_DIR}/hoodidev.json" +GEN_CONFIG="${RUN_DIR}/hoodidev-deploy-config.generated.json" +mkdir -p "${STATE}" "${LOGS}" "${DEPLOY_DIR}" "${GENESIS_DIR}" + +# shellcheck disable=SC1090 +source "${ROOT}/scripts/lib/env.sh" +[[ -f "${SECRETS}" ]] || { echo "missing ${SECRETS}" >&2; exit 1; } +set -a +# shellcheck disable=SC1090 +source "${SECRETS}" +set +a +# Public RPCs sit behind several nodes; a read right after a mined write can hit a node that has not seen the block. +# contracts/src/deploy-utils.ts retries its assertion reads when these are set (default there: off). +export MORPH_CONTRACTS="${MORPH}/contracts" # send-tx.js loads ethers from here +export MORPH_READ_RETRIES="${MORPH_READ_RETRIES:-15}" +export MORPH_READ_RETRY_DELAY_MS="${MORPH_READ_RETRY_DELAY_MS:-2000}" + +# ---- read-after-write consistency proxy for public RPCs ---- +USE_CONSISTENCY_PROXY="${USE_CONSISTENCY_PROXY:-auto}" +PROXY_PORT="${PROXY_PORT:-18546}" +UPSTREAM_RPC_URL="${RPC_URL}" +if [[ "${USE_CONSISTENCY_PROXY}" == "1" || ( "${USE_CONSISTENCY_PROXY}" == "auto" && "${RPC_URL}" == https://* ) ]]; then + if (exec 3<>"/dev/tcp/127.0.0.1/${PROXY_PORT}") 2>/dev/null; then + echo "port ${PROXY_PORT} is already in use; set PROXY_PORT or stop what is listening" >&2; exit 1 + fi + # fallbacks are used when the primary is rate-limited or unreachable (public RPCs do rate-limit; see notes/issues.md I-020) + RPC_FALLBACK_URLS="${RPC_FALLBACK_URLS-https://0xrpc.io/hoodi,https://ethereum-hoodi-rpc.publicnode.com}" + node "${ROOT}/scripts/rpc-consistency-proxy.js" "${UPSTREAM_RPC_URL}${RPC_FALLBACK_URLS:+,${RPC_FALLBACK_URLS}}" "${PROXY_PORT}" >"${LOGS}/rpc-proxy.log" 2>&1 & + PROXY_PID=$! + trap 'kill "${PROXY_PID}" 2>/dev/null || true' EXIT + for _ in $(seq 1 50); do (exec 3<>"/dev/tcp/127.0.0.1/${PROXY_PORT}") 2>/dev/null && break; sleep 0.1; done + RPC_URL="http://127.0.0.1:${PROXY_PORT}" + echo "$(date +%H:%M:%S) consistency proxy ${UPSTREAM_RPC_URL} -> ${RPC_URL} (pid ${PROXY_PID})" +fi + +export HOODIDEV_RPC_URL="${RPC_URL}" +export ETH_RPC_URL="${RPC_URL}" +for v in DEPLOYER_PRIVATE_KEY SEQUENCER_PRIVATE_KEY BATCH_SUBMITTER_PRIVATE_KEY; do + [[ "${!v:-}" =~ ^0x[0-9a-fA-F]{64}$ ]] || { echo "${v} is not set to a 32-byte hex key in ${SECRETS}" >&2; exit 1; } +done + +# addr_of ENVVAR: derive an address from the key held in that variable without putting the key on a command line +# (ethers from the contracts' node_modules reads the key from the environment; `cast wallet address` only takes it as an argument) +addr_of() { ( cd "${MORPH}/contracts" && KEY="${!1}" node -e 'console.log(new (require("ethers").Wallet)(process.env.KEY).address)' ); } +DEPLOYER="$(addr_of DEPLOYER_PRIVATE_KEY)" +SEQUENCER="$(addr_of SEQUENCER_PRIVATE_KEY)" +SUBMITTER="$(addr_of BATCH_SUBMITTER_PRIVATE_KEY)" + +say() { printf '%s %s\n' "$(date +%H:%M:%S)" "$*"; } + +# step NAME FUNCTION: run once; skip if its marker exists; log to $LOGS/NAME.log. +# The function runs in a subshell with `set -e` ON. (Calling it from an `if` would silently disable errexit and let a failed +# command in the middle of a step go unnoticed -- exactly how a failed `cast send` once showed up as "ok".) +step() { + local name="$1" fn="$2" rc + if [[ -f "${STATE}/${name}.done" ]]; then say "[skip] ${name} (already done)"; else + say "[run ] ${name}" + set +e + ( set -e; "${fn}" ) >"${LOGS}/${name}.log" 2>&1 + rc=$? + set -e + if [[ "${rc}" -ne 0 ]]; then + say "[FAIL] ${name} (exit ${rc}) -- last lines of ${LOGS}/${name}.log:" + tail -n 15 "${LOGS}/${name}.log" | sed 's/^/ /' >&2 + exit 1 + fi + touch "${STATE}/${name}.done" + say "[ ok ] ${name}" + fi + if [[ "${STOP_AFTER}" == "${name}" ]]; then say "STOP_AFTER=${name}: stopping here"; exit 0; fi +} + +hardhat() { ( cd "${MORPH}/contracts" && yarn -s hardhat "$@" ); } +wei_to_eth() { cast from-wei "$1" 2>/dev/null || echo "$1"; } + +# ---------------------------------------------------------------- steps +s00_preflight() { + local id bal start_dec + id="$(cast chain-id --rpc-url "${RPC_URL}")" + [[ "${id}" == "${EXPECT_L1_CHAIN_ID}" ]] || { echo "L1 chain id is ${id}, expected ${EXPECT_L1_CHAIN_ID}"; return 1; } + bal="$(cast balance "${DEPLOYER}" --rpc-url "${RPC_URL}")" + [[ "${bal}" != "0" ]] || { echo "deployer ${DEPLOYER} has no balance on this L1"; return 1; } + echo "${bal}" >"${STATE}/deployer-balance-before.wei" + cast balance "${SUBMITTER}" --rpc-url "${RPC_URL}" >"${STATE}/submitter-balance-before.wei" + cast nonce "${DEPLOYER}" --rpc-url "${RPC_URL}" >"${STATE}/deployer-nonce-before" + start_dec="$(cast block-number --rpc-url "${RPC_URL}")" + echo "${start_dec}" >"${STATE}/start-block.dec" + printf '0x%x\n' "${start_dec}" >"${STATE}/start-block.hex" + # generated copy of the genesis deploy config with the real L1 starting block (the tracked file keeps a placeholder) + node -e ' + const fs = require("fs"); + const [src, dst, tag] = process.argv.slice(1); + const c = JSON.parse(fs.readFileSync(src, "utf8")); + c.l1StartingBlockTag = tag; + fs.writeFileSync(dst, JSON.stringify(c, null, 2) + "\n"); + ' "${MORPH}/ops/l2-genesis/deploy-config/hoodidev-deploy-config.json" "${GEN_CONFIG}" "$(cat "${STATE}/start-block.hex")" + echo "chain ${id}; deployer ${DEPLOYER} balance $(wei_to_eth "${bal}") ETH; L1 start block ${start_dec}" +} + +s10_deploy() { + # hardhat's --storagepath appends to an existing file; start from nothing by moving any leftover of a failed run aside + if [[ -e "${DEPLOY_JSON}" ]]; then mv "${DEPLOY_JSON}" "${DEPLOY_JSON}.prev-$(date +%s)"; fi + hardhat deploy --network hoodidev --storagepath "${DEPLOY_JSON}" --concurrent false +} + +s11_verify_deploy() { + local n=0 bad=0 name addr + while IFS=$'\t' read -r name addr; do + n=$((n + 1)) + if [[ "$(cast code "${addr}" --rpc-url "${RPC_URL}")" == "0x" ]]; then echo "NO CODE: ${name} ${addr}"; bad=$((bad + 1)); fi + done < <(node -e 'for (const d of JSON.parse(require("fs").readFileSync(process.argv[1], "utf8"))) console.log(d.name + "\t" + d.address)' "${DEPLOY_JSON}") + echo "${n} deployed entries, ${bad} without code" + [[ "${n}" -gt 0 && "${bad}" -eq 0 ]] +} + +s20_genesis() { + ( cd "${MORPH}/ops/l2-genesis" && env CGO_ENABLED=1 CGO_LDFLAGS="-ldl" go run cmd/main.go genesis l2 \ + --l1-rpc "${RPC_URL}" \ + --deploy-config "${GEN_CONFIG}" \ + --deployment-dir "${DEPLOY_JSON}" \ + --outfile.l2 "${GENESIS_DIR}/genesis-l2.json" \ + --outfile.genbatchheader "${GENESIS_DIR}/genesis-batch-header.json" \ + --outfile.rollup "${GENESIS_DIR}/rollup.json" ) + [[ -s "${GENESIS_DIR}/genesis-l2.json" && -s "${GENESIS_DIR}/rollup.json" ]] +} + +s21_batchheader() { + node -e ' + const r = JSON.parse(require("fs").readFileSync(process.argv[1], "utf8")); + if (!r.genesis_batch_header) { console.error("no genesis_batch_header in rollup.json"); process.exit(1); } + require("fs").writeFileSync(process.argv[2], r.genesis_batch_header); + console.log("genesis_batch_header length", r.genesis_batch_header.length, "l2_genesis_state_root", r.l2_genesis_state_root); + ' "${GENESIS_DIR}/rollup.json" "${STATE}/batch-header.hex" +} + +s30_initialize() { + [[ -s "${STATE}/batch-header.hex" ]] || { echo "batch header missing: run s21_batchheader first"; return 1; } + MORPH_BATCH_HEADER="$(cat "${STATE}/batch-header.hex")" \ + hardhat initialize --network hoodidev --storagepath "${DEPLOY_JSON}" --concurrent false +} + +s31_register() { + # register: owner adds the submitter and STAKES submitterMinimumStake on its behalf (paid by the deployer). + # NOT `hardhat fund`, which would send 100 ETH to the submitter. + batchSubmitterPks="[\"${BATCH_SUBMITTER_PRIVATE_KEY}\"]" \ + hardhat register --network hoodidev --storagepath "${DEPLOY_JSON}" +} + +s32_first_sequencer() { + local seq_proxy owner cur data + seq_proxy="$(node -e 'const d=JSON.parse(require("fs").readFileSync(process.argv[1],"utf8")).find(x=>x.name==="Proxy__L1Sequencer"); if(!d){process.exit(1)} console.log(d.address)' "${DEPLOY_JSON}")" + owner="$(cast call "${seq_proxy}" 'owner()(address)' --rpc-url "${RPC_URL}")" + [[ "${owner,,}" == "${DEPLOYER,,}" ]] || { echo "L1Sequencer owner ${owner} != deployer ${DEPLOYER}"; return 1; } + cur="$(cast call "${seq_proxy}" 'getSequencer()(address)' --rpc-url "${RPC_URL}" 2>/dev/null || true)" + if [[ "${cur,,}" == "${SEQUENCER,,}" ]]; then echo "first sequencer already ${SEQUENCER}"; return 0; fi + data="$(cast calldata 'setFirstSequencer(address)' "${SEQUENCER}")" + KEY="${DEPLOYER_PRIVATE_KEY}" node "${ROOT}/scripts/send-tx.js" "${RPC_URL}" "${seq_proxy}" --data "${data}" + # do not trust the exit code alone: read the result back + cur="$(cast call "${seq_proxy}" 'getSequencer()(address)' --rpc-url "${RPC_URL}")" + [[ "${cur,,}" == "${SEQUENCER,,}" ]] || { echo "getSequencer() = ${cur}, expected ${SEQUENCER}"; return 1; } + echo "L1Sequencer ${seq_proxy}: first sequencer is ${SEQUENCER}" +} + +s33_fund_submitter() { + if [[ "${SUBMITTER_FUND_ETH}" == "0" ]]; then echo "SUBMITTER_FUND_ETH=0: not funding the submitter (do it by hand)"; return 0; fi + local before after want + before="$(cast balance "${SUBMITTER}" --rpc-url "${RPC_URL}")" + KEY="${DEPLOYER_PRIVATE_KEY}" node "${ROOT}/scripts/send-tx.js" "${RPC_URL}" "${SUBMITTER}" --value-ether "${SUBMITTER_FUND_ETH}" + after="$(cast balance "${SUBMITTER}" --rpc-url "${RPC_URL}")" + want="$(cast to-wei "${SUBMITTER_FUND_ETH}" ether)" + node -e 'process.exit(BigInt(process.argv[2]) - BigInt(process.argv[1]) === BigInt(process.argv[3]) ? 0 : 1)' "${before}" "${after}" "${want}" || + { echo "submitter balance ${before} -> ${after}, expected +${want}"; return 1; } + echo "submitter funded: $(wei_to_eth "${before}") -> $(wei_to_eth "${after}") ETH" +} + +s40_wait_finalized() { + if [[ "${WAIT_FINALIZED}" != "1" ]]; then echo "WAIT_FINALIZED=${WAIT_FINALIZED}: skipped"; return 0; fi + local target end fin + target="$(cast block-number --rpc-url "${RPC_URL}")" + end=$(( $(date +%s) + FINALIZED_TIMEOUT_SEC )) + while true; do + fin="$(cast block finalized --field number --rpc-url "${RPC_URL}" 2>/dev/null || echo 0)" + echo "finalized=${fin} target=${target}" + [[ "${fin}" -ge "${target}" ]] && return 0 + [[ "$(date +%s)" -lt "${end}" ]] || { echo "timeout after ${FINALIZED_TIMEOUT_SEC}s"; return 1; } + sleep 20 + done +} + +s90_summary() { + local b0 b1 s0 s1 n0 n1 spent + b0="$(cat "${STATE}/deployer-balance-before.wei")"; b1="$(cast balance "${DEPLOYER}" --rpc-url "${RPC_URL}")" + s0="$(cat "${STATE}/submitter-balance-before.wei")"; s1="$(cast balance "${SUBMITTER}" --rpc-url "${RPC_URL}")" + n0="$(cat "${STATE}/deployer-nonce-before")"; n1="$(cast nonce "${DEPLOYER}" --rpc-url "${RPC_URL}")" + spent="$(node -e 'console.log((BigInt(process.argv[1]) - BigInt(process.argv[2])).toString())' "${b0}" "${b1}")" + { + echo "deployer ${DEPLOYER}" + echo " balance before: $(wei_to_eth "${b0}") ETH" + echo " balance after : $(wei_to_eth "${b1}") ETH" + echo " spent : $(wei_to_eth "${spent}") ETH (${spent} wei)" + echo " transactions : $((n1 - n0))" + echo "submitter ${SUBMITTER}" + echo " balance before: $(wei_to_eth "${s0}") ETH after: $(wei_to_eth "${s1}") ETH" + echo "L1 start block : $(cat "${STATE}/start-block.dec") ($(cat "${STATE}/start-block.hex"))" + } | tee "${STATE}/summary.txt" +} + +say "RPC ${RPC_URL} RUN_DIR ${RUN_DIR}" +step s00_preflight s00_preflight +step s10_deploy s10_deploy +step s11_verify_deploy s11_verify_deploy +step s20_genesis s20_genesis +step s21_batchheader s21_batchheader +step s30_initialize s30_initialize +step s31_register s31_register +step s32_first_sequencer s32_first_sequencer +step s33_fund_submitter s33_fund_submitter +step s40_wait_finalized s40_wait_finalized +s90_summary +if [[ -n "${PROXY_PID:-}" ]]; then say "proxy stats: $(curl -s "http://127.0.0.1:${PROXY_PORT}/stats")"; fi diff --git a/ops/native-hoodi/scripts/deposit-test.sh b/ops/native-hoodi/scripts/deposit-test.sh new file mode 100755 index 000000000..7633589bd --- /dev/null +++ b/ops/native-hoodi/scripts/deposit-test.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +# +# deposit-test.sh — L1 -> L2 ETH deposit smoke test (P7-1). +# Deposits AMOUNT_ETH from the deployer on Hoodi into a brand-new random L2 address, then waits for the balance to +# appear on BOTH L2 nodes (node-0 produced the block; node-1 re-derives it from L1). +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +MORPH="${MORPH:-$(cd "${ROOT}/../.." && pwd)}" +L1_RUN="${L1_RUN:-${ROOT}/run/l1}" +AMOUNT_ETH="${AMOUNT_ETH:-0.01}" +VALUE_ETH="${VALUE_ETH:-0.012}" # amount + the L1 message fee (110000 gas * l2BaseFee is tiny; the rest is refunded) +GAS_LIMIT="${GAS_LIMIT:-400000}" # 110000 (the repo example) ran out of gas on L2: see notes/issues.md I-027 +L1_RPC="${L1_RPC:-http://127.0.0.1:18546}" # the l1-proxy started by morph-native.sh +L2_A=http://127.0.0.1:8545; L2_B=http://127.0.0.1:8645 +# shellcheck disable=SC1090 +source "${ROOT}/scripts/lib/env.sh" +set -a; source "${ROOT}/env/secrets.env"; set +a +export MORPH_CONTRACTS="${MORPH}/contracts" +ROUTER="$(node -e 'console.log(JSON.parse(require("fs").readFileSync(process.argv[1],"utf8")).find(x=>x.name==="Proxy__L1GatewayRouter").address)' "${L1_RUN}/deployment/hoodidev.json")" +RECIPIENT="$(cd "${MORPH}/contracts" && node -e 'console.log(require("ethers").Wallet.createRandom().address)')" # address only; nobody holds its key +say() { printf '%s %s\n' "$(date +%H:%M:%S)" "$*"; } + +say "L1GatewayRouter ${ROUTER}"; say "fresh L2 recipient ${RECIPIENT} (balance now: A=$(cast balance "${RECIPIENT}" --rpc-url ${L2_A}) B=$(cast balance "${RECIPIENT}" --rpc-url ${L2_B}))" +data="$(cast calldata 'depositETH(address,uint256,uint256)' "${RECIPIENT}" "$(cast to-wei "${AMOUNT_ETH}" ether)" "${GAS_LIMIT}")" +KEY="${DEPLOYER_PRIVATE_KEY}" node "${ROOT}/scripts/send-tx.js" "${L1_RPC}" "${ROUTER}" --data "${data}" --value-ether "${VALUE_ETH}" +t0=$(date +%s); want="$(cast to-wei "${AMOUNT_ETH}" ether)" +while true; do + a="$(cast balance "${RECIPIENT}" --rpc-url ${L2_A})"; b="$(cast balance "${RECIPIENT}" --rpc-url ${L2_B})" + say "L2 balance: node-0=${a} node-1=${b} (want ${want})" + [[ "${a}" == "${want}" && "${b}" == "${want}" ]] && break + [[ $(( $(date +%s) - t0 )) -lt "${DEPOSIT_TIMEOUT_SEC:-600}" ]] || { echo "timed out waiting for the deposit on L2" >&2; exit 1; } + sleep 15 +done +say "OK: ${AMOUNT_ETH} ETH deposited on Hoodi arrived on L2 at ${RECIPIENT} on both nodes after $(( $(date +%s) - t0 )) s" diff --git a/ops/native-hoodi/scripts/dryrun-fork.sh b/ops/native-hoodi/scripts/dryrun-fork.sh new file mode 100755 index 000000000..5c0230907 --- /dev/null +++ b/ops/native-hoodi/scripts/dryrun-fork.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# +# dryrun-fork.sh — P2-5:在 Hoodi 的 anvil 分叉上把 deploy-l1.sh 完整干跑一遍,量出真实的 gas / ETH 需求。 +# +# anvil 从公共 Hoodi 分叉出一个本地链(链 ID 560048),给 deployer / submitter 凭空设置余额; +# 部署只发生在本地分叉里,**不会向公共 Hoodi 发送任何交易,也不花任何测试币**。 +# +# 用法:dryrun-fork.sh [RUN_DIR] (默认 run/dryrun-<时间戳>) +# 环境:FORK_URL 默认 https://rpc.hoodi.ethpandaops.io;PORT 默认 18545 +# +# 退出时会停掉自己启动的 anvil(按 pid 文件)。 + +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +FORK_URL="${FORK_URL:-https://rpc.hoodi.ethpandaops.io}" +PORT="${PORT:-18545}" +RUN_DIR="${1:-${ROOT}/run/dryrun-$(date +%Y%m%d-%H%M%S)}" +mkdir -p "${RUN_DIR}/logs" +# shellcheck disable=SC1090 +source "${ROOT}/scripts/lib/env.sh" +command -v anvil >/dev/null 2>&1 || { echo "error: anvil (Foundry) is not on PATH" >&2; exit 1; } + +PIDFILE="${RUN_DIR}/anvil.pid" +cleanup() { if [[ -f "${PIDFILE}" ]]; then kill "$(cat "${PIDFILE}")" 2>/dev/null || true; fi; } +trap cleanup EXIT + +if (exec 3<>"/dev/tcp/127.0.0.1/${PORT}") 2>/dev/null; then echo "port ${PORT} is already in use" >&2; exit 1; fi + +echo "starting anvil fork of ${FORK_URL} on 127.0.0.1:${PORT} (chain-id 560048)" +anvil --fork-url "${FORK_URL}" --chain-id 560048 --port "${PORT}" --host 127.0.0.1 >"${RUN_DIR}/logs/anvil.log" 2>&1 & +echo $! >"${PIDFILE}" +for _ in $(seq 1 60); do + cast chain-id --rpc-url "http://127.0.0.1:${PORT}" >/dev/null 2>&1 && break + sleep 1 +done +RPC="http://127.0.0.1:${PORT}" +[[ "$(cast chain-id --rpc-url "${RPC}")" == "560048" ]] || { echo "anvil fork did not come up; see ${RUN_DIR}/logs/anvil.log" >&2; exit 1; } +echo "fork head: $(cast block-number --rpc-url "${RPC}")" + +# give the two paying accounts a generous balance on the FORK ONLY (nothing touches public Hoodi) +MORPH="$(cd "${ROOT}/../.." && pwd)" +set -a; source "${ROOT}/env/secrets.env"; set +a +for v in DEPLOYER_PRIVATE_KEY BATCH_SUBMITTER_PRIVATE_KEY; do + a="$( cd "${MORPH}/contracts" && KEY="${!v}" node -e 'console.log(new (require("ethers").Wallet)(process.env.KEY).address)' )" + cast rpc anvil_setBalance "${a}" "$(cast to-hex 100000000000000000000)" --rpc-url "${RPC}" >/dev/null # 100 ETH, fork only +done + +RPC_URL="${RPC}" RUN_DIR="${RUN_DIR}" WAIT_FINALIZED=0 SUBMITTER_FUND_ETH="${SUBMITTER_FUND_ETH:-0}" \ + "${ROOT}/scripts/deploy-l1.sh" diff --git a/ops/native-hoodi/scripts/export-deployment.sh b/ops/native-hoodi/scripts/export-deployment.sh new file mode 100755 index 000000000..e3a791593 --- /dev/null +++ b/ops/native-hoodi/scripts/export-deployment.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# export-deployment.sh — save a record of a deployment under deployments// (no private keys). +# Usage: export-deployment.sh NAME [L1_RUN_DIR=run/l1] +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +NAME="${1:?usage: export-deployment.sh NAME [L1_RUN_DIR]}" +L1="${2:-${ROOT}/run/l1}" +D="${ROOT}/deployments/${NAME}" +source "${ROOT}/scripts/lib/env.sh" +[[ -f "${L1}/deployment/hoodidev.json" ]] || { echo "no deployment in ${L1}" >&2; exit 1; } +[[ ! -e "${D}" ]] || { echo "${D} exists; refusing to overwrite" >&2; exit 1; } +mkdir -p "${D}/genesis" "${D}/verification" +cp "${L1}/deployment/hoodidev.json" "${D}/contracts.json" +cp "${L1}"/genesis/*.json "${D}/genesis/" 2>/dev/null || true +[[ -f "${L1}/state/start-block.dec" ]] && cp "${L1}/state/start-block.dec" "${D}/l1-start-block.txt" +cp "${ROOT}/notes/versions.md" "${D}/versions.md" +for f in "${ROOT}"/run/*test*.out "${ROOT}"/run/verify*.out "${L1}"/../verify*.out; do [[ -f "$f" ]] && cp "$f" "${D}/verification/"; done 2>/dev/null || true +set -a; source "${ROOT}/env/secrets.env"; set +a +DEP="$(cast wallet address --private-key "${DEPLOYER_PRIVATE_KEY}")" +SEQ="$(cast wallet address --private-key "${SEQUENCER_PRIVATE_KEY}")" +SUB="$(cast wallet address --private-key "${BATCH_SUBMITTER_PRIVATE_KEY}")" +ORA="$(cast wallet address --private-key "${L2_GAS_ORACLE_PRIVATE_KEY}")" +{ + echo "# Deployment ${NAME}"; echo + echo "- exported: $(date -Is)" + echo "- L1: Ethereum Hoodi (chain 560048); L2 chain id 53077" + echo "- L1 start block: $(cat "${D}/l1-start-block.txt" 2>/dev/null || echo '?')" + echo "- L2 genesis hash: $(node -e 'try{const j=require(process.argv[1]);console.log(j.genesisHash||j.hash||"see genesis/")}catch(e){console.log("see genesis/")}' "${D}/genesis/rollup.json" 2>/dev/null || echo 'see genesis/')" + echo; echo "## Accounts (addresses only)"; echo + echo "| role | address |"; echo "|---|---|" + echo "| deployer | ${DEP} |"; echo "| sequencer | ${SEQ} |"; echo "| batch submitter | ${SUB} |"; echo "| gas oracle | ${ORA} |" + echo; echo "## Contracts (L1)"; echo; echo "| name | address |"; echo "|---|---|" + node -e 'for (const x of JSON.parse(require("fs").readFileSync(process.argv[1],"utf8"))) console.log("| "+x.name+" | "+x.address+" |")' "${D}/contracts.json" + echo; echo "Files: contracts.json, genesis/, versions.md, verification/ (test outputs)." +} >"${D}/README.md" +echo "exported to ${D}" diff --git a/ops/native-hoodi/scripts/init-secrets.sh b/ops/native-hoodi/scripts/init-secrets.sh new file mode 100755 index 000000000..1007ddc88 --- /dev/null +++ b/ops/native-hoodi/scripts/init-secrets.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# init-secrets.sh — create env/secrets.env (mode 600) from the template: your deployer key + three freshly generated keys. +# The deployer key comes from the environment (DEPLOYER_PRIVATE_KEY), never from the command line. Prints only addresses. +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "${ROOT}/scripts/lib/env.sh" +OUT="${ROOT}/env/secrets.env" +[[ -n "${DEPLOYER_PRIVATE_KEY:-}" ]] || { echo "error: set DEPLOYER_PRIVATE_KEY in the environment first" >&2; exit 1; } +[[ ! -e "${OUT}" ]] || { echo "error: ${OUT} exists; move it away first (scripts/reset-env.sh --new-keys does that)" >&2; exit 1; } +python3 -I - "${ROOT}/env/hoodi.env.example" "${OUT}" <<'PY' +import json, os, re, subprocess, sys +src, dst = sys.argv[1:3] +def new_key(): + out = json.loads(subprocess.check_output(["cast", "wallet", "new", "--json"])) + if isinstance(out, dict) and "data" in out: out = out["data"] + if isinstance(out, list): out = out[0] + return out["private_key"] +keys = {"DEPLOYER_PRIVATE_KEY": os.environ["DEPLOYER_PRIVATE_KEY"], "SEQUENCER_PRIVATE_KEY": new_key(), + "BATCH_SUBMITTER_PRIVATE_KEY": new_key(), "L2_GAS_ORACLE_PRIVATE_KEY": new_key()} +text = open(src).read() +for k, v in keys.items(): + text, n = re.subn(r'^(export ' + k + r'=).*$', lambda m: m.group(1) + '"' + v + '"', text, flags=re.M) + assert n == 1, k +fd = os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) +with os.fdopen(fd, "w") as f: f.write(text) +PY +set -a; source "${OUT}"; set +a +for r in DEPLOYER SEQUENCER BATCH_SUBMITTER L2_GAS_ORACLE; do v="${r}_PRIVATE_KEY"; printf '%-16s %s\n' "${r}" "$(cast wallet address --private-key "${!v}")"; done +echo "written ${OUT} (mode 600). Fund the DEPLOYER address with ~1.5 Hoodi ETH, then follow README.md." diff --git a/ops/native-hoodi/scripts/l2-bootstrap.sh b/ops/native-hoodi/scripts/l2-bootstrap.sh new file mode 100755 index 000000000..cd578b4a0 --- /dev/null +++ b/ops/native-hoodi/scripts/l2-bootstrap.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +# +# l2-bootstrap.sh — one-time setup on the (local, private) L2 so that the gas-price-oracle can work: +# 1. give the deployer (owner of the L2 contracts) and the oracle key some L2 balance, from a dev account that the L2 +# genesis pre-funds (`fundDevAccounts`). That account's key is the well-known Anvil #0 key: acceptable ONLY because +# this L2 listens on 127.0.0.1 and holds nothing of value. +# 2. let the deployer (GasPriceOracle owner) put the oracle key on the GasPriceOracle allow list +# (the bot's setters are `onlyAllowed`; the owner is the user's deployer, not the oracle key). +# Idempotent: every step checks the current state first and reads the result back. +# +# Usage: L2_RPC=http://127.0.0.1:8545 scripts/l2-bootstrap.sh +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +MORPH="${MORPH:-$(cd "${ROOT}/../.." && pwd)}" +L2_RPC="${L2_RPC:-http://127.0.0.1:8545}" +ORACLE_CONTRACT=0x530000000000000000000000000000000000000F +DEV_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 # Anvil #0: public, local-only L2 +FUND_DEPLOYER_ETH="${FUND_DEPLOYER_ETH:-100}" +FUND_ORACLE_ETH="${FUND_ORACLE_ETH:-10}" +# shellcheck disable=SC1090 +source "${ROOT}/scripts/lib/env.sh" +set -a; source "${ROOT}/env/secrets.env"; set +a +export MORPH_CONTRACTS="${MORPH}/contracts" + +addr_of() { ( cd "${MORPH}/contracts" && KEY="${!1}" node -e 'console.log(new (require("ethers").Wallet)(process.env.KEY).address)' ); } +DEPLOYER="$(addr_of DEPLOYER_PRIVATE_KEY)"; ORACLE="$(addr_of L2_GAS_ORACLE_PRIVATE_KEY)" +[[ "$(cast chain-id --rpc-url "${L2_RPC}")" == "53077" ]] || { echo "L2 at ${L2_RPC} is not chain 53077" >&2; exit 1; } +say() { printf '%s %s\n' "$(date +%H:%M:%S)" "$*"; } + +fund() { # fund NAME ADDRESS ETH + local bal; bal="$(cast balance "$2" --rpc-url "${L2_RPC}")" + if [[ "${bal}" != "0" ]]; then say "$1 $2 already has L2 balance $(cast from-wei "${bal}") ETH"; return 0; fi + cast send "$2" --value "$3ether" --private-key "${DEV_KEY}" --rpc-url "${L2_RPC}" >/dev/null + bal="$(cast balance "$2" --rpc-url "${L2_RPC}")" + [[ "${bal}" != "0" ]] || { echo "funding $1 failed" >&2; exit 1; } + say "$1 $2 funded on L2: $(cast from-wei "${bal}") ETH" +} +fund deployer "${DEPLOYER}" "${FUND_DEPLOYER_ETH}" +fund oracle "${ORACLE}" "${FUND_ORACLE_ETH}" + +owner="$(cast call "${ORACLE_CONTRACT}" 'owner()(address)' --rpc-url "${L2_RPC}")" +[[ "${owner,,}" == "${DEPLOYER,,}" ]] || { echo "GasPriceOracle owner ${owner} is not the deployer ${DEPLOYER}" >&2; exit 1; } +if [[ "$(cast call "${ORACLE_CONTRACT}" 'isAllowed(address)(bool)' "${ORACLE}" --rpc-url "${L2_RPC}")" == "true" ]]; then + say "oracle ${ORACLE} is already on the allow list" +else + data="$(cast calldata 'setAllowList(address[],bool[])' "[${ORACLE}]" "[true]")" + KEY="${DEPLOYER_PRIVATE_KEY}" node "${ROOT}/scripts/send-tx.js" "${L2_RPC}" "${ORACLE_CONTRACT}" --data "${data}" + [[ "$(cast call "${ORACLE_CONTRACT}" 'isAllowed(address)(bool)' "${ORACLE}" --rpc-url "${L2_RPC}")" == "true" ]] || + { echo "allow list still does not contain ${ORACLE}" >&2; exit 1; } + say "oracle ${ORACLE} added to the allow list (read back: true)" +fi +say "done: allowListEnabled=$(cast call "${ORACLE_CONTRACT}" 'allowListEnabled()(bool)' --rpc-url "${L2_RPC}")" diff --git a/ops/native-hoodi/scripts/lib/env.sh b/ops/native-hoodi/scripts/lib/env.sh new file mode 100644 index 000000000..39e73d8e0 --- /dev/null +++ b/ops/native-hoodi/scripts/lib/env.sh @@ -0,0 +1,40 @@ +# lib/env.sh — sourced by every script. Prepares the toolchain and fails early, with a clear message, if something is missing. +# +# MORPH_ENV_FILE=/path/to/env.sh optional: a file that puts Go / Rust / Node / Foundry on PATH (and sets any build flags +# your machine needs). It is sourced first. Without it, the tools must already be on PATH. +# +# Runtime tools (every script): node cast python3 curl (anvil only for dryrun-fork.sh) +# Build tools (build-all.sh): go (>= 1.24) cargo yarn make gcc +# This file only checks; it installs nothing. + +if [[ -n "${MORPH_ENV_FILE:-}" ]]; then + [[ -f "${MORPH_ENV_FILE}" ]] || { echo "error: MORPH_ENV_FILE=${MORPH_ENV_FILE} does not exist" >&2; exit 1; } + # shellcheck disable=SC1090 + source "${MORPH_ENV_FILE}" >/dev/null 2>&1 +fi + +_missing=() +for _t in node cast python3 curl; do command -v "${_t}" >/dev/null 2>&1 || _missing+=("${_t}"); done +if [[ ${#_missing[@]} -gt 0 ]]; then + echo "error: missing tools on PATH: ${_missing[*]}" >&2 + echo " node >= 18, python3 >= 3.9, curl, and Foundry (cast, anvil; tested with 1.9.0: https://getfoundry.sh)." >&2 + echo " If they are installed somewhere else, point MORPH_ENV_FILE at a file that sets PATH (see README.md)." >&2 + exit 1 +fi +unset _missing _t + +# build-all.sh calls this before it compiles anything +require_build_tools() { + local m=() t gov + for t in go cargo yarn make gcc; do command -v "${t}" >/dev/null 2>&1 || m+=("${t}"); done + if [[ ${#m[@]} -gt 0 ]]; then + echo "error: missing build tools on PATH: ${m[*]}" >&2 + echo " needs Go >= 1.24 (tested 1.25.7), Rust (tested 1.95; needs OpenSSL headers + pkg-config), Node + yarn 1.x, make, gcc." >&2 + exit 1 + fi + gov="$(go env GOVERSION 2>/dev/null | sed 's/^go//')" + if ! printf '1.24.0\n%s\n' "${gov}" | sort -V -C; then + echo "error: Go ${gov} is too old; Morph's go.work needs >= 1.24.0" >&2 + exit 1 + fi +} diff --git a/ops/native-hoodi/scripts/morph-native.sh b/ops/native-hoodi/scripts/morph-native.sh new file mode 100755 index 000000000..4c4f78627 --- /dev/null +++ b/ops/native-hoodi/scripts/morph-native.sh @@ -0,0 +1,290 @@ +#!/usr/bin/env bash +# +# morph-native.sh — 用原生进程运行 Morph L2(L1 = 公共 Hoodi),代替上游的 docker compose。 +# +# 进程(启动顺序): +# l1-proxy → morph-el-0 → node-0 → morph-el-1 → node-1 → morph-el-2 → node-2 → tx-submitter → gas-price-oracle +# node-2 exists only so that node-0 can be restarted: see notes/issues.md I-028 +# l1-proxy 是本机的 rpc-consistency-proxy.js:所有进程访问 L1 都走它(限流时切换备用端点、读写一致性),见 notes/issues.md I-018~I-021 +# node-0 是 tendermint 验证者(出块);node-1 以 layer1 校验模式运行,不启动 tendermint。 +# +# 用法: +# morph-native.sh setup 生成 tendermint / geth 运行目录(用 deploy-l1.sh 产出的创世文件) +# morph-native.sh up [NAME...] 启动全部或指定进程 +# morph-native.sh down 停止全部进程(保留链数据) +# morph-native.sh status 进程、L2 高度、L1 同步高度、Rollup 批次 +# morph-native.sh logs NAME 跟随某个进程的日志 +# morph-native.sh clean logs 把日志挪到 run/archive/(需先 down) +# morph-native.sh clean l2 把 L2 链数据挪到 run/archive/(需先 down)。**会让 L2 与 L1 上的 Rollup 对不上**,见下 +# morph-native.sh kill NAME 停掉某个进程(不会被自动重启) +# morph-native.sh start NAME 启动某个进程 +# +# 路径(可用环境变量改): +# L1_RUN deploy-l1.sh 的输出目录,默认 run/l1(其中 deployment/hoodidev.json、genesis/、state/start-block.dec) +# L2_RUN 本脚本的运行目录,默认 run/l2 +# +# 密钥取自 env/secrets.env,只经环境变量传给子进程,不出现在命令行参数里。 + +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +MORPH="${MORPH:-$(cd "${ROOT}/../.." && pwd)}" +BIN="${ROOT}/bin" +L1_RUN="${L1_RUN:-${ROOT}/run/l1}" +L2_RUN="${L2_RUN:-${ROOT}/run/l2}" +PIDS="${L2_RUN}/pids" +LOGS="${L2_RUN}/logs" +STATE="${L2_RUN}/state" +SECRETS="${SECRETS:-${ROOT}/env/secrets.env}" + +ALL=(l1-proxy morph-el-0 node-0 morph-el-1 node-1 morph-el-2 node-2 tx-submitter gas-price-oracle) +CHAIN_ID=53077 +JWT="${L2_RUN}/jwt-secret.txt" + +# shellcheck disable=SC1090 +source "${ROOT}/scripts/lib/env.sh" + +die() { echo "error: $*" >&2; exit 1; } +say() { printf '%s %s\n' "$(date +%H:%M:%S)" "$*"; } + +load_secrets() { + [[ -f "${SECRETS}" ]] || die "missing ${SECRETS}" + set -a + # shellcheck disable=SC1090 + source "${SECRETS}" + set +a + : "${L1_ETH_RPC:?L1_ETH_RPC not set in secrets}" "${L1_BEACON_RPC:?L1_BEACON_RPC not set in secrets}" + # every process talks to L1 through the local consistency proxy; the real endpoints become its upstreams + L1_UPSTREAM="${L1_ETH_RPC}" + L1_FALLBACKS="${RPC_FALLBACK_URLS-https://0xrpc.io/hoodi,https://ethereum-hoodi-rpc.publicnode.com}" + L1_PROXY_PORT="${PROXY_PORT:-18546}" + L1_ETH_RPC="http://127.0.0.1:${L1_PROXY_PORT}" +} + +# deployed address by name from the deployment file written by deploy-l1.sh +addr() { + node -e ' + const d = JSON.parse(require("fs").readFileSync(process.argv[1], "utf8")).find(x => x.name === process.argv[2]); + if (!d) { console.error("not in deployment: " + process.argv[2]); process.exit(1); } + console.log(d.address);' "${L1_RUN}/deployment/hoodidev.json" "$1" +} + +# ---------------------------------------------------------------- ports (PLAN.md §6) +idx_of() { case "$1" in morph-el-0|node-0) echo 0;; morph-el-1|node-1) echo 1;; morph-el-2|node-2) echo 2;; *) echo 0;; esac; } +el_http() { echo $((8545 + 100 * $1)); } +el_ws() { echo $((8546 + 100 * $1)); } +el_auth() { echo $((8551 + 100 * $1)); } +el_p2p() { echo $((30303 + $1)); } +el_metrics() { echo $((6160 + $1)); } # not 6060: the Coder workspace agent listens there + +# ---------------------------------------------------------------- process control +alive() { [[ -f "${PIDS}/$1.pid" ]] && kill -0 "$(cat "${PIDS}/$1.pid")" 2>/dev/null; } + +# spawn NAME ENV... -- CMD... : run under a tiny restart supervisor in its own process group +spawn() { + local name="$1"; shift + local envs=() + while [[ "$1" != "--" ]]; do envs+=("$1"); shift; done + shift + mkdir -p "${PIDS}" "${LOGS}" "${STATE}" + if alive "${name}"; then say "${name}: already running (pid $(cat "${PIDS}/${name}.pid"))"; return 0; fi + # cwd = state dir, so programs that write relative files (tx-submitter: journal.rlp, leveldb) stay inside run/ + cd "${STATE}" + setsid bash -c ' + echo $$ > "$1"; shift + while :; do + "$@"; rc=$? + echo "--- $(date +%FT%T) exited with status ${rc}; restarting in 2s" + sleep 2 + done' _ "${PIDS}/${name}.pid" env "${envs[@]}" "$@" >>"${LOGS}/${name}.log" 2>&1 & + for _ in $(seq 1 20); do [[ -s "${PIDS}/${name}.pid" ]] && break; sleep 0.1; done + say "${name}: started (pid $(cat "${PIDS}/${name}.pid" 2>/dev/null || echo ?))" +} + +stop_one() { + local name="$1" + if alive "${name}"; then + local pid; pid="$(cat "${PIDS}/${name}.pid")" + kill -TERM -- "-${pid}" 2>/dev/null || kill -TERM "${pid}" 2>/dev/null || true + for _ in $(seq 1 50); do kill -0 "${pid}" 2>/dev/null || break; sleep 0.2; done + kill -KILL -- "-${pid}" 2>/dev/null || true + say "${name}: stopped" + else + say "${name}: not running" + fi + mv -f "${PIDS}/${name}.pid" "${PIDS}/${name}.pid.stopped" 2>/dev/null || true +} + +wait_port() { # wait_port PORT [SECONDS] + local end=$(( $(date +%s) + ${2:-60} )) + until (exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null; do + [[ "$(date +%s)" -lt "${end}" ]] || die "port $1 did not open in time" + sleep 1 + done +} + +upgrade_time_ms() { # fixed on first start so restarts reuse it (see morph ops/README: never push this into the future) + mkdir -p "${STATE}" + [[ -s "${STATE}/sequencer-upgrade-time.ms" ]] || echo $(( $(date +%s) * 1000 )) >"${STATE}/sequencer-upgrade-time.ms" + cat "${STATE}/sequencer-upgrade-time.ms" +} + +# ---------------------------------------------------------------- per-process launchers +launch() { + local name="$1" i; i="$(idx_of "${name}")" + case "${name}" in + l1-proxy) + spawn l1-proxy -- node "${ROOT}/scripts/rpc-consistency-proxy.js" "${L1_UPSTREAM}${L1_FALLBACKS:+,${L1_FALLBACKS}}" "${L1_PROXY_PORT}" + wait_port "${L1_PROXY_PORT}" 15 + ;; + morph-el-0|morph-el-1|morph-el-2) + spawn "${name}" -- "${BIN}/morph-geth/geth" --datadir "${L2_RUN}/el${i}" --verbosity=3 \ + --http --http.corsdomain='*' --http.vhosts='*' --http.addr=127.0.0.1 --http.port="$(el_http "${i}")" \ + --http.api=web3,debug,eth,txpool,net,morph,engine,admin \ + --ws --ws.addr=127.0.0.1 --ws.port="$(el_ws "${i}")" --ws.origins='*' --ws.api=web3,debug,eth,txpool,net,morph,engine,admin \ + --networkid="${CHAIN_ID}" \ + --authrpc.addr=127.0.0.1 --authrpc.port="$(el_auth "${i}")" --authrpc.vhosts='*' --authrpc.jwtsecret="${JWT}" \ + --gcmode=archive --nodiscover --miner.gasprice=0 --port="$(el_p2p "${i}")" \ + --metrics --metrics.expensive --metrics.addr=127.0.0.1 --metrics.port="$(el_metrics "${i}")" + wait_port "$(el_http "${i}")" 60 + ;; + node-0|node-1|node-2) + local envs=( + "MORPH_NODE_L2_ETH_RPC=http://127.0.0.1:$(el_http "${i}")" + "MORPH_NODE_L2_ENGINE_RPC=http://127.0.0.1:$(el_auth "${i}")" + "MORPH_NODE_L2_ENGINE_AUTH=${JWT}" + "MORPH_NODE_L1_ETH_RPC=${L1_ETH_RPC}" + "MORPH_NODE_L1_ETH_BEACON_RPC=${L1_BEACON_RPC}" + "MORPH_NODE_SYNC_DEPOSIT_CONTRACT_ADDRESS=$(addr Proxy__L1MessageQueueWithGasPriceOracle)" + "MORPH_NODE_L1_CONFIRMATIONS=0" + "MORPH_NODE_ROLLUP_ADDRESS=$(addr Proxy__Rollup)" + "MORPH_NODE_SYNC_START_HEIGHT=$(cat "${L1_RUN}/state/start-block.dec")" + "MORPH_NODE_UPGRADE_BATCH_TIME=0" + "MORPH_NODE_L1_SEQUENCER_CONTRACT=$(addr Proxy__L1Sequencer)" + "MORPH_NODE_SEQUENCER_UPGRADE_TIME=$(upgrade_time_ms)" + ) + if [[ "${name}" == node-0 ]]; then + envs+=("MORPH_NODE_SEQUENCER_PRIVATE_KEY=${SEQUENCER_PRIVATE_KEY}") + elif [[ "${name}" == node-2 ]]; then + # an ordinary full node: runs tendermint (so node-0's block pool always has a peer after a restart), follows node-0, + # and holds NO sequencer key (only one node may, unless HA is on) + : + else + # layer1 verify mode: no tendermint. Its metrics port defaults to 26660, the same as node-0's tendermint prometheus + envs+=("EMPTY_BLOCK_DELAY=true" "MORPH_NODE_DERIVATION_VERIFY_MODE=layer1" + "MORPH_NODE_METRICS_SERVER_ENABLE=true" "MORPH_NODE_METRICS_PORT=27660") + fi + spawn "${name}" "${envs[@]}" -- "${BIN}/morphnode/morphnode" --home "${L2_RUN}/nodes/node${i}" + ;; + tx-submitter) + spawn tx-submitter \ + "TX_SUBMITTER_BUILD_ENV=dev" \ + "TX_SUBMITTER_L1_ETH_RPC=${L1_ETH_RPC}" \ + "TX_SUBMITTER_L1_PRIVATE_KEY=${BATCH_SUBMITTER_PRIVATE_KEY}" \ + "TX_SUBMITTER_L2_ETH_RPCS=http://127.0.0.1:$(el_http 0),http://127.0.0.1:$(el_http 1)" \ + "TX_SUBMITTER_TX_TIMEOUT=60s" \ + "TX_SUBMITTER_ROLLUP_ADDRESS=$(addr Proxy__Rollup)" \ + "TX_SUBMITTER_SUBMITTER_ADDRESS=$(addr Proxy__Submitter)" \ + "TX_SUBMITTER_BATCH_BLOCK_INTERVAL=$(node -e 'console.log(require(process.argv[1]).govBatchBlockInterval)' "${MORPH}/ops/l2-genesis/deploy-config/hoodidev-deploy-config.json")" \ + "TX_SUBMITTER_BATCH_TIMEOUT=$(node -e 'console.log(require(process.argv[1]).govBatchTimeout)' "${MORPH}/ops/l2-genesis/deploy-config/hoodidev-deploy-config.json")" \ + "TX_SUBMITTER_FINALIZE=true" "TX_SUBMITTER_SEAL_BATCH=true" \ + "TX_SUBMITTER_TX_FEE_LIMIT=${TX_FEE_LIMIT_WEI:-50000000000000000}" \ + "TX_SUBMITTER_BATCH_V2_UPGRADE_TIME=1777533291" \ + "TX_SUBMITTER_METRICS_SERVER_ENABLE=true" "TX_SUBMITTER_METRICS_HOSTNAME=127.0.0.1" "TX_SUBMITTER_METRICS_PORT=8060" \ + -- "${BIN}/tx-submitter/tx-submitter" + ;; + gas-price-oracle) + mkdir -p "${LOGS}/gas-oracle-files" + spawn gas-price-oracle \ + "GAS_ORACLE_L1_RPC=${L1_ETH_RPC}" \ + "GAS_ORACLE_L1_BEACON_RPC=${L1_BEACON_RPC%%,*}" \ + "GAS_ORACLE_L2_RPC=http://127.0.0.1:$(el_http 0)" \ + "GAS_THRESHOLD=5" "INTERVAL=28000" "OVERHEAD_INTERVAL=10" \ + "L2_GAS_PRICE_ORACLE=0x530000000000000000000000000000000000000F" \ + "L2_GAS_ORACLE_PRIVATE_KEY=${L2_GAS_ORACLE_PRIVATE_KEY}" \ + "L1_ROLLUP=$(addr Proxy__Rollup)" \ + "GAS_ORACLE_METRIC_ADDRESS=127.0.0.1:6070" \ + "GAS_ORACLE_LOG_DIR=${LOGS}/gas-oracle-files" \ + -- "${BIN}/gas-oracle/app" + ;; + *) die "unknown process: ${name} (one of: ${ALL[*]})" ;; + esac +} + +# ---------------------------------------------------------------- commands +cmd_setup() { + [[ -s "${L1_RUN}/genesis/genesis-l2.json" ]] || die "no ${L1_RUN}/genesis/genesis-l2.json — run deploy-l1.sh first" + python3 -I "${ROOT}/scripts/setup-nodes.py" --morph "${MORPH}" --run-dir "${L2_RUN}" \ + --genesis "${L1_RUN}/genesis/genesis-l2.json" \ + --tendermint "${BIN}/morphnode/tendermint" --geth "${BIN}/morph-geth/geth" + # node-0 cannot resume block production after a restart unless another tendermint node is its peer (notes/issues.md I-028) + python3 -I "${ROOT}/scripts/add-node2.py" --morph "${MORPH}" --run-dir "${L2_RUN}" \ + --tendermint "${BIN}/morphnode/tendermint" --geth "${BIN}/morph-geth/geth" +} + +# clean: never deletes anything -- it MOVES data into run/archive/-/ so a mistake can be undone. +cmd_clean() { + local what="${1:-}" p ts dest + for p in "${ALL[@]}"; do alive "${p}" && die "${p} is still running: run 'down' first"; done + ts="$(date +%Y%m%d-%H%M%S)"; dest="${ROOT}/run/archive/${what}-${ts}" + case "${what}" in + logs) + [[ -d "${LOGS}" ]] || die "no logs at ${LOGS}" + mkdir -p "${dest}" && mv "${LOGS}" "${dest}/logs" && say "logs moved to ${dest}" ;; + l2) + [[ -d "${L2_RUN}" ]] || die "nothing at ${L2_RUN}" + cat >&2 <= 0; i--)); do stop_one "${ALL[i]}"; done +} + +rpc_height() { cast block-number --rpc-url "http://127.0.0.1:$1" 2>/dev/null || echo "-"; } + +cmd_status() { + local n + for n in "${ALL[@]}"; do + if alive "${n}"; then printf ' %-18s running (pid %s)\n' "${n}" "$(cat "${PIDS}/${n}.pid")"; else printf ' %-18s stopped\n' "${n}"; fi + done + echo ">>> L2 heights: el-0 :$(el_http 0) -> $(rpc_height "$(el_http 0)") el-1 :$(el_http 1) -> $(rpc_height "$(el_http 1)") el-2 :$(el_http 2) -> $(rpc_height "$(el_http 2)")" + if [[ -f "${SECRETS}" ]]; then + load_secrets + echo ">>> L1 (Hoodi) head: $(cast block-number --rpc-url "${L1_UPSTREAM}" 2>/dev/null || echo '-')" + if alive l1-proxy; then echo ">>> l1-proxy stats: $(curl -s -m 3 "http://127.0.0.1:${L1_PROXY_PORT}/stats" | cut -c1-200)"; fi + if [[ -f "${L1_RUN}/deployment/hoodidev.json" ]]; then + local rollup; rollup="$(addr Proxy__Rollup)" + echo ">>> Rollup ${rollup}: lastCommittedBatchIndex = $(cast call "${rollup}" 'lastCommittedBatchIndex()(uint256)' --rpc-url "${L1_UPSTREAM}" 2>/dev/null || echo '?')" + fi + fi +} + +case "${1:-}" in + setup) cmd_setup ;; + clean) shift; cmd_clean "$@" ;; + up) shift; cmd_up "$@" ;; + down) cmd_down ;; + status) cmd_status ;; + logs) [[ -n "${2:-}" ]] || die "usage: logs NAME"; tail -n 100 -F "${LOGS}/$2.log" ;; + kill) [[ -n "${2:-}" ]] || die "usage: kill NAME"; stop_one "$2" ;; + start) [[ -n "${2:-}" ]] || die "usage: start NAME"; cmd_up "$2" ;; + *) sed -n '2,30p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; exit 1 ;; +esac diff --git a/ops/native-hoodi/scripts/probe-hoodi.sh b/ops/native-hoodi/scripts/probe-hoodi.sh new file mode 100755 index 000000000..f450ec579 --- /dev/null +++ b/ops/native-hoodi/scripts/probe-hoodi.sh @@ -0,0 +1,73 @@ +#!/usr/bin/env bash +# probe-hoodi.sh — 对 Hoodi 的公共 EL / 信标端点做温和的限流与能力探测(只读,不发交易)。 +# +# 用法:probe-hoodi.sh [并发数,默认 20] [轮数,默认 3] +# 输出:每个端点的 HTTP 状态分布、平均延迟,以及几项 Morph 实际会用到的接口。 +# 注意:对公共服务只做小规模并发,不是压测。 + +set -uo pipefail +CONC="${1:-20}" +ROUNDS="${2:-3}" + +EL_ENDPOINTS=("https://0xrpc.io/hoodi" "https://rpc.hoodi.ethpandaops.io") +BEACON_ENDPOINTS=("https://beacon.hoodi.ethpandaops.io" "https://ethereum-hoodi-beacon-api.publicnode.com") + +tmp="$(mktemp -d)" +trap 'rm -rf "${tmp}"' EXIT + +one_el() { # one_el URL METHOD PARAMS -> "HTTP_CODE TIME" + curl -s -o /dev/null -w '%{http_code} %{time_total}\n' -m 20 -X POST "$1" \ + -H 'content-type: application/json' \ + --data "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"$2\",\"params\":$3}" +} +export -f one_el + +summarize() { # summarize FILE -> "codes: 200x20 429x0 ...; avg=..s max=..s" + awk '{c[$1]++; t+=$2; if($2>m)m=$2; n++} END{ + s=""; for(k in c) s=s k "x" c[k] " "; printf "%s avg=%.2fs max=%.2fs n=%d\n", s, (n?t/n:0), m, n}' "$1" +} + +echo "== 并发 ${CONC} × ${ROUNDS} 轮" +for u in "${EL_ENDPOINTS[@]}"; do + : >"${tmp}/el.txt" + for _ in $(seq 1 "${ROUNDS}"); do + seq 1 "${CONC}" | xargs -P "${CONC}" -I{} bash -c "one_el '${u}' eth_blockNumber '[]'" >>"${tmp}/el.txt" + sleep 1 + done + printf 'EL %-44s ' "${u}"; summarize "${tmp}/el.txt" +done + +for u in "${BEACON_ENDPOINTS[@]}"; do + : >"${tmp}/bn.txt" + for _ in $(seq 1 "${ROUNDS}"); do + seq 1 "${CONC}" | xargs -P "${CONC}" -I{} curl -s -o /dev/null -w '%{http_code} %{time_total}\n' -m 20 "${u}/eth/v1/beacon/headers/head" >>"${tmp}/bn.txt" + sleep 1 + done + printf 'BEACON %-44s ' "${u}"; summarize "${tmp}/bn.txt" +done + +echo +echo "== eth_getLogs:区间上限(Morph 的 L1 同步会用)" +for u in "${EL_ENDPOINTS[@]}"; do + head_hex="$(curl -s -m 15 -X POST "${u}" -H 'content-type: application/json' --data '{"jsonrpc":"2.0","id":1,"method":"eth_blockNumber","params":[]}' | sed -E 's/.*"result":"(0x[0-9a-f]+)".*/\1/')" + head=$((head_hex)) + for span in 1000 5000 10000 50000; do + from=$(printf '0x%x' $((head - span))) + out="$(curl -s -m 30 -X POST "${u}" -H 'content-type: application/json' \ + --data "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"eth_getLogs\",\"params\":[{\"fromBlock\":\"${from}\",\"toBlock\":\"latest\",\"address\":\"0x00000000219ab540356cBB839Cbe05303d7705Fa\"}]}")" + if [[ "${out}" == *'"error"'* ]]; then msg="$(printf '%s' "${out}" | sed -E 's/.*"message":"([^"]{0,80}).*/\1/')"; else msg="ok"; fi + printf ' %-40s span=%-6s %s\n' "${u}" "${span}" "${msg}" + done +done + +echo +echo "== 信标:近期 slot 的 blob_sidecars 连续取 5 个" +for u in "${BEACON_ENDPOINTS[@]}"; do + head_slot="$(curl -s -m 15 "${u}/eth/v1/beacon/headers/head" | sed -E 's/.*"slot":"([0-9]+)".*/\1/')" + ok=0; fail=0 + for i in 1 2 3 4 5; do + code="$(curl -s -o /dev/null -w '%{http_code}' -m 20 "${u}/eth/v1/beacon/blob_sidecars/$((head_slot - 8 * i))")" + [[ "${code}" == 200 ]] && ok=$((ok + 1)) || fail=$((fail + 1)) + done + printf ' %-52s head_slot=%s ok=%d fail=%d\n' "${u}" "${head_slot}" "${ok}" "${fail}" +done diff --git a/ops/native-hoodi/scripts/reset-env.sh b/ops/native-hoodi/scripts/reset-env.sh new file mode 100755 index 000000000..fd7d7790e --- /dev/null +++ b/ops/native-hoodi/scripts/reset-env.sh @@ -0,0 +1,165 @@ +#!/usr/bin/env bash +# +# reset-env.sh — 把本机环境重置到"干净状态",并且可以原样恢复。从不删除任何东西,只 mv。 +# +# 用法: +# reset-env.sh plan [--with-build] [--new-keys] 只打印会做什么(默认命令,不改任何东西) +# reset-env.sh run [--with-build] [--new-keys] --yes 真正执行 +# reset-env.sh restore <时间戳> --yes 把某次 reset 挪走的东西原样挪回 +# reset-env.sh list 列出已有的归档 +# +# run 做的事(按顺序): +# 1. 检查 submitter 在 L1 上的余额;高于 SWEEP_THRESHOLD_ETH(默认 0.02)就拒绝,先回收资金再来(--ignore-balance 可跳过) +# 2. morph-native.sh down(停全部进程) +# 3. 把 run/ 下的运行数据(l1、l2、失败尝试、测试输出、日志)挪到 run/archive/<时间戳>/ +# 4. --with-build:把二进制和构建产物也挪进去(bin/、go-ethereum/build/bin、node/build/bin、tx-submitter 二进制、 +# gas-oracle/app/target、contracts 的 node_modules/artifacts/dist/typechain-types)。这些在 git 里都是被忽略的 +# 5. --new-keys:旧 env/secrets.env 挪到 env/archive/secrets-<时间戳>.env,新建一份:deployer 和 RPC 配置原样保留, +# sequencer / batch submitter / gas oracle 三个密钥重新生成(私钥不会被打印) +# 6. 写 run/archive/<时间戳>/MANIFEST.tsv(原路径现路径),restore 就靠它 +# +# 不碰:仓库里被 git 跟踪的文件、deployer 密钥、notes/ 与 docs、deployments/(部署记录)。 +# 公共 Hoodi 上已部署的合约不受影响(链上的东西没法"清空")。 +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +MORPH="${MORPH:-$(cd "${ROOT}/../.." && pwd)}" +CTL="${ROOT}/scripts/morph-native.sh" +SECRETS="${SECRETS:-${ROOT}/env/secrets.env}" +ARCH="${ROOT}/run/archive" +THRESH="${SWEEP_THRESHOLD_ETH:-0.02}" +# shellcheck disable=SC1090 +source "${ROOT}/scripts/lib/env.sh" + +die() { echo "error: $*" >&2; exit 1; } +say() { printf '%s %s\n' "$(date +%H:%M:%S)" "$*"; } + +CMD="${1:-plan}"; [[ $# -gt 0 ]] && shift +WITH_BUILD=0; NEW_KEYS=0; YES=0; IGNORE_BAL=0; TS_ARG="" +for a in "$@"; do + case "$a" in + --with-build) WITH_BUILD=1 ;; --new-keys) NEW_KEYS=1 ;; --yes) YES=1 ;; --ignore-balance) IGNORE_BAL=1 ;; + -*) die "unknown option $a" ;; *) TS_ARG="$a" ;; + esac +done + +data_paths() { # run data: everything under run/ except the archive itself + local p + for p in "${ROOT}"/run/*; do [[ "$p" == "${ARCH}" ]] && continue; [[ -e "$p" ]] && echo "$p"; done +} +build_paths() { + local p + for p in "${ROOT}/bin" "${MORPH}/go-ethereum/build/bin" "${MORPH}/node/build/bin" "${MORPH}/tx-submitter/tx-submitter" \ + "${MORPH}/gas-oracle/app/target" "${MORPH}/contracts/node_modules" "${MORPH}/contracts/artifacts" \ + "${MORPH}/contracts/dist" "${MORPH}/contracts/typechain-types"; do + [[ -e "$p" ]] && echo "$p" + done +} + +alive_any() { local f; for f in "${ROOT}"/run/l2/pids/*.pid; do [[ -f "$f" ]] && kill -0 "$(cat "$f")" 2>/dev/null && return 0; done; return 1; } + +# value of a variable in secrets.env without printing anything else +secret() { ( set -a; source "${SECRETS}"; set +a; printf '%s' "${!1:-}" ); } + +submitter_balance_eth() { + local key rpc addr + key="$(secret BATCH_SUBMITTER_PRIVATE_KEY)"; rpc="${HOODI_RPC:-https://rpc.hoodi.ethpandaops.io}" + [[ -n "${key}" ]] || { echo "?"; return; } + addr="$(cast wallet address --private-key "${key}" 2>/dev/null)" || { echo "?"; return; } + cast balance "${addr}" --ether --rpc-url "${rpc}" 2>/dev/null || echo "?" +} + +gen_secrets() { # $1 = new file; copies the old one, replacing the three generated roles + python3 -I - "${SECRETS}" "$1" <<'PY' +import json, re, subprocess, sys +src, dst = sys.argv[1:3] +roles = ["SEQUENCER_PRIVATE_KEY", "BATCH_SUBMITTER_PRIVATE_KEY", "L2_GAS_ORACLE_PRIVATE_KEY"] +def new_key(): + out = json.loads(subprocess.check_output(["cast", "wallet", "new", "--json"])) + if isinstance(out, dict) and "data" in out: out = out["data"] + if isinstance(out, list): out = out[0] + return out["private_key"] +text = open(src).read() +for r in roles: + pat = re.compile(r'^(\s*(?:export\s+)?' + r + r'\s*=\s*).*$', re.M) + if not pat.search(text): sys.exit("role not found in secrets: " + r) + k = new_key() + text = pat.sub(lambda m: m.group(1) + k, text, count=1) +open(dst, "w").write(text) +PY + chmod 600 "$1" +} + +do_plan_or_run() { + local ts items=() p + ts="$(date +%Y%m%d-%H%M%S)" + mapfile -t items < <(data_paths) + [[ "${WITH_BUILD}" -eq 1 ]] && mapfile -t -O "${#items[@]}" items < <(build_paths) + + echo "== reset-env ${CMD} (timestamp ${ts})" + echo "-- submitter balance on L1: $(submitter_balance_eth) ETH (threshold ${THRESH})" + echo "-- processes: $(alive_any && echo 'RUNNING -> will be stopped with morph-native.sh down' || echo 'none running')" + echo "-- will move to ${ARCH}/${ts}/ :" + for p in "${items[@]}"; do printf ' %s (%s)\n' "${p#"${ROOT}"/}" "$(du -sh "$p" 2>/dev/null | cut -f1)"; done + [[ "${WITH_BUILD}" -eq 1 ]] || echo " (build artifacts NOT included: add --with-build)" + if [[ "${NEW_KEYS}" -eq 1 ]]; then + echo "-- keys: env/secrets.env -> env/archive/secrets-${ts}.env ; new secrets.env keeps deployer + RPC settings, regenerates sequencer / submitter / gas-oracle keys" + else + echo "-- keys: unchanged (add --new-keys to regenerate sequencer / submitter / oracle)" + fi + [[ "${CMD}" == plan ]] && { echo "== plan only; nothing was changed. Re-run as: reset-env.sh run ... --yes"; return 0; } + + [[ "${YES}" -eq 1 ]] || die "refusing to run without --yes" + if [[ "${IGNORE_BAL}" -ne 1 ]]; then + local bal; bal="$(submitter_balance_eth)" + [[ "${bal}" != "?" ]] || die "could not read the submitter balance; fix the RPC or pass --ignore-balance" + awk -v b="${bal}" -v t="${THRESH}" 'BEGIN{exit !(b+0 > t+0)}' && die "submitter still holds ${bal} ETH (> ${THRESH}): sweep it to the deployer first, or pass --ignore-balance" + fi + + alive_any && "${CTL}" down + alive_any && die "processes still alive after down" + local dest="${ARCH}/${ts}" man + mkdir -p "${dest}"; man="${dest}/MANIFEST.tsv"; : >"${man}" + local n=0 + for p in "${items[@]}"; do + n=$((n + 1)); mkdir -p "${dest}/${n}" + mv "$p" "${dest}/${n}/" && printf '%s\t%s\n' "$p" "${dest}/${n}/$(basename "$p")" >>"${man}" + say "moved ${p#"${ROOT}"/}" + done + if [[ "${NEW_KEYS}" -eq 1 ]]; then + mkdir -p "${ROOT}/env/archive" + local old="${ROOT}/env/archive/secrets-${ts}.env" + cp -p "${SECRETS}" "${old}.tmp" && gen_secrets "${SECRETS}.new" && mv "${old}.tmp" "${old}" && mv "${SECRETS}.new" "${SECRETS}" + printf '%s\t%s\n' "${SECRETS}" "${old}" >>"${man}.keys" + say "secrets regenerated (old file kept at env/archive/secrets-${ts}.env)" + fi + mkdir -p "${ROOT}/run" + echo "== done. Restore with: reset-env.sh restore ${ts} --yes" +} + +do_restore() { + [[ -n "${TS_ARG}" ]] || die "usage: restore --yes" + local man="${ARCH}/${TS_ARG}/MANIFEST.tsv" orig cur + [[ -f "${man}" ]] || die "no manifest ${man}" + echo "== restore ${TS_ARG}" + while IFS=$'\t' read -r orig cur; do + if [[ -e "${orig}" ]]; then echo " CONFLICT (exists now): ${orig}"; CONFLICT=1; else echo " ${cur#"${ROOT}"/} -> ${orig#"${ROOT}"/}"; fi + done <"${man}" + [[ "${CONFLICT:-0}" -eq 0 ]] || die "some targets exist; reset again or move them away first" + [[ "${YES}" -eq 1 ]] || { echo "== preview only; add --yes"; return 0; } + alive_any && die "stop the stack first (morph-native.sh down)" + while IFS=$'\t' read -r orig cur; do mkdir -p "$(dirname "${orig}")"; mv "${cur}" "${orig}"; done <"${man}" + if [[ -f "${man}.keys" ]]; then + while IFS=$'\t' read -r orig cur; do + echo " note: the keys of that time are in ${cur#"${ROOT}"/}; current secrets.env was NOT overwritten (copy it yourself if wanted)" + done <"${man}.keys" + fi + echo "== restored" +} + +case "${CMD}" in + plan|run) do_plan_or_run ;; + restore) do_restore ;; + list) ls -1 "${ARCH}" 2>/dev/null || echo "(no archives)" ;; + *) sed -n '2,25p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; exit 1 ;; +esac diff --git a/ops/native-hoodi/scripts/restart-test.sh b/ops/native-hoodi/scripts/restart-test.sh new file mode 100755 index 000000000..400cba6ea --- /dev/null +++ b/ops/native-hoodi/scripts/restart-test.sh @@ -0,0 +1,119 @@ +#!/usr/bin/env bash +# +# restart-test.sh — does the Morph L2 stack recover from processes being killed or restarted? +# +# Scenarios T1..T8 (see below). Before each one the stack must be healthy (every process up, both L2 heights moving); a +# scenario passes only if its stated condition holds after the action. Nothing is assumed from exit codes: heights and +# block hashes are read from the nodes. +# +# Usage: restart-test.sh [T1 T2 ...] (default: all except T7, which waits for the next batch: add T7 explicitly) +set -uo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +CTL="${ROOT}/scripts/morph-native.sh" +L2_RUN="${L2_RUN:-${ROOT}/run/l2}" +L1_URL="${HOODI_RPC:-https://rpc.hoodi.ethpandaops.io}" +A=http://127.0.0.1:8545; B=http://127.0.0.1:8645 +# shellcheck disable=SC1090 +source "${ROOT}/scripts/lib/env.sh" +ALL_PROCS=(l1-proxy morph-el-0 node-0 morph-el-1 node-1 morph-el-2 node-2 tx-submitter gas-price-oracle) + +say() { printf '%s %s\n' "$(date +%H:%M:%S)" "$*"; } +ha() { cast block-number --rpc-url "${A}" 2>/dev/null || echo 0; } +hb() { cast block-number --rpc-url "${B}" 2>/dev/null || echo 0; } +hash_at() { cast block "$2" --field hash --rpc-url "$1" 2>/dev/null; } +alive() { [[ -f "${L2_RUN}/pids/$1.pid" ]] && kill -0 "$(cat "${L2_RUN}/pids/$1.pid")" 2>/dev/null; } +wait_until() { # wait_until SECONDS DESCRIPTION CMD... + local end=$(( $(date +%s) + $1 )) what="$2"; shift 2 + until "$@"; do [[ "$(date +%s)" -lt "${end}" ]] || { say " timed out: ${what}"; return 1; }; sleep 3; done +} +PASS=0; FAIL=0 +verdict() { # verdict NAME RC [DETAIL] + if [[ "$2" -eq 0 ]]; then PASS=$((PASS + 1)); say "PASS $1 ${3:-}"; else FAIL=$((FAIL + 1)); say "FAIL $1 ${3:-}"; fi +} + +all_up() { local p; for p in "${ALL_PROCS[@]}"; do alive "${p}" || return 1; done; } +a_moves() { local h; h="$(ha)"; sleep 10; [[ "$(ha)" -gt "${h}" ]]; } +b_moves() { local h; h="$(hb)"; sleep 30; [[ "$(hb)" -gt "${h}" ]]; } # node-1 advances in bursts, one batch at a time +tip_hashes_agree() { # hashes at node-1's tip-1 equal on both nodes + local t; t="$(( $(hb) - 1 ))"; [[ "$(hash_at "${A}" "${t}")" == "$(hash_at "${B}" "${t}")" && -n "$(hash_at "${A}" "${t}")" ]] +} +healthy() { all_up && a_moves; } +preflight() { say "-- preflight: all processes up and node-0 producing"; healthy || { say " stack is not healthy before ${1}; aborting"; exit 2; }; } + +# ---------------------------------------------------------------- scenarios +T1() { # crash node-1 with kill -9 (the supervisor should restart it by itself) + preflight T1 + local sup child h0; sup="$(cat "${L2_RUN}/pids/node-1.pid")"; child="$(pgrep -P "${sup}" | head -1)"; h0="$(hb)" + say "T1: kill -9 node-1 (pid ${child}, supervisor ${sup}); node-1 height before: ${h0}" + kill -9 "${child}"; sleep 5 + local newchild; newchild="$(pgrep -P "${sup}" | head -1)" + [[ -n "${newchild}" && "${newchild}" != "${child}" ]]; verdict "T1a supervisor restarted node-1 on its own" $? "(new pid ${newchild:-none})" + wait_until 900 "node-1 moves past ${h0}" bash -c "[[ \$(cast block-number --rpc-url ${B}) -gt ${h0} ]]"; verdict "T1b node-1 keeps deriving after the crash" $? "(height $(hb))" + tip_hashes_agree; verdict "T1c node-1 tip hash == node-0" $? +} +T2() { # stop/start morph-el-1 + preflight T2 + local h0; h0="$(hb)"; say "T2: stop morph-el-1 then start it; node-1 height before: ${h0}" + "${CTL}" kill morph-el-1 >/dev/null; sleep 5; "${CTL}" start morph-el-1 >/dev/null + wait_until 900 "node-1 moves past ${h0}" bash -c "[[ \$(cast block-number --rpc-url ${B}) -gt ${h0} ]]"; verdict "T2a node-1 resumes after its execution client restarted" $? "(height $(hb))" + tip_hashes_agree; verdict "T2b node-1 tip hash == node-0" $? +} +T3() { # stop/start node-1 + preflight T3 + local h0; h0="$(hb)"; say "T3: stop node-1 then start it; node-1 height before: ${h0}" + "${CTL}" kill node-1 >/dev/null; sleep 5; "${CTL}" start node-1 >/dev/null + wait_until 900 "node-1 moves past ${h0}" bash -c "[[ \$(cast block-number --rpc-url ${B}) -gt ${h0} ]]"; verdict "T3a node-1 resumes after a clean restart" $? "(height $(hb))" + tip_hashes_agree; verdict "T3b node-1 tip hash == node-0" $? +} +T4() { # stop/start the L1 proxy + preflight T4 + local l0; l0="$(curl -s -m 5 localhost:26660/metrics | awk '/^morphnode_syncer_l1height /{printf "%d", $2}')" + say "T4: stop l1-proxy for 20 s then start it; node-0 L1 syncer height before: ${l0}" + "${CTL}" kill l1-proxy >/dev/null; sleep 20; "${CTL}" start l1-proxy >/dev/null + wait_until 180 "node-0 syncer advances past ${l0}" bash -c "[[ \$(curl -s -m 5 localhost:26660/metrics | awk '/^morphnode_syncer_l1height /{printf \"%d\", \$2}') -gt ${l0} ]]" + verdict "T4a node-0 L1 syncer recovers after the proxy was gone" $? "(now $(curl -s -m 5 localhost:26660/metrics | awk '/^morphnode_syncer_l1height /{printf "%d", $2}'))" + a_moves; verdict "T4b node-0 never stopped producing" $? + all_up; verdict "T4c every process is still running (nothing exited because of the outage)" $? +} +T5() { # stop/start node-0, the block producer + preflight T5 + local h0 hash0 mid; h0="$(ha)"; mid="$(( h0 - 5 ))"; hash0="$(hash_at "${A}" "${mid}")" + say "T5: stop node-0 for 15 s then start it; node-0 height before: ${h0}; remembering the hash of block ${mid}" + "${CTL}" kill node-0 >/dev/null; sleep 15; "${CTL}" start node-0 >/dev/null + wait_until 180 "node-0 produces past ${h0}" bash -c "[[ \$(cast block-number --rpc-url ${A}) -gt ${h0} ]]"; verdict "T5a node-0 resumes producing after a restart" $? "(height $(ha))" + [[ "$(hash_at "${A}" "${mid}")" == "${hash0}" ]]; verdict "T5b block ${mid} unchanged after the restart (no reorg)" $? + a_moves; verdict "T5c node-0 keeps producing" $? +} +T6() { # stop/start the execution client of the producer + preflight T6 + local h0; h0="$(ha)"; say "T6: stop morph-el-0 for 15 s then start it; node-0 height before: ${h0}" + "${CTL}" kill morph-el-0 >/dev/null; sleep 15; "${CTL}" start morph-el-0 >/dev/null + wait_until 240 "node-0 produces past ${h0}" bash -c "[[ \$(cast block-number --rpc-url ${A}) -gt ${h0} ]]"; verdict "T6a node-0 produces again after its execution client came back" $? "(height $(ha))" + alive node-0; verdict "T6b node-0 process survived" $? +} +T7() { # stop/start tx-submitter, then wait for the next batch + preflight T7 + local R b0; R="$(node -e 'console.log(JSON.parse(require("fs").readFileSync(process.argv[1],"utf8")).find(x=>x.name==="Proxy__Rollup").address)' "${ROOT}/run/l1/deployment/hoodidev.json")" + b0="$(cast call "${R}" 'lastCommittedBatchIndex()(uint256)' --rpc-url ${L1_URL} | awk '{print $1}')" + say "T7: stop tx-submitter for 10 s then start it; committed batches before: ${b0}; waiting up to 15 min for the next one" + "${CTL}" kill tx-submitter >/dev/null; sleep 10; "${CTL}" start tx-submitter >/dev/null + wait_until 900 "a new batch is committed" bash -c "[[ \$(cast call ${R} 'lastCommittedBatchIndex()(uint256)' --rpc-url ${L1_URL} | awk '{print \$1}') -gt ${b0} ]]" + verdict "T7a submitter commits the next batch after a restart" $? "(now $(cast call "${R}" 'lastCommittedBatchIndex()(uint256)' --rpc-url ${L1_URL} | awk '{print $1}'))" +} +T8() { # everything down, everything up + preflight T8 + local h0 mid hash0; h0="$(ha)"; mid="$(( h0 - 5 ))"; hash0="$(hash_at "${A}" "${mid}")" + say "T8: down ALL, wait 15 s, up ALL; node-0 height before: ${h0}; remembering the hash of block ${mid}" + "${CTL}" down >/dev/null 2>&1; sleep 15; "${CTL}" up >/dev/null 2>&1 + wait_until 300 "node-0 serves RPC again" bash -c "cast block-number --rpc-url ${A} >/dev/null 2>&1" + wait_until 300 "node-0 produces past ${h0}" bash -c "[[ \$(cast block-number --rpc-url ${A}) -gt ${h0} ]]"; verdict "T8a node-0 continues from its old height, not from 0" $? "(before ${h0}, now $(ha))" + [[ "$(hash_at "${A}" "${mid}")" == "${hash0}" ]]; verdict "T8b history unchanged after a full stop/start" $? + all_up; verdict "T8c all processes are running" $? + wait_until 900 "node-1 catches up" bash -c "[[ \$(cast block-number --rpc-url ${B}) -gt 0 ]]"; tip_hashes_agree; verdict "T8d node-1 tip hash == node-0" $? +} + +SEL=("$@"); [[ ${#SEL[@]} -gt 0 ]] || SEL=(T1 T2 T3 T4 T5 T6 T8) +say "== restart test: ${SEL[*]}" +for s in "${SEL[@]}"; do "${s}"; done +say "== result: ${PASS} passed, ${FAIL} failed" +[[ "${FAIL}" -eq 0 ]] diff --git a/ops/native-hoodi/scripts/rpc-consistency-proxy.js b/ops/native-hoodi/scripts/rpc-consistency-proxy.js new file mode 100755 index 000000000..d694a1f78 --- /dev/null +++ b/ops/native-hoodi/scripts/rpc-consistency-proxy.js @@ -0,0 +1,227 @@ +#!/usr/bin/env node +/* + * rpc-consistency-proxy.js — a tiny JSON-RPC proxy that gives read-after-write consistency on a public RPC. + * + * Problem: public RPC endpoints sit behind several nodes. A client sends a transaction, sees its receipt from node A, + * then asks `latest` state from node B which has not seen that block yet and gets stale data or empty return data. + * Deploy scripts do exactly that (`await contract.deployed(); await contract.owner()`). + * + * Fix: remember the highest block we have seen (from receipts and eth_blockNumber) -- the "floor" -- and rewrite every + * state read that targets `latest`/`pending` to that explicit block number. A node that does not have the block yet + * answers with an error ("header not found", only eth_estimateGas does that on the endpoint we use) or, for most + * methods, with `result: null` (a valid eth_call/getBalance/getCode/... result is never null). Either way the proxy + * waits and retries, but ONLY for requests it rewrote; requests with an explicit block tag pass through unchanged so a + * client that polls for a future block is not held up. Writes and everything else pass through untouched. + * + * Usage: rpc-consistency-proxy.js UPSTREAM_URL[,FALLBACK_URL...] [PORT=18546] (listens on 127.0.0.1) + * GET /stats returns counters, including requests per method and rate-limit / failover counts. + */ +const http = require("http"); + +const upstreams = (process.argv[2] || "").split(",").map((u) => u.trim()).filter(Boolean); +const port = Number(process.argv[3] || 18546); +if (upstreams.length === 0) { console.error("usage: rpc-consistency-proxy.js UPSTREAM_URL[,FALLBACK_URL...] [PORT]"); process.exit(2); } +let current = 0; // index of the upstream that last answered; sticky until it is rate-limited or unreachable +const MIN_INTERVAL_MS = Number(process.env.PROXY_MIN_INTERVAL_MS || 0); // optional pacing between upstream calls (0 = off) +const HEAD_REFRESH_MS = Number(process.env.PROXY_HEAD_REFRESH_MS || 1000); // how often the floor follows the chain head +let nextSlot = 0; + +let floor = 0n; +const startAhead = BigInt(process.env.PROXY_TEST_FLOOR_AHEAD || 0); // testing aid: pretend we already saw head+N +const hex = (n) => "0x" + n.toString(16); +const bump = (v) => { try { const n = BigInt(v); if (n > floor) floor = n; } catch (_) { /* ignore */ } }; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const stats = { requests: 0, rewritten: 0, retries: 0, rateLimited: 0, networkErrors: 0, failovers: 0, byMethod: {} }; + +// method -> index of the block-tag parameter +const TAG_INDEX = { + eth_call: 1, eth_getCode: 1, eth_getBalance: 1, eth_getStorageAt: 2, + eth_getTransactionCount: 1, eth_estimateGas: 1, eth_getBlockByNumber: 0, +}; +const FLOATING = new Set([undefined, null, "latest", "pending", "safe", "finalized"]); +const NOT_YET = /header not found|missing trie node|unknown block|block not found|not available|no state|future block|too far|beyond current head|extends beyond|after last block/i; + +const RATE_LIMITED = /rate.?limit|too many requests|\b429\b|quota|exceeded/i; + +// One request to the upstreams. A rate-limit answer (HTTP 429/503 or a JSON-RPC error that says so) or a network error +// moves on to the next upstream at once; when every upstream refuses, back off exponentially (0.5 s .. 8 s) and go +// round again, up to 8 rounds. Anything else -- including ordinary JSON-RPC errors such as a revert -- is the answer. +async function callUpstream(req) { + stats.byMethod[req.method] = (stats.byMethod[req.method] || 0) + 1; + if (MIN_INTERVAL_MS > 0) { // global pacing: at most one upstream call per MIN_INTERVAL_MS + const now = Date.now(); + nextSlot = Math.max(nextSlot, now) + MIN_INTERVAL_MS; + const wait = nextSlot - MIN_INTERVAL_MS - now; + if (wait > 0) await sleep(wait); + } + let delay = 500; + for (let round = 0; round < 8; round++) { + for (let k = 0; k < upstreams.length; k++) { + const idx = (current + k) % upstreams.length; + try { + const r = await fetch(upstreams[idx], { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(req) }); + const text = await r.text(); + let j = null; + try { j = JSON.parse(text); } catch (_) { /* not JSON */ } + const limited = r.status === 429 || r.status === 503 || + (j && j.error && RATE_LIMITED.test(String(j.error.message || ""))); + if (j && !limited) { + if (idx !== current) { stats.failovers++; console.error(`[failover] now using ${upstreams[idx]}`); current = idx; } + return j; + } + stats.rateLimited++; + if (stats.rateLimited % 5 === 1) console.error(`[limited] ${req.method} on ${upstreams[idx]} (HTTP ${r.status}): ${j && j.error ? j.error.message : text.slice(0, 80)}`); + } catch (e) { + stats.networkErrors++; + if (stats.networkErrors % 5 === 1) console.error(`[network] ${upstreams[idx]}: ${e.message}`); + } + } + await sleep(delay); + delay = Math.min(delay * 2, 8000); + } + return { jsonrpc: "2.0", id: req.id, error: { code: -32005, message: "proxy: every upstream is rate-limited or unreachable" } }; +} + +function rewrite(req) { + if (floor === 0n) return req; + const p = Array.isArray(req.params) ? req.params.slice() : []; + if (req.method in TAG_INDEX) { + const i = TAG_INDEX[req.method]; + // "finalized"/"safe" are deliberately left alone: they are old enough to be consistent everywhere + if (p[i] === "latest" || p[i] === "pending" || p[i] === undefined || p[i] === null) { + p[i] = hex(floor); + stats.rewritten++; + return { ...req, params: p }; + } + } else if (req.method === "eth_getLogs" && p[0] && typeof p[0] === "object") { + const f = { ...p[0] }; + let changed = false; + if (f.blockHash === undefined) { + if (FLOATING.has(f.toBlock) && f.toBlock !== "finalized" && f.toBlock !== "safe") { f.toBlock = hex(floor); changed = true; } + if (f.fromBlock === "latest" || f.fromBlock === "pending") { f.fromBlock = hex(floor); changed = true; } + } + if (!changed) return req; // explicit range: nothing was rewritten + p[0] = f; + stats.rewritten++; + return { ...req, params: p }; + } + return req; +} + +// ---- the floor must follow the chain, otherwise a client that polls `latest` for a change it made (and never asks for the +// block number or a receipt) would be pinned to a block from before its own transaction and wait forever. +let lastRefresh = 0; +let refreshing = null; +async function refreshFloor() { + if (Date.now() - lastRefresh < HEAD_REFRESH_MS) return; + if (!refreshing) { + refreshing = (async () => { + try { const r = await callUpstream({ jsonrpc: "2.0", id: 0, method: "eth_blockNumber", params: [] }); if (r.result) bump(r.result); } + catch (_) { /* keep the old floor */ } + lastRefresh = Date.now(); + refreshing = null; + })(); + } + await refreshing; +} + +// ---- nonces: a state read pinned to a block cannot see transactions that were sent but not mined yet, so remember +// the next nonce of every sender we forwarded a transaction for (found via eth_getTransactionByHash). +const localNonce = new Map(); // lower-case address -> next nonce (BigInt) +async function recordSentTx(hash) { + for (let i = 0; i < 6; i++) { + const r = await callUpstream({ jsonrpc: "2.0", id: 0, method: "eth_getTransactionByHash", params: [hash] }); + if (r.result && r.result.from) { + const from = r.result.from.toLowerCase(); + const next = BigInt(r.result.nonce) + 1n; + if (next > (localNonce.get(from) || 0n)) localNonce.set(from, next); + return; + } + await sleep(500); + } +} + +// An explicit block number that is <= the floor is a block this proxy has already told the client about (or one the client +// derived from it), so some upstream has it and a lagging backend answering "beyond head" / null is only behind. +// A number above the floor is a genuine request for the future and is passed through untouched. +const isNum = (t) => typeof t === "string" && /^0x[0-9a-fA-F]+$/.test(t); +function explicitWithinFloor(req) { + const p = Array.isArray(req.params) ? req.params : []; + if (req.method === "eth_getLogs") { + const f = p[0]; + if (!f || typeof f !== "object" || f.blockHash !== undefined) return false; + const nums = [f.fromBlock, f.toBlock].filter(isNum).map((x) => BigInt(x)); + return nums.length > 0 && nums.every((n) => n <= floor); + } + if (req.method in TAG_INDEX) return isNum(p[TAG_INDEX[req.method]]) && BigInt(p[TAG_INDEX[req.method]]) <= floor; + return false; +} + +// state read pinned to the floor, retried until some upstream has that block +async function pinnedRead(req) { + const rewritten = rewrite(req); + const rw = rewritten === req && explicitWithinFloor(req) ? req : rewritten; + if (rw === req && !explicitWithinFloor(req)) return callUpstream(req); // nothing to enforce + for (let attempt = 0; ; attempt++) { + const resp = await callUpstream(rw); + const msg = resp.error ? String(resp.error.message || "") : ""; + const notYet = resp.error ? NOT_YET.test(msg) : (resp.result === null || resp.result === undefined); + if (!notYet || attempt >= 60) return { ...resp, id: req.id }; // 60 x 500ms = 30 s, then hand back what we got + stats.retries++; + if (stats.retries % 10 === 1) console.error(`[retry] ${req.method} @${rw.params && (rw.params[TAG_INDEX[req.method]] || JSON.stringify(rw.params[0]))}: ${msg || "null result"}`); + await sleep(500); + } +} + +async function handle(req) { + const m = req.method; + if (m === "eth_blockNumber") { + const resp = await callUpstream(req); + if (resp.result) { + if (startAhead > 0n && floor === 0n) bump(hex(BigInt(resp.result) + startAhead)); + bump(resp.result); resp.result = hex(floor); // never go backwards + } + return resp; + } + if (m === "eth_getTransactionReceipt") { + const resp = await callUpstream(req); + if (resp.result && resp.result.blockNumber) bump(resp.result.blockNumber); + return resp; + } + if (m === "eth_sendRawTransaction") { + const resp = await callUpstream(req); + if (resp.result && typeof resp.result === "string") await Promise.race([recordSentTx(resp.result), sleep(3000)]); + return resp; + } + if (!(m in TAG_INDEX || m === "eth_getLogs")) return callUpstream(req); + + await refreshFloor(); + if (m === "eth_getTransactionCount" && Array.isArray(req.params) && req.params[1] === "pending") { + // pending = whatever the (possibly stale) node says, the count at the floor block, and what we sent ourselves + const addr = String(req.params[0]).toLowerCase(); + const [a, b] = await Promise.all([callUpstream(req), pinnedRead({ ...req, params: [req.params[0], "latest"] })]); + let best = localNonce.get(addr) || 0n; + for (const r of [a, b]) if (r && r.result) { try { const v = BigInt(r.result); if (v > best) best = v; } catch (_) { /* ignore */ } } + return { jsonrpc: "2.0", id: req.id, result: hex(best) }; + } + return pinnedRead(req); +} + +const server = http.createServer((req, res) => { + if (req.method === "GET" && req.url === "/stats") { res.end(JSON.stringify({ floor: hex(floor), ...stats })); return; } + const chunks = []; + req.on("data", (c) => chunks.push(c)); + req.on("end", async () => { + try { + const body = JSON.parse(Buffer.concat(chunks).toString("utf8")); + stats.requests++; + const out = Array.isArray(body) ? await Promise.all(body.map(handle)) : await handle(body); + res.setHeader("content-type", "application/json"); + res.end(JSON.stringify(out)); + } catch (e) { + res.statusCode = 502; + res.end(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32603, message: "proxy error: " + e.message } })); + } + }); +}); +server.listen(port, "127.0.0.1", () => console.error(`rpc-consistency-proxy ${upstreams.join(" , ")} -> http://127.0.0.1:${port}`)); diff --git a/ops/native-hoodi/scripts/rpc-consistency-proxy.selftest.js b/ops/native-hoodi/scripts/rpc-consistency-proxy.selftest.js new file mode 100755 index 000000000..df8fe530b --- /dev/null +++ b/ops/native-hoodi/scripts/rpc-consistency-proxy.selftest.js @@ -0,0 +1,63 @@ +// Self-test for rpc-consistency-proxy.js against a fake chain. Exits non-zero on failure. +const http = require("http"); const { spawn } = require("child_process"); +const PROXY = process.argv[2] || require("path").join(__dirname, "rpc-consistency-proxy.js"); +const SENDER = "0x" + "aa".repeat(20); +let head = 100; setInterval(() => head++, 1000); // a chain at 1 block / second +const CHANGE_AT = 103; // contract state changes in block 103 +const fake = http.createServer((q, r) => { let b = ""; q.on("data", c => b += c); q.on("end", () => { + const req = JSON.parse(b); const P = req.params || []; let result = null; const hexn = n => "0x" + n.toString(16); + const tagNum = t => (t === "latest" || t === "pending" || t === undefined) ? head : parseInt(t, 16); + switch (req.method) { + case "eth_chainId": result = "0x88bb0"; break; + case "eth_getLogs": { const f = P[0] || {}; const hi = Math.max(tagNum(f.fromBlock), tagNum(f.toBlock)); + if (hi > head) { r.setHeader("content-type", "application/json"); r.end(JSON.stringify({ jsonrpc: "2.0", id: req.id, error: { code: -32000, message: "block range extends beyond current head block" } })); return; } + result = []; break; } + case "eth_blockNumber": result = hexn(head); break; + case "eth_call": { const n = tagNum(P[1]); result = n > head ? null : (n < CHANGE_AT ? "0x01" : "0x02"); break; } + case "eth_getTransactionCount": { const n = tagNum(P[1]); result = n > head ? null : "0x5"; break; } // never sees the mempool (stale node) + case "eth_sendRawTransaction": result = "0x" + "ab".repeat(32); break; + case "eth_getTransactionByHash": result = { from: SENDER, nonce: "0x5", hash: P[0] }; break; + } + r.setHeader("content-type", "application/json"); r.end(JSON.stringify({ jsonrpc: "2.0", id: req.id, result })); +}); }); +const rpc = (url, method, params = []) => fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }) }).then(r => r.json()); +const sleep = ms => new Promise(r => setTimeout(r, ms)); +(async () => { + await new Promise(r => fake.listen(19200, "127.0.0.1", r)); + const proxy = spawn("node", [PROXY, "http://127.0.0.1:19200", "19201"], { stdio: ["ignore", "ignore", "inherit"], env: { ...process.env } }); + await sleep(800); const P = "http://127.0.0.1:19201"; let failed = 0; + const check = (name, ok, detail) => { console.log((ok ? "PASS " : "FAIL ") + name + " " + detail); if (!ok) failed++; }; + + // 1) frozen-floor bug: ask for the block number ONCE, then only poll `latest` + const bn = parseInt((await rpc(P, "eth_blockNumber")).result, 16); + const t0 = Date.now(); let value = null, polls = 0; + while (Date.now() - t0 < 12000) { value = (await rpc(P, "eth_call", [{ to: "0x" + "11".repeat(20), data: "0x" }, "latest"])).result; polls++; if (value === "0x02") break; await sleep(500); } + check("polling `latest` sees the state change (floor follows the chain)", value === "0x02", `first block number seen=${bn}, change at ${CHANGE_AT}, final value=${value} after ${polls} polls, ${(Date.now() - t0)} ms`); + + // 2) pending nonce after we sent a transaction through the proxy, upstream stays stale at 5 + const before = parseInt((await rpc(P, "eth_getTransactionCount", [SENDER, "pending"])).result, 16); + await rpc(P, "eth_sendRawTransaction", ["0xdeadbeef"]); + const after = parseInt((await rpc(P, "eth_getTransactionCount", [SENDER, "pending"])).result, 16); + check("pending nonce reflects a tx we sent even if the node is stale", before === 5 && after === 6, `before=${before} after=${after} (expect 5 -> 6)`); + + // 3) latest nonce is not inflated by our local record + const latest = parseInt((await rpc(P, "eth_getTransactionCount", [SENDER, "latest"])).result, 16); + check("latest nonce unchanged", latest === 5, `latest=${latest} (expect 5)`); + + // 4) explicit block tags pass through untouched (future block -> upstream's null, immediately) + const s = Date.now(); const fut = (await rpc(P, "eth_call", [{ to: "0x" + "11".repeat(20), data: "0x" }, "0xfffff"])).result; + check("explicit future block passes straight through", fut === null && Date.now() - s < 1500, `result=${fut} in ${Date.now() - s} ms`); + + // 5) an explicit range at/below the floor that a lagging backend does not have yet is waited for, a real future range is not + const proxy2 = spawn("node", [PROXY, "http://127.0.0.1:19200", "19202"], { stdio: ["ignore", "ignore", "inherit"], env: { ...process.env, PROXY_TEST_FLOOR_AHEAD: "2" } }); + await sleep(800); const P2 = "http://127.0.0.1:19202"; + const fl = (await rpc(P2, "eth_blockNumber")).result; // primes floor = head + 2 + const t1 = Date.now(); const lg = await rpc(P2, "eth_getLogs", [{ fromBlock: fl, toBlock: fl }]); + check("explicit range <= floor is retried until the backend catches up", Array.isArray(lg.result) && Date.now() - t1 > 500, `result=${JSON.stringify(lg.result || lg.error)} after ${Date.now() - t1} ms`); + const farBlock = "0x" + (parseInt(fl, 16) + 1000).toString(16); const t2 = Date.now(); + const far = await rpc(P2, "eth_getLogs", [{ fromBlock: farBlock, toBlock: farBlock }]); + check("explicit range above the floor passes straight through (upstream's error)", far.error && /beyond/.test(far.error.message) && Date.now() - t2 < 1500, `error=${far.error && far.error.message} in ${Date.now() - t2} ms`); + proxy2.kill(); + + console.log(failed ? `\n${failed} FAILED` : "\nall passed"); proxy.kill(); fake.close(); process.exit(failed ? 1 : 0); +})(); diff --git a/ops/native-hoodi/scripts/send-tx.js b/ops/native-hoodi/scripts/send-tx.js new file mode 100755 index 000000000..b29763607 --- /dev/null +++ b/ops/native-hoodi/scripts/send-tx.js @@ -0,0 +1,30 @@ +#!/usr/bin/env node +/* + * send-tx.js — send one transaction and wait for it. The private key comes from the environment (KEY), never from the + * command line, so it does not show up in `ps`. (This cast version ignores ETH_PRIVATE_KEY for `cast send`.) + * + * Usage: KEY=0x... send-tx.js RPC_URL TO [--value-ether N] [--data 0x...] + * Needs ethers v5: it is loaded from $MORPH_CONTRACTS/node_modules (the contracts workspace of this repo). + * Exit code 0 only if the receipt has status 1. + */ +const path = require("path"); +const contracts = process.env.MORPH_CONTRACTS; +if (!contracts) { console.error("MORPH_CONTRACTS is not set"); process.exit(2); } +const ethers = require(path.join(contracts, "node_modules", "ethers")); + +const [rpc, to, ...rest] = process.argv.slice(2); +if (!rpc || !to || !process.env.KEY) { console.error("usage: KEY=0x... send-tx.js RPC_URL TO [--value-ether N] [--data 0x...]"); process.exit(2); } +const opt = (name) => { const i = rest.indexOf(name); return i >= 0 ? rest[i + 1] : undefined; }; + +(async () => { + const provider = new ethers.providers.JsonRpcProvider(rpc); + const wallet = new ethers.Wallet(process.env.KEY, provider); + const tx = { to }; + if (opt("--value-ether")) tx.value = ethers.utils.parseEther(opt("--value-ether")); + if (opt("--data")) tx.data = opt("--data"); + const sent = await wallet.sendTransaction(tx); + console.log("from", wallet.address, "to", to, "hash", sent.hash); + const receipt = await sent.wait(1); + console.log("block", receipt.blockNumber, "status", receipt.status, "gasUsed", receipt.gasUsed.toString()); + process.exit(receipt.status === 1 ? 0 : 1); +})().catch((e) => { console.error("send-tx failed:", e.message || e); process.exit(1); }); diff --git a/ops/native-hoodi/scripts/setup-nodes.py b/ops/native-hoodi/scripts/setup-nodes.py new file mode 100755 index 000000000..8c9d47099 --- /dev/null +++ b/ops/native-hoodi/scripts/setup-nodes.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +"""setup-nodes.py — 生成 2 节点(单序列器)Morph L2 的本地运行目录,不依赖 Docker。 + +改编自上游 ops/devnet-morph/devnet/setup_nodes.py,差异: + - 只做 node-0(tendermint 验证者,出块)和 node-1(layer1 校验模式,不启动 tendermint)两个节点 + - 所有路径落在 --run-dir 下;所有主机名换成 127.0.0.1;端口按 PLAN.md 第 6 节分开 + - 不依赖 PATH 里的 tendermint,用 --tendermint 指定全路径 + - 同时初始化两个 morph-geth 的数据目录(geth init)并放好 nodekey / static-nodes.json + +输出(都在 --run-dir 下): + nodes/node0, nodes/node1 tendermint / morphnode 的 home + el0, el1 morph-geth 的 datadir(已 init) + jwt-secret.txt 引擎 API 的 JWT +幂等:目标目录已存在则拒绝覆盖(不删除任何东西,换一个 --run-dir 或自行处理)。 +""" +import argparse +import base64 +import hashlib +import json +import os +import re +import shutil +import subprocess +import sys + +# 端口规划(PLAN.md 第 6 节) +EL = { + "el0": dict(http=8545, ws=8546, authrpc=8551, p2p=30303, metrics=6060), + "el1": dict(http=8645, ws=8646, authrpc=8651, p2p=30304, metrics=6061), +} +NODE0 = dict(p2p=26656, rpc=26657, prometheus=26660) + + +def node_id(node_key_path): + """tendermint 节点 ID = sha256(ed25519 公钥)前 20 字节;私钥 = seed(32) || pubkey(32)。""" + with open(node_key_path) as f: + priv = json.load(f)["priv_key"]["value"] + return hashlib.sha256(base64.b64decode(priv)[32:]).hexdigest()[:40] + + +def run(cmd, **kw): + print("+", " ".join(cmd)) + subprocess.run(cmd, check=True, **kw) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--morph", required=True, help="Morph 仓库根目录") + ap.add_argument("--run-dir", required=True, help="输出目录(必须不存在或为空)") + ap.add_argument("--genesis", required=True, help="L2 创世文件 genesis-l2.json") + ap.add_argument("--tendermint", required=True, help="tendermint 二进制的全路径") + ap.add_argument("--geth", required=True, help="morph-geth 二进制的全路径") + a = ap.parse_args() + + docker_dir = os.path.join(a.morph, "ops", "docker") + run_dir = os.path.abspath(a.run_dir) + if os.path.exists(run_dir) and os.listdir(run_dir): + sys.exit(f"{run_dir} already exists and is not empty; refusing to overwrite") + os.makedirs(run_dir, exist_ok=True) + nodes_dir = os.path.join(run_dir, "nodes") + + # ---- tendermint homes: 1 validator (node0) + 1 non-validator (node1) ---- + run([a.tendermint, "testnet", "--v", "1", "--n", "1", "--o", nodes_dir, + "--populate-persistent-peers", "--hostname", "127.0.0.1", "--hostname", "127.0.0.1"]) + + for node in ("node0", "node1"): + cfg_dir = os.path.join(nodes_dir, node, "config") + shutil.copyfile(os.path.join(docker_dir, node, "node_key.json"), os.path.join(cfg_dir, "node_key.json")) + shutil.copyfile(os.path.join(docker_dir, "tendermint-devnet-genesis.json"), os.path.join(cfg_dir, "genesis.json")) + if node == "node0": + shutil.copyfile(os.path.join(docker_dir, node, "priv_validator_key.json"), + os.path.join(cfg_dir, "priv_validator_key.json")) + else: + # only the sole genesis validator may hold a validator key; otherwise block sync is disabled + for f in (os.path.join(cfg_dir, "priv_validator_key.json"), + os.path.join(nodes_dir, node, "data", "priv_validator_state.json")): + if os.path.exists(f): + os.remove(f) + + # ---- config.toml: same tuning as upstream, ports/peers for a single host ---- + for node in ("node0", "node1"): + path = os.path.join(nodes_dir, node, "config", "config.toml") + with open(path) as f: + c = f.read() + c = c.replace('create_empty_blocks_interval = "0s"', 'create_empty_blocks_interval = "5s"') + c = c.replace('peer_gossip_sleep_duration = "100ms"', 'peer_gossip_sleep_duration = "10ms"') + c = c.replace('flush_throttle_timeout = "100ms"', 'flush_throttle_timeout = "10ms"') + c = c.replace('max_packet_msg_payload_size = 1024', 'max_packet_msg_payload_size = 10485760') + c = c.replace('send_rate = 5120000', 'send_rate = 52428800') + c = c.replace('recv_rate = 5120000', 'recv_rate = 102428800') + c = c.replace('block_sync = false', 'block_sync = true') + c = c.replace('prometheus = false', 'prometheus = true') + # only node0 runs tendermint; nobody else to dial in single-sequencer mode + c = re.sub(r'persistent_peers\s*=\s*".*?"', 'persistent_peers = ""', c) + if node == "node0": + c = c.replace('pex = true', 'pex = false') + c = re.sub(r'(\[rpc\][\s\S]*?laddr\s*=\s*)"[^"]*"', rf'\1"tcp://127.0.0.1:{NODE0["rpc"]}"', c, count=1) + c = re.sub(r'(\[p2p\][\s\S]*?laddr\s*=\s*)"[^"]*"', rf'\1"tcp://127.0.0.1:{NODE0["p2p"]}"', c, count=1) + c = re.sub(r'prometheus_listen_addr\s*=\s*"[^"]*"', f'prometheus_listen_addr = "127.0.0.1:{NODE0["prometheus"]}"', c) + with open(path, "w") as f: + f.write(c) + + # ---- morph-geth datadirs ---- + jwt_src = os.path.join(docker_dir, "jwt-secret.txt") + shutil.copyfile(jwt_src, os.path.join(run_dir, "jwt-secret.txt")) + for i, el in enumerate(("el0", "el1")): + datadir = os.path.join(run_dir, el) + os.makedirs(os.path.join(datadir, "geth"), exist_ok=True) + shutil.copyfile(os.path.join(docker_dir, f"nodekey{i}"), os.path.join(datadir, "geth", "nodekey")) + run([a.geth, "--verbosity=3", "init", f"--datadir={datadir}", a.genesis]) + + # static-nodes.json: the upstream file names containers; rewrite to loopback with our p2p ports + with open(os.path.join(docker_dir, "static-nodes.json")) as f: + static = json.load(f) + fixed = [] + for enode in static: + m = re.match(r"(enode://[0-9a-f]+)@morph-el-(\d):30303", enode) + if not m: + sys.exit(f"unexpected enode format: {enode}") + port = EL[f"el{m.group(2)}"]["p2p"] + fixed.append(f"{m.group(1)}@127.0.0.1:{port}") + with open(os.path.join(run_dir, "el1", "geth", "static-nodes.json"), "w") as f: + json.dump(fixed, f, indent=2) + + print() + print("node0 id:", node_id(os.path.join(nodes_dir, "node0", "config", "node_key.json"))) + print("done:", run_dir) + + +if __name__ == "__main__": + main() diff --git a/ops/native-hoodi/scripts/sweep-submitter.sh b/ops/native-hoodi/scripts/sweep-submitter.sh new file mode 100755 index 000000000..2ea101e83 --- /dev/null +++ b/ops/native-hoodi/scripts/sweep-submitter.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# sweep-submitter.sh — send the batch submitter's L1 balance (minus a reserve) to the deployer. Stop the stack first. +# Usage: sweep-submitter.sh [RESERVE_ETH=0.01] +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "${ROOT}/scripts/lib/env.sh" +set -a; source "${ROOT}/env/secrets.env"; set +a +RPC="${HOODI_RPC:-https://rpc.hoodi.ethpandaops.io}" +RESERVE="${1:-0.01}" +export MORPH_CONTRACTS="$(cd "${ROOT}/../../contracts" && pwd)" +SUB="$(cast wallet address --private-key "${BATCH_SUBMITTER_PRIVATE_KEY}")" +DEP="$(cast wallet address --private-key "${DEPLOYER_PRIVATE_KEY}")" +BAL="$(cast balance "${SUB}" --ether --rpc-url "${RPC}")" +AMT="$(awk -v b="${BAL}" -v r="${RESERVE}" 'BEGIN{printf "%.6f", b-r}')" +echo "submitter ${SUB}: ${BAL} ETH -> sending ${AMT} to deployer ${DEP}" +echo "deployer before: $(cast balance "${DEP}" --ether --rpc-url "${RPC}")" +KEY="${BATCH_SUBMITTER_PRIVATE_KEY}" node "${ROOT}/scripts/send-tx.js" "${RPC}" "${DEP}" --value-ether "${AMT}" +sleep 20 +echo "deployer after : $(cast balance "${DEP}" --ether --rpc-url "${RPC}")" +echo "submitter after: $(cast balance "${SUB}" --ether --rpc-url "${RPC}")" diff --git a/ops/native-hoodi/scripts/verify-l1.sh b/ops/native-hoodi/scripts/verify-l1.sh new file mode 100755 index 000000000..a4c5280a6 --- /dev/null +++ b/ops/native-hoodi/scripts/verify-l1.sh @@ -0,0 +1,92 @@ +#!/usr/bin/env bash +# +# verify-l1.sh — read the deployed Morph L1 state back from the chain and compare it with what the deployment should have +# produced. It ignores every exit code and log of the deploy steps (hardhat tasks often print an error and still exit 0). +# +# Usage: RPC_URL=... [L1_RUN=run/l1] scripts/verify-l1.sh +# Exit 0 only if every check passes. + +set -uo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +L1_RUN="${L1_RUN:-${ROOT}/run/l1}" +MORPH="${MORPH:-$(cd "${ROOT}/../.." && pwd)}" +: "${RPC_URL:?set RPC_URL}" +SECRETS="${SECRETS:-${ROOT}/env/secrets.env}" +DEPLOY_JSON="${L1_RUN}/deployment/hoodidev.json" +CFG="${MORPH}/ops/l2-genesis/deploy-config/hoodidev-deploy-config.json" +# shellcheck disable=SC1090 +source "${ROOT}/scripts/lib/env.sh" + +# addresses only, derived from the keys without putting a key on a command line +addr_of() { ( set -a; source "${SECRETS}"; set +a; cd "${MORPH}/contracts" && KEY="${!1}" node -e 'console.log(new (require("ethers").Wallet)(process.env.KEY).address)' ); } +DEPLOYER="$(addr_of DEPLOYER_PRIVATE_KEY)"; SEQUENCER="$(addr_of SEQUENCER_PRIVATE_KEY)"; SUBMITTER="$(addr_of BATCH_SUBMITTER_PRIVATE_KEY)" +L2_CHAIN_ID="$(node -e 'console.log(require(process.argv[1]).l2ChainID)' "${CFG}")" +MIN_STAKE_WEI="$(cast to-wei 0.01 ether)" + +dep() { node -e 'const d=JSON.parse(require("fs").readFileSync(process.argv[1],"utf8")).find(x=>x.name===process.argv[2]); if(!d)process.exit(1); console.log(d.address)' "${DEPLOY_JSON}" "$1"; } +call() { cast call "$1" "$2" "${@:3}" --rpc-url "${RPC_URL}" 2>&1 | awk 'NR==1{print $1}'; } +lc() { printf '%s' "${1,,}"; } + +PASS=0; FAIL=0 +check() { # check NAME ACTUAL EXPECTED + if [[ "$(lc "$2")" == "$(lc "$3")" ]]; then PASS=$((PASS + 1)); printf ' PASS %-52s %s\n' "$1" "$2" + else FAIL=$((FAIL + 1)); printf ' FAIL %-52s got %s, want %s\n' "$1" "$2" "$3"; fi +} +nonzero() { # nonzero NAME VALUE (a 32-byte value that is not all zeros / not an error) + if [[ "$2" =~ ^0x[0-9a-fA-F]{64}$ && ! "$2" =~ ^0x0{64}$ ]]; then PASS=$((PASS + 1)); printf ' PASS %-52s %s\n' "$1" "${2:0:18}…" + else FAIL=$((FAIL + 1)); printf ' FAIL %-52s got %s\n' "$1" "$2"; fi +} + +ROLLUP="$(dep Proxy__Rollup)"; MQ="$(dep Proxy__L1MessageQueueWithGasPriceOracle)"; MSGR="$(dep Proxy__L1CrossDomainMessenger)" +SUBM="$(dep Proxy__Submitter)"; SEQ="$(dep Proxy__L1Sequencer)"; PADMIN="$(dep Impl__ProxyAdmin)" +echo "L1 chain $(cast chain-id --rpc-url "${RPC_URL}"), deployer ${DEPLOYER}" +echo "Rollup ${ROLLUP} MessageQueue ${MQ} Messenger ${MSGR} Submitter ${SUBM} L1Sequencer ${SEQ} ProxyAdmin ${PADMIN}" + +echo; echo "== Rollup" +check "owner" "$(call "${ROLLUP}" 'owner()(address)')" "${DEPLOYER}" +check "LAYER_2_CHAIN_ID" "$(call "${ROLLUP}" 'LAYER_2_CHAIN_ID()(uint64)')" "${L2_CHAIN_ID}" +check "messageQueue" "$(call "${ROLLUP}" 'messageQueue()(address)')" "${MQ}" +check "submitterContract" "$(call "${ROLLUP}" 'submitterContract()(address)')" "${SUBM}" +nonzero "genesis batch imported: committedBatches(0)" "$(call "${ROLLUP}" 'committedBatches(uint256)(bytes32)' 0)" +check "lastCommittedBatchIndex" "$(call "${ROLLUP}" 'lastCommittedBatchIndex()(uint256)')" "0" +check "paused" "$(call "${ROLLUP}" 'paused()(bool)')" "false" + +echo; echo "== L1CrossDomainMessenger" +check "owner" "$(call "${MSGR}" 'owner()(address)')" "${DEPLOYER}" +check "rollup" "$(call "${MSGR}" 'rollup()(address)')" "${ROLLUP}" +check "messageQueue" "$(call "${MSGR}" 'messageQueue()(address)')" "${MQ}" +check "counterpart (L2 messenger)" "$(call "${MSGR}" 'counterpart()(address)')" "0x5300000000000000000000000000000000000007" + +echo; echo "== L1MessageQueueWithGasPriceOracle" +check "owner" "$(call "${MQ}" 'owner()(address)')" "${DEPLOYER}" +check "MESSENGER" "$(call "${MQ}" 'MESSENGER()(address)')" "${MSGR}" +check "ROLLUP_CONTRACT" "$(call "${MQ}" 'ROLLUP_CONTRACT()(address)')" "${ROLLUP}" + +echo; echo "== Submitter" +check "owner" "$(call "${SUBM}" 'owner()(address)')" "${DEPLOYER}" +check "rollupContract" "$(call "${SUBM}" 'rollupContract()(address)')" "${ROLLUP}" +check "minimumStake" "$(call "${SUBM}" 'minimumStake()(uint256)')" "${MIN_STAKE_WEI}" +check "registered(submitter)" "$(call "${SUBM}" 'registered(address)(bool)' "${SUBMITTER}")" "true" +check "stakeOf(submitter)" "$(call "${SUBM}" 'stakeOf(address)(uint256)' "${SUBMITTER}")" "${MIN_STAKE_WEI}" +check "isActive(submitter)" "$(call "${SUBM}" 'isActive(address)(bool)' "${SUBMITTER}")" "true" + +echo; echo "== L1Sequencer" +check "owner" "$(call "${SEQ}" 'owner()(address)')" "${DEPLOYER}" +check "getSequencer() is the sequencer we generated" "$(call "${SEQ}" 'getSequencer()(address)')" "${SEQUENCER}" + +echo; echo "== every proxy: has code, implementation slot = recorded Impl__, admin slot = ProxyAdmin" +IMPL_SLOT=0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc +ADMIN_SLOT=0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103 +while IFS=$'\t' read -r name addr; do + impl_name="Impl__${name#Proxy__}" + want_impl="$(dep "${impl_name}" 2>/dev/null || true)" + code="$(cast code "${addr}" --rpc-url "${RPC_URL}")" + if [[ "${code}" == "0x" ]]; then FAIL=$((FAIL + 1)); printf ' FAIL %-52s no code\n' "${name}"; continue; fi + got_impl="$(cast parse-bytes32-address "$(cast storage "${addr}" "${IMPL_SLOT}" --rpc-url "${RPC_URL}")" 2>/dev/null)" + got_admin="$(cast parse-bytes32-address "$(cast storage "${addr}" "${ADMIN_SLOT}" --rpc-url "${RPC_URL}")" 2>/dev/null)" + if [[ -n "${want_impl}" ]]; then check "${name} implementation" "${got_impl}" "${want_impl}"; else printf ' ---- %-52s no recorded Impl__ (implementation %s)\n' "${name}" "${got_impl}"; fi + check "${name} admin" "${got_admin}" "${PADMIN}" +done < <(node -e 'for (const d of JSON.parse(require("fs").readFileSync(process.argv[1],"utf8"))) if (d.name.startsWith("Proxy__")) console.log(d.name+"\t"+d.address)' "${DEPLOY_JSON}") + +echo; echo "== result: ${PASS} passed, ${FAIL} failed" +[[ "${FAIL}" -eq 0 ]] diff --git a/ops/native-hoodi/scripts/withdraw-proof.selftest.js b/ops/native-hoodi/scripts/withdraw-proof.selftest.js new file mode 100755 index 000000000..ca5b6ab22 --- /dev/null +++ b/ops/native-hoodi/scripts/withdraw-proof.selftest.js @@ -0,0 +1,24 @@ +const path = require("path"); +const ethers = require(path.join(__dirname, "..", "..", "..", "contracts", "node_modules", "ethers")); +const keccak2 = (a, b) => ethers.utils.keccak256(ethers.utils.concat([a, b])); +// --- copy of sparseProof from withdraw-test.js (extracted by regex so the test runs the real code) +const src = require("fs").readFileSync(require("path").join(__dirname, "withdraw-test.js"), "utf8"); +const fn = src.match(/function sparseProof[\s\S]*?\n}\n/)[0]; +const sparseProof = new Function("ethers", "keccak2", fn + "; return sparseProof;")(ethers, keccak2); +// --- the contract's algorithm, line by line (Tree.sol) +const ZERO = "0x" + "00".repeat(32); +class Tree { constructor(){ this.branch = Array(32).fill(ZERO); this.count = 0; } + append(leaf){ let node = leaf; const size = ++this.count; for (let h = 0; h < 32; h++) { if (((size >> h) & 1) === 1) { this.branch[h] = node; return; } node = keccak2(this.branch[h], node); } } + root(){ let node = ZERO; const size = this.count; let zh = ZERO; for (let h = 0; h < 32; h++) { node = ((size >> h) & 1) === 1 ? keccak2(this.branch[h], node) : keccak2(node, zh); zh = keccak2(zh, zh); } return node; } } +const verify = (leaf, proof, index, root) => { let node = leaf; for (let h = 0; h < 32; h++) node = ((index >> h) & 1) === 1 ? keccak2(proof[h], node) : keccak2(node, proof[h]); return node === root; }; +let bad = 0, checks = 0; +const leaves = []; +const t = new Tree(); +for (let n = 1; n <= 20; n++) { + const leaf = ethers.utils.keccak256(ethers.utils.toUtf8Bytes("leaf" + n)); leaves.push(leaf); t.append(leaf); + const contractRoot = t.root(); + for (let i = 0; i < n; i++) { const { proof, root } = sparseProof(leaves.slice(0, n), i); checks++; + if (root !== contractRoot || !verify(leaves[i], proof, i, contractRoot)) { bad++; console.log("MISMATCH n=" + n + " i=" + i); } } +} +console.log("checked", checks, "(leaf-count, index) pairs;", bad, "mismatches"); +process.exit(bad ? 1 : 0); diff --git a/ops/native-hoodi/scripts/withdraw-test.js b/ops/native-hoodi/scripts/withdraw-test.js new file mode 100755 index 000000000..cc94d0170 --- /dev/null +++ b/ops/native-hoodi/scripts/withdraw-test.js @@ -0,0 +1,128 @@ +#!/usr/bin/env node +/* + * withdraw-test.js — L2 -> L1 ETH withdrawal, end to end (P7-5). + * + * 1. On L2, the deployer calls L2GatewayRouter.withdrawETH(to, amount, gasLimit) with `to` = a brand-new L1 address. + * 2. From that receipt it reads the L2CrossDomainMessenger SentMessage event (from/to/value/nonce/message) and the + * L2ToL1MessagePasser AppendMessage event (leaf index, message hash, tree root). + * 3. It waits until the L1 Rollup lists that root as a finalized withdrawal root (i.e. the batch holding the withdrawal + * was committed and finalized on L1). + * 4. It rebuilds the depth-32 sparse Merkle tree from ALL AppendMessage events (zero hash 0x00..00, node = keccak(l||r), + * empty subtree of height h = z[h], z[h+1] = keccak(z[h]||z[h])), takes the sibling path of the leaf, and checks that it + * reproduces the on-chain root. The proof therefore does not depend on any off-chain proof service. + * 5. On L1 it calls L1CrossDomainMessenger.proveAndRelayMessage(...) and checks that the new address received the ETH. + * + * Env: KEY (deployer private key), L1_RPC, L2_RPC, L1_RUN (dir with deployment/hoodidev.json), MORPH_CONTRACTS. + * Exit 0 only if the L1 recipient's balance rose by exactly the amount. + */ +const fs = require("fs"); +const path = require("path"); +const ethers = require(path.join(process.env.MORPH_CONTRACTS, "node_modules", "ethers")); +const art = (p) => require(path.join(process.env.MORPH_CONTRACTS, "artifacts/contracts", p)).abi; + +const L1_RPC = process.env.L1_RPC || "http://127.0.0.1:18546"; +const L2_RPC = process.env.L2_RPC || "http://127.0.0.1:8545"; +const L1_RUN = process.env.L1_RUN; +const AMOUNT = ethers.utils.parseEther(process.env.AMOUNT_ETH || "0.005"); +const L1_GAS_LIMIT = Number(process.env.WITHDRAW_GAS_LIMIT || 400000); // gas for the L1 side of the relay +const TIMEOUT_MIN = Number(process.env.FINALIZE_TIMEOUT_MIN || 25); +const L2_ROUTER = "0x5300000000000000000000000000000000000002"; +const L2_MESSENGER = "0x5300000000000000000000000000000000000007"; +const L2_PASSER = "0x5300000000000000000000000000000000000001"; + +const say = (...a) => console.log(new Date().toISOString().slice(11, 19), ...a); +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const keccak2 = (a, b) => ethers.utils.keccak256(ethers.utils.concat([a, b])); + +function sparseProof(leaves, index) { + const ZERO = "0x" + "00".repeat(32); + const z = [ZERO]; + for (let h = 0; h < 32; h++) z.push(keccak2(z[h], z[h])); + let level = leaves.slice(); + let idx = index; + const proof = []; + for (let h = 0; h < 32; h++) { + const sib = idx ^ 1; + proof.push(sib < level.length ? level[sib] : z[h]); + const next = []; + for (let k = 0; k < Math.ceil(level.length / 2); k++) next.push(keccak2(level[2 * k], 2 * k + 1 < level.length ? level[2 * k + 1] : z[h])); + level = next.length ? next : [keccak2(z[h], z[h])]; + idx >>= 1; + } + return { proof, root: level[0] }; +} + +(async () => { + const deployment = JSON.parse(fs.readFileSync(path.join(L1_RUN, "deployment/hoodidev.json"), "utf8")); + const addr = (n) => deployment.find((x) => x.name === n).address; + const l1 = new ethers.providers.JsonRpcProvider(L1_RPC); + const l2 = new ethers.providers.JsonRpcProvider(L2_RPC); + const wallet2 = new ethers.Wallet(process.env.KEY, l2); + const wallet1 = new ethers.Wallet(process.env.KEY, l1); + + const router = new ethers.Contract(L2_ROUTER, art("l2/gateways/L2GatewayRouter.sol/L2GatewayRouter.json"), wallet2); + const messengerIface = new ethers.utils.Interface(art("l2/L2CrossDomainMessenger.sol/L2CrossDomainMessenger.json")); + const passerIface = new ethers.utils.Interface(art("l2/system/L2ToL1MessagePasser.sol/L2ToL1MessagePasser.json")); + const rollup = new ethers.Contract(addr("Proxy__Rollup"), art("l1/rollup/Rollup.sol/Rollup.json"), l1); + const l1Messenger = new ethers.Contract(addr("Proxy__L1CrossDomainMessenger"), art("l1/L1CrossDomainMessenger.sol/L1CrossDomainMessenger.json"), wallet1); + + const recipient = ethers.Wallet.createRandom().address; // address only: nobody holds its key + say("L1 recipient", recipient, "(balance", ethers.utils.formatEther(await l1.getBalance(recipient)), "ETH)"); + + // 1) withdraw on L2 + const tx = await router["withdrawETH(address,uint256,uint256)"](recipient, AMOUNT, L1_GAS_LIMIT, { value: AMOUNT }); + say("L2 withdraw tx", tx.hash); + const rc = await tx.wait(); + say("L2 block", rc.blockNumber, "status", rc.status, "gasUsed", rc.gasUsed.toString()); + if (rc.status !== 1) throw new Error("the L2 withdrawal transaction reverted"); + + // 2) events + const sent = rc.logs.filter((l) => l.address.toLowerCase() === L2_MESSENGER.toLowerCase()) + .map((l) => { try { return messengerIface.parseLog(l); } catch (_) { return null; } }).find((e) => e && e.name === "SentMessage"); + const appended = rc.logs.filter((l) => l.address.toLowerCase() === L2_PASSER.toLowerCase()) + .map((l) => { try { return passerIface.parseLog(l); } catch (_) { return null; } }).find((e) => e && e.name === "AppendMessage"); + if (!sent || !appended) throw new Error("SentMessage / AppendMessage not found in the receipt"); + const index = appended.args[0].toNumber(); + say("SentMessage: from", sent.args.sender, "to", sent.args.target, "value", ethers.utils.formatEther(sent.args.value), "nonce", sent.args.messageNonce.toString()); + say("AppendMessage: leaf index", index, "hash", appended.args[1].slice(0, 18) + "…", "root", appended.args[2].slice(0, 18) + "…"); + + // 3) wait until a finalized batch lists a withdrawal root that contains our leaf + // (the root grows with every later withdrawal, so try the roots of the leaf counts index+1 .. current) + const allLogs = await l2.getLogs({ address: L2_PASSER, fromBlock: 0, toBlock: "latest", topics: [passerIface.getEventTopic("AppendMessage")] }); + const parsed = allLogs.map((l) => passerIface.parseLog(l).args); + const leaves = parsed.map((a) => a[1]); + say("leaves in the L2 withdraw tree:", leaves.length); + const t0 = Date.now(); + let usable = null; + while (!usable) { + for (let n = index + 1; n <= parsed.length; n++) { + const root = parsed[n - 1][2]; // root after leaf n-1 was appended + if (await rollup.withdrawalRoots(root)) { usable = { n, root }; } // keep the newest finalized one + } + if (usable) break; + if (Date.now() - t0 > TIMEOUT_MIN * 60000) throw new Error("timed out waiting for the batch with the withdrawal to be finalized on L1"); + say("waiting for the batch to be finalized on L1 (Rollup.lastFinalizedBatchIndex =", (await rollup.lastFinalizedBatchIndex()).toString() + ")"); + await sleep(30000); + } + say("finalized withdrawal root found: covers", usable.n, "leaves,", usable.root.slice(0, 18) + "…", "after", Math.round((Date.now() - t0) / 1000), "s"); + + // 4) local proof, checked against the root + const { proof, root } = sparseProof(leaves.slice(0, usable.n), index); + if (root.toLowerCase() !== usable.root.toLowerCase()) throw new Error(`locally rebuilt root ${root} != on-chain root ${usable.root}`); + say("proof rebuilt locally; root matches the on-chain root"); + + // 5) prove and relay on L1 + const before = await l1.getBalance(recipient); + const relay = await l1Messenger.proveAndRelayMessage(sent.args.sender, sent.args.target, sent.args.value, sent.args.messageNonce, sent.args.message, proof, usable.root); + say("L1 proveAndRelayMessage tx", relay.hash); + const rr = await relay.wait(); + say("L1 block", rr.blockNumber, "status", rr.status, "gasUsed", rr.gasUsed.toString()); + const events = rr.logs.map((l) => { try { return l1Messenger.interface.parseLog(l); } catch (_) { return null; } }).filter(Boolean).map((e) => e.name); + say("L1 messenger events:", events.join(", ") || "(none)"); + await sleep(15000); + const after = await l1.getBalance(recipient); + say("L1 recipient balance:", ethers.utils.formatEther(before), "->", ethers.utils.formatEther(after), "ETH"); + const ok = after.sub(before).eq(AMOUNT) && events.includes("RelayedMessage"); + say(ok ? `OK: ${ethers.utils.formatEther(AMOUNT)} ETH withdrawn from L2 and released on L1 to ${recipient}` : "FAIL: the L1 recipient did not receive exactly the withdrawn amount"); + process.exit(ok ? 0 : 1); +})().catch((e) => { console.error("withdraw-test failed:", e.message || e); process.exit(1); }); diff --git a/ops/native-hoodi/scripts/withdraw-test.sh b/ops/native-hoodi/scripts/withdraw-test.sh new file mode 100755 index 000000000..3ea7e3f66 --- /dev/null +++ b/ops/native-hoodi/scripts/withdraw-test.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +# withdraw-test.sh — run scripts/withdraw-test.js with the deployer key taken from env/secrets.env (environment only). +# Needs the whole stack up (scripts/morph-native.sh status). Waits for the withdrawal batch to be finalized on L1. +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +MORPH="${MORPH:-$(cd "${ROOT}/../.." && pwd)}" +# shellcheck disable=SC1090 +source "${ROOT}/scripts/lib/env.sh" +set -a; source "${ROOT}/env/secrets.env"; set +a +export KEY="${DEPLOYER_PRIVATE_KEY}" MORPH_CONTRACTS="${MORPH}/contracts" L1_RUN="${L1_RUN:-${ROOT}/run/l1}" +export L1_RPC="${L1_RPC:-http://127.0.0.1:18546}" L2_RPC="${L2_RPC:-http://127.0.0.1:8545}" +exec node "${ROOT}/scripts/withdraw-test.js" From 1e8c729c8d9d4b6b94e8006004d6272c9df36812 Mon Sep 17 00:00:00 2001 From: Agnar Song Date: Wed, 25 Nov 2026 07:22:35 +0000 Subject: [PATCH 03/23] ops(native-hoodi): make dryrun-fork.sh mine blocks on its own anvil only mines when it receives a transaction. The deploy waits for later blocks (confirmations) after each transaction, so on the fork it stalled after the second contract and never finished. Start anvil with --block-time (ANVIL_BLOCK_TIME, default 1 second). Co-Authored-By: Claude Sonnet 5.5 --- ops/native-hoodi/scripts/dryrun-fork.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ops/native-hoodi/scripts/dryrun-fork.sh b/ops/native-hoodi/scripts/dryrun-fork.sh index 5c0230907..af3145a95 100755 --- a/ops/native-hoodi/scripts/dryrun-fork.sh +++ b/ops/native-hoodi/scripts/dryrun-fork.sh @@ -27,7 +27,8 @@ trap cleanup EXIT if (exec 3<>"/dev/tcp/127.0.0.1/${PORT}") 2>/dev/null; then echo "port ${PORT} is already in use" >&2; exit 1; fi echo "starting anvil fork of ${FORK_URL} on 127.0.0.1:${PORT} (chain-id 560048)" -anvil --fork-url "${FORK_URL}" --chain-id 560048 --port "${PORT}" --host 127.0.0.1 >"${RUN_DIR}/logs/anvil.log" 2>&1 & +# --block-time: without it anvil only mines on a transaction, and the deploy waits for later blocks (confirmations) forever +anvil --fork-url "${FORK_URL}" --chain-id 560048 --port "${PORT}" --host 127.0.0.1 --block-time "${ANVIL_BLOCK_TIME:-1}" >"${RUN_DIR}/logs/anvil.log" 2>&1 & echo $! >"${PIDFILE}" for _ in $(seq 1 60); do cast chain-id --rpc-url "http://127.0.0.1:${PORT}" >/dev/null 2>&1 && break From 492a15e46650ceb8d1b4d1865b8fb8c17f7cfd99 Mon Sep 17 00:00:00 2001 From: Agnar Song Date: Wed, 25 Nov 2026 07:22:52 +0000 Subject: [PATCH 04/23] ops(native-hoodi): run the challenger service as an optional native process The challenger service (#1081) can now be built and run next to the other native processes. - init-secrets.sh generates a CHALLENGER_PRIVATE_KEY (a new key per run, separate from the deployer). - register-challenger.sh adds that account to Rollup.isChallenger and tops it up (CHALLENGER_FUND_ETH, default 0.2 ETH). It is idempotent and reads each result back from the chain. deploy-l1.sh runs it as step s34 when the key is set; older secrets files skip the step. - build-all.sh builds challenger/ into bin/challenger/. - morph-native.sh gets an optional 'challenger' process: 'up challenger', or CHALLENGER_ENABLE=1 for a plain 'up'. It reads L1 through the l1-proxy and L2 from el-0 (archive node), listens on 127.0.0.1:8090 (metrics 6065) because auth is off by default, and is shown by 'status' and stopped by 'down'. - reset-env.sh --new-keys rotates the challenger key too; export-deployment.sh lists its address. The core process list and the default 'up' are unchanged. Co-Authored-By: Claude Sonnet 5.5 --- ops/native-hoodi/env/hoodi.env.example | 3 + ops/native-hoodi/scripts/build-all.sh | 4 +- ops/native-hoodi/scripts/deploy-l1.sh | 13 ++++ ops/native-hoodi/scripts/export-deployment.sh | 2 + ops/native-hoodi/scripts/init-secrets.sh | 7 +- ops/native-hoodi/scripts/morph-native.sh | 32 ++++++-- .../scripts/register-challenger.sh | 74 +++++++++++++++++++ ops/native-hoodi/scripts/reset-env.sh | 7 +- 8 files changed, 131 insertions(+), 11 deletions(-) create mode 100755 ops/native-hoodi/scripts/register-challenger.sh diff --git a/ops/native-hoodi/env/hoodi.env.example b/ops/native-hoodi/env/hoodi.env.example index 0171452ba..8119ed3a9 100644 --- a/ops/native-hoodi/env/hoodi.env.example +++ b/ops/native-hoodi/env/hoodi.env.example @@ -15,3 +15,6 @@ export DEPLOYER_PRIVATE_KEY=""${L}/p1-2-morph-geth.log" 2>&1 cp "${MORPH}/go-ethereum/build/bin/geth" "${ROOT}/bin/morph-geth/geth" @@ -15,6 +15,8 @@ step tx-submitter; ( cd "${MORPH}/tx-submitter" && make build ) >"${L}/p1-4-tx-s cp "${MORPH}/tx-submitter/tx-submitter" "${ROOT}/bin/tx-submitter/" step gas-oracle; ( cd "${MORPH}/gas-oracle" && make build ) >"${L}/p1-5-gas-oracle.log" 2>&1 cp "${MORPH}/gas-oracle/app/target/release/app" "${ROOT}/bin/gas-oracle/" +step challenger; ( cd "${MORPH}/challenger" && make build ) >"${L}/p1-5b-challenger.log" 2>&1 +cp "${MORPH}/challenger/build/bin/challenger" "${ROOT}/bin/challenger/" step contracts; ( cd "${MORPH}/contracts" && yarn install --frozen-lockfile && yarn build ) >"${L}/p1-6-contracts.log" 2>&1 step done "${ROOT}/bin/morph-geth/geth" version | sed -n 1,2p; "${ROOT}/bin/morphnode/tendermint" version diff --git a/ops/native-hoodi/scripts/deploy-l1.sh b/ops/native-hoodi/scripts/deploy-l1.sh index 50c3517e3..f76d77372 100755 --- a/ops/native-hoodi/scripts/deploy-l1.sh +++ b/ops/native-hoodi/scripts/deploy-l1.sh @@ -82,6 +82,8 @@ export ETH_RPC_URL="${RPC_URL}" for v in DEPLOYER_PRIVATE_KEY SEQUENCER_PRIVATE_KEY BATCH_SUBMITTER_PRIVATE_KEY; do [[ "${!v:-}" =~ ^0x[0-9a-fA-F]{64}$ ]] || { echo "${v} is not set to a 32-byte hex key in ${SECRETS}" >&2; exit 1; } done +# the challenger key is optional (older secrets files do not have one); if set it must be well-formed +[[ -z "${CHALLENGER_PRIVATE_KEY:-}" || "${CHALLENGER_PRIVATE_KEY}" =~ ^0x[0-9a-fA-F]{64}$ ]] || { echo "CHALLENGER_PRIVATE_KEY in ${SECRETS} is not a 32-byte hex key" >&2; exit 1; } # addr_of ENVVAR: derive an address from the key held in that variable without putting the key on a command line # (ethers from the contracts' node_modules reads the key from the environment; `cast wallet address` only takes it as an argument) @@ -217,6 +219,12 @@ s33_fund_submitter() { echo "submitter funded: $(wei_to_eth "${before}") -> $(wei_to_eth "${after}") ETH" } +s34_register_challenger() { + if [[ -z "${CHALLENGER_PRIVATE_KEY:-}" ]]; then echo "no CHALLENGER_PRIVATE_KEY in ${SECRETS}: not registering a challenger"; return 0; fi + # same RPC as this script (the consistency proxy when it is on); the deployment file is the one this run wrote + RPC_URL="${RPC_URL}" L1_RUN="${RUN_DIR}" SECRETS="${SECRETS}" MORPH="${MORPH}" "${ROOT}/scripts/register-challenger.sh" +} + s40_wait_finalized() { if [[ "${WAIT_FINALIZED}" != "1" ]]; then echo "WAIT_FINALIZED=${WAIT_FINALIZED}: skipped"; return 0; fi local target end fin @@ -245,6 +253,10 @@ s90_summary() { echo " transactions : $((n1 - n0))" echo "submitter ${SUBMITTER}" echo " balance before: $(wei_to_eth "${s0}") ETH after: $(wei_to_eth "${s1}") ETH" + if [[ -n "${CHALLENGER_PRIVATE_KEY:-}" ]]; then + CHA="$(addr_of CHALLENGER_PRIVATE_KEY)" + echo "challenger ${CHA} (Rollup.isChallenger; balance $(wei_to_eth "$(cast balance "${CHA}" --rpc-url "${RPC_URL}")") ETH)" + fi echo "L1 start block : $(cat "${STATE}/start-block.dec") ($(cat "${STATE}/start-block.hex"))" } | tee "${STATE}/summary.txt" } @@ -259,6 +271,7 @@ step s30_initialize s30_initialize step s31_register s31_register step s32_first_sequencer s32_first_sequencer step s33_fund_submitter s33_fund_submitter +step s34_register_challenger s34_register_challenger step s40_wait_finalized s40_wait_finalized s90_summary if [[ -n "${PROXY_PID:-}" ]]; then say "proxy stats: $(curl -s "http://127.0.0.1:${PROXY_PORT}/stats")"; fi diff --git a/ops/native-hoodi/scripts/export-deployment.sh b/ops/native-hoodi/scripts/export-deployment.sh index e3a791593..1dfe125dd 100755 --- a/ops/native-hoodi/scripts/export-deployment.sh +++ b/ops/native-hoodi/scripts/export-deployment.sh @@ -20,6 +20,7 @@ DEP="$(cast wallet address --private-key "${DEPLOYER_PRIVATE_KEY}")" SEQ="$(cast wallet address --private-key "${SEQUENCER_PRIVATE_KEY}")" SUB="$(cast wallet address --private-key "${BATCH_SUBMITTER_PRIVATE_KEY}")" ORA="$(cast wallet address --private-key "${L2_GAS_ORACLE_PRIVATE_KEY}")" +CHA=""; [[ -n "${CHALLENGER_PRIVATE_KEY:-}" ]] && CHA="$(cast wallet address --private-key "${CHALLENGER_PRIVATE_KEY}")" { echo "# Deployment ${NAME}"; echo echo "- exported: $(date -Is)" @@ -29,6 +30,7 @@ ORA="$(cast wallet address --private-key "${L2_GAS_ORACLE_PRIVATE_KEY}")" echo; echo "## Accounts (addresses only)"; echo echo "| role | address |"; echo "|---|---|" echo "| deployer | ${DEP} |"; echo "| sequencer | ${SEQ} |"; echo "| batch submitter | ${SUB} |"; echo "| gas oracle | ${ORA} |" + [[ -n "${CHA}" ]] && echo "| challenger | ${CHA} |" echo; echo "## Contracts (L1)"; echo; echo "| name | address |"; echo "|---|---|" node -e 'for (const x of JSON.parse(require("fs").readFileSync(process.argv[1],"utf8"))) console.log("| "+x.name+" | "+x.address+" |")' "${D}/contracts.json" echo; echo "Files: contracts.json, genesis/, versions.md, verification/ (test outputs)." diff --git a/ops/native-hoodi/scripts/init-secrets.sh b/ops/native-hoodi/scripts/init-secrets.sh index 1007ddc88..1bf5eb292 100755 --- a/ops/native-hoodi/scripts/init-secrets.sh +++ b/ops/native-hoodi/scripts/init-secrets.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# init-secrets.sh — create env/secrets.env (mode 600) from the template: your deployer key + three freshly generated keys. +# init-secrets.sh — create env/secrets.env (mode 600) from the template: your deployer key + four freshly generated keys. # The deployer key comes from the environment (DEPLOYER_PRIVATE_KEY), never from the command line. Prints only addresses. set -euo pipefail ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" @@ -16,7 +16,8 @@ def new_key(): if isinstance(out, list): out = out[0] return out["private_key"] keys = {"DEPLOYER_PRIVATE_KEY": os.environ["DEPLOYER_PRIVATE_KEY"], "SEQUENCER_PRIVATE_KEY": new_key(), - "BATCH_SUBMITTER_PRIVATE_KEY": new_key(), "L2_GAS_ORACLE_PRIVATE_KEY": new_key()} + "BATCH_SUBMITTER_PRIVATE_KEY": new_key(), "L2_GAS_ORACLE_PRIVATE_KEY": new_key(), + "CHALLENGER_PRIVATE_KEY": new_key()} text = open(src).read() for k, v in keys.items(): text, n = re.subn(r'^(export ' + k + r'=).*$', lambda m: m.group(1) + '"' + v + '"', text, flags=re.M) @@ -25,5 +26,5 @@ fd = os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, "w") as f: f.write(text) PY set -a; source "${OUT}"; set +a -for r in DEPLOYER SEQUENCER BATCH_SUBMITTER L2_GAS_ORACLE; do v="${r}_PRIVATE_KEY"; printf '%-16s %s\n' "${r}" "$(cast wallet address --private-key "${!v}")"; done +for r in DEPLOYER SEQUENCER BATCH_SUBMITTER L2_GAS_ORACLE CHALLENGER; do v="${r}_PRIVATE_KEY"; printf '%-16s %s\n' "${r}" "$(cast wallet address --private-key "${!v}")"; done echo "written ${OUT} (mode 600). Fund the DEPLOYER address with ~1.5 Hoodi ETH, then follow README.md." diff --git a/ops/native-hoodi/scripts/morph-native.sh b/ops/native-hoodi/scripts/morph-native.sh index 4c4f78627..79b5e9ffc 100755 --- a/ops/native-hoodi/scripts/morph-native.sh +++ b/ops/native-hoodi/scripts/morph-native.sh @@ -7,10 +7,12 @@ # node-2 exists only so that node-0 can be restarted: see notes/issues.md I-028 # l1-proxy 是本机的 rpc-consistency-proxy.js:所有进程访问 L1 都走它(限流时切换备用端点、读写一致性),见 notes/issues.md I-018~I-021 # node-0 是 tendermint 验证者(出块);node-1 以 layer1 校验模式运行,不启动 tendermint。 +# 可选进程 challenger(不在上面的默认列表里):比对 L1/L2 的 batch 根并在不一致时发起 challengeState。 +# 用 `up challenger` 启动,或在 env/secrets.env 里设 CHALLENGER_ENABLE=1 让 `up` 一并启动。仅监听 127.0.0.1。 # # 用法: # morph-native.sh setup 生成 tendermint / geth 运行目录(用 deploy-l1.sh 产出的创世文件) -# morph-native.sh up [NAME...] 启动全部或指定进程 +# morph-native.sh up [NAME...] 启动全部或指定进程(challenger 需显式指定或设 CHALLENGER_ENABLE=1) # morph-native.sh down 停止全部进程(保留链数据) # morph-native.sh status 进程、L2 高度、L1 同步高度、Rollup 批次 # morph-native.sh logs NAME 跟随某个进程的日志 @@ -38,6 +40,7 @@ STATE="${L2_RUN}/state" SECRETS="${SECRETS:-${ROOT}/env/secrets.env}" ALL=(l1-proxy morph-el-0 node-0 morph-el-1 node-1 morph-el-2 node-2 tx-submitter gas-price-oracle) +OPTIONAL=(challenger) # not started by a plain `up` unless CHALLENGER_ENABLE=1 CHAIN_ID=53077 JWT="${L2_RUN}/jwt-secret.txt" @@ -207,7 +210,22 @@ launch() { "GAS_ORACLE_LOG_DIR=${LOGS}/gas-oracle-files" \ -- "${BIN}/gas-oracle/app" ;; - *) die "unknown process: ${name} (one of: ${ALL[*]})" ;; + challenger) + [[ -n "${CHALLENGER_PRIVATE_KEY:-}" ]] || die "CHALLENGER_PRIVATE_KEY is not set in ${SECRETS} (see scripts/register-challenger.sh)" + [[ -x "${BIN}/challenger/challenger" ]] || die "missing ${BIN}/challenger/challenger: run scripts/build-all.sh" + # The service reads archive state from el-0 and sends challengeState through the l1-proxy. It is open (no auth) by + # default, so it only listens on 127.0.0.1. Ports 8080/6060 are avoided on purpose (see the port table in RUNBOOK.md). + spawn challenger \ + "CHALLENGER_L1_ETH_RPC=${L1_ETH_RPC}" \ + "CHALLENGER_L2_ETH_RPC=http://127.0.0.1:$(el_http 0)" \ + "CHALLENGER_ROLLUP_ADDRESS=$(addr Proxy__Rollup)" \ + "CHALLENGER_PRIVATE_KEY=${CHALLENGER_PRIVATE_KEY}" \ + "CHALLENGER_HTTP_HOSTNAME=127.0.0.1" "CHALLENGER_HTTP_PORT=${CHALLENGER_HTTP_PORT:-8090}" \ + "CHALLENGER_METRICS_SERVER_ENABLE=true" "CHALLENGER_METRICS_HOSTNAME=127.0.0.1" "CHALLENGER_METRICS_PORT=${CHALLENGER_METRICS_PORT:-6065}" \ + "CHALLENGER_LOG_TERMINAL=true" \ + -- "${BIN}/challenger/challenger" + ;; + *) die "unknown process: ${name} (one of: ${ALL[*]} ${OPTIONAL[*]})" ;; esac } @@ -225,7 +243,7 @@ cmd_setup() { # clean: never deletes anything -- it MOVES data into run/archive/-/ so a mistake can be undone. cmd_clean() { local what="${1:-}" p ts dest - for p in "${ALL[@]}"; do alive "${p}" && die "${p} is still running: run 'down' first"; done + for p in "${ALL[@]}" "${OPTIONAL[@]}"; do alive "${p}" && die "${p} is still running: run 'down' first"; done ts="$(date +%Y%m%d-%H%M%S)"; dest="${ROOT}/run/archive/${what}-${ts}" case "${what}" in logs) @@ -249,12 +267,13 @@ cmd_up() { [[ -f "${L1_RUN}/deployment/hoodidev.json" ]] || die "no L1 deployment at ${L1_RUN}/deployment/hoodidev.json" [[ -d "${L2_RUN}/nodes/node0" ]] || die "no ${L2_RUN}/nodes — run: morph-native.sh setup" load_secrets - local names=("$@"); [[ ${#names[@]} -gt 0 ]] || names=("${ALL[@]}") + local names=("$@"); [[ ${#names[@]} -gt 0 ]] || { names=("${ALL[@]}"); [[ "${CHALLENGER_ENABLE:-0}" == "1" ]] && names+=("${OPTIONAL[@]}"); } for n in "${names[@]}"; do launch "${n}"; done } cmd_down() { - local i + local i p + for p in "${OPTIONAL[@]}"; do alive "${p}" && stop_one "${p}"; done for ((i = ${#ALL[@]} - 1; i >= 0; i--)); do stop_one "${ALL[i]}"; done } @@ -265,6 +284,9 @@ cmd_status() { for n in "${ALL[@]}"; do if alive "${n}"; then printf ' %-18s running (pid %s)\n' "${n}" "$(cat "${PIDS}/${n}.pid")"; else printf ' %-18s stopped\n' "${n}"; fi done + for n in "${OPTIONAL[@]}"; do + if alive "${n}"; then printf ' %-18s running (pid %s) [optional]\n' "${n}" "$(cat "${PIDS}/${n}.pid")"; else printf ' %-18s stopped [optional]\n' "${n}"; fi + done echo ">>> L2 heights: el-0 :$(el_http 0) -> $(rpc_height "$(el_http 0)") el-1 :$(el_http 1) -> $(rpc_height "$(el_http 1)") el-2 :$(el_http 2) -> $(rpc_height "$(el_http 2)")" if [[ -f "${SECRETS}" ]]; then load_secrets diff --git a/ops/native-hoodi/scripts/register-challenger.sh b/ops/native-hoodi/scripts/register-challenger.sh new file mode 100755 index 000000000..0ae609b56 --- /dev/null +++ b/ops/native-hoodi/scripts/register-challenger.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +# +# register-challenger.sh — make the challenger account usable on an existing deployment (idempotent): +# 1. the deployer (Rollup owner) adds CHALLENGER_PRIVATE_KEY's address to Rollup.isChallenger +# 2. the deployer tops the challenger up to CHALLENGER_FUND_ETH so it can pay the challenge deposit and gas +# Each result is read back from the chain; a zero exit code from a transaction is not trusted (notes/issues.md I-022). +# +# deploy-l1.sh runs this as step s34 when CHALLENGER_PRIVATE_KEY is set. Run it by hand for a deployment made without it. +# +# Environment (all optional): +# RPC_URL L1 endpoint. Default: the local l1-proxy if it is listening, else L1_ETH_RPC from secrets +# L1_RUN deploy-l1.sh output dir (default run/l1); the Rollup address comes from its deployment/hoodidev.json +# CHALLENGER_FUND_ETH balance to keep on the challenger, in ETH (default 0.2; challengeDeposit is 0.01 on this deployment) +# SECRETS default env/secrets.env +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +MORPH="${MORPH:-$(cd "${ROOT}/../.." && pwd)}" +SECRETS="${SECRETS:-${ROOT}/env/secrets.env}" +L1_RUN="${L1_RUN:-${ROOT}/run/l1}" +FUND_ETH="${CHALLENGER_FUND_ETH:-0.2}" +# shellcheck disable=SC1090 +source "${ROOT}/scripts/lib/env.sh" +[[ -f "${SECRETS}" ]] || { echo "missing ${SECRETS}" >&2; exit 1; } +set -a +# shellcheck disable=SC1090 +source "${SECRETS}" +set +a +for v in DEPLOYER_PRIVATE_KEY CHALLENGER_PRIVATE_KEY; do + [[ "${!v:-}" =~ ^0x[0-9a-fA-F]{64}$ ]] || { + echo "${v} is not set to a 32-byte hex key in ${SECRETS}" >&2 + [[ "${v}" == "CHALLENGER_PRIVATE_KEY" ]] && echo " add one (cast wallet new), or generate a full set with scripts/init-secrets.sh on a fresh checkout" >&2 + exit 1 + } +done +export MORPH_CONTRACTS="${MORPH}/contracts" # send-tx.js loads ethers from here + +if [[ -z "${RPC_URL:-}" ]]; then + PROXY_PORT="${PROXY_PORT:-18546}" + if (exec 3<>"/dev/tcp/127.0.0.1/${PROXY_PORT}") 2>/dev/null; then RPC_URL="http://127.0.0.1:${PROXY_PORT}"; else RPC_URL="${L1_ETH_RPC:?set RPC_URL or L1_ETH_RPC}"; fi +fi +DEPLOY_JSON="${L1_RUN}/deployment/hoodidev.json" +[[ -f "${DEPLOY_JSON}" ]] || { echo "no deployment at ${DEPLOY_JSON}" >&2; exit 1; } +ROLLUP="$(node -e 'const d=JSON.parse(require("fs").readFileSync(process.argv[1],"utf8")).find(x=>x.name==="Proxy__Rollup"); if(!d){process.exit(1)} console.log(d.address)' "${DEPLOY_JSON}")" + +addr_of() { ( cd "${MORPH}/contracts" && KEY="${!1}" node -e 'console.log(new (require("ethers").Wallet)(process.env.KEY).address)' ); } +DEPLOYER="$(addr_of DEPLOYER_PRIVATE_KEY)" +CHALLENGER="$(addr_of CHALLENGER_PRIVATE_KEY)" +say() { printf '%s %s\n' "$(date +%H:%M:%S)" "$*"; } +# a read right after a mined write can hit a public-RPC node that has not seen the block: poll briefly +wait_for() { local i; for i in $(seq 1 30); do "$@" && return 0; sleep 2; done; return 1; } +is_challenger() { [[ "$(cast call "${ROLLUP}" 'isChallenger(address)(bool)' "${CHALLENGER}" --rpc-url "${RPC_URL}")" == "true" ]]; } + +owner="$(cast call "${ROLLUP}" 'owner()(address)' --rpc-url "${RPC_URL}")" +[[ "${owner,,}" == "${DEPLOYER,,}" ]] || { echo "Rollup owner ${owner} is not the deployer ${DEPLOYER}" >&2; exit 1; } + +if is_challenger; then + say "challenger ${CHALLENGER} is already on Rollup ${ROLLUP}" +else + data="$(cast calldata 'addChallenger(address)' "${CHALLENGER}")" + KEY="${DEPLOYER_PRIVATE_KEY}" node "${ROOT}/scripts/send-tx.js" "${RPC_URL}" "${ROLLUP}" --data "${data}" + wait_for is_challenger || { echo "isChallenger(${CHALLENGER}) is still false after addChallenger" >&2; exit 1; } + say "added ${CHALLENGER} to the challenger list of Rollup ${ROLLUP}" +fi + +want="$(cast to-wei "${FUND_ETH}" ether)" +has() { node -e 'process.exit(BigInt(process.argv[1]) >= BigInt(process.argv[2]) ? 0 : 1)' "$(cast balance "${CHALLENGER}" --rpc-url "${RPC_URL}")" "${want}"; } +if has; then + say "challenger balance $(cast balance "${CHALLENGER}" --ether --rpc-url "${RPC_URL}") ETH (>= ${FUND_ETH}): not funding" +else + KEY="${DEPLOYER_PRIVATE_KEY}" node "${ROOT}/scripts/send-tx.js" "${RPC_URL}" "${CHALLENGER}" --value-ether "${FUND_ETH}" + wait_for has || { echo "challenger balance is still below ${FUND_ETH} ETH after funding" >&2; exit 1; } + say "challenger funded: $(cast balance "${CHALLENGER}" --ether --rpc-url "${RPC_URL}") ETH" +fi +echo "challenger ${CHALLENGER}" diff --git a/ops/native-hoodi/scripts/reset-env.sh b/ops/native-hoodi/scripts/reset-env.sh index fd7d7790e..9b2b6d88d 100755 --- a/ops/native-hoodi/scripts/reset-env.sh +++ b/ops/native-hoodi/scripts/reset-env.sh @@ -80,9 +80,12 @@ def new_key(): if isinstance(out, list): out = out[0] return out["private_key"] text = open(src).read() -for r in roles: +optional = ["CHALLENGER_PRIVATE_KEY"] # absent in secrets files made before the challenger was added +for r in roles + optional: pat = re.compile(r'^(\s*(?:export\s+)?' + r + r'\s*=\s*).*$', re.M) - if not pat.search(text): sys.exit("role not found in secrets: " + r) + if not pat.search(text): + if r in optional: continue + sys.exit("role not found in secrets: " + r) k = new_key() text = pat.sub(lambda m: m.group(1) + k, text, count=1) open(dst, "w").write(text) From 8c12f0122bb701d4a4a870cc52c471c6d6457e1d Mon Sep 17 00:00:00 2001 From: Agnar Song Date: Wed, 25 Nov 2026 07:23:09 +0000 Subject: [PATCH 05/23] docs(native-hoodi): document running the challenger How to start the challenger, what GET /batch and POST /challenge do, the ports (8090/6065), the cost, the account setup, and the limits: it does not poll, a successful challenge freezes finalization until the owner calls revertBatch, and the committing submitter is slashed once proofWindow passes. Adds troubleshooting rows. Co-Authored-By: Claude Sonnet 5.5 --- ops/native-hoodi/README.md | 45 +++++++++++++++++++++++++++++++++---- ops/native-hoodi/RUNBOOK.md | 40 +++++++++++++++++++++++++++------ 2 files changed, 74 insertions(+), 11 deletions(-) diff --git a/ops/native-hoodi/README.md b/ops/native-hoodi/README.md index 2c6b58279..707c5cc61 100644 --- a/ops/native-hoodi/README.md +++ b/ops/native-hoodi/README.md @@ -15,6 +15,7 @@ deployed on Hoodi, and L2 batches are submitted there as EIP-4844 blob transacti │ morph-el-2 ◀▶ node-2 full node with tendermint, no sequencer key; required so node-0 can restart │ tx-submitter submits batches to the Rollup on Hoodi and finalizes them │ gas-price-oracle writes L1 fees into the L2 GasPriceOracle + │ challenger (optional) HTTP service: compares batch roots with el-0 and sends Rollup.challengeState on a mismatch └──────────────────────────────────────────────────────────────────────────────┘ ``` @@ -37,14 +38,15 @@ Four small, already-committed changes on this branch (everything else is in this | Build tools | Go ≥ 1.24 (tested 1.25.7), Rust (tested 1.95; needs OpenSSL headers + pkg-config), Node + yarn 1.x (tested Node 24, yarn 1.22), make, gcc | | Runtime tools | Node ≥ 18, Python ≥ 3.9, curl, Foundry `cast` and `anvil` (tested 1.9.0) | | Network | outbound HTTPS to the Hoodi RPC and beacon endpoints (no inbound ports) | -| **Hoodi ETH** | **about 1.5 ETH in your deployer account**: ~0.07 for gas, 1 ETH is passed on to the batch submitter (which then spends ~0.09 ETH/day). Faucet: https://hoodi.ethpandaops.io | +| **Hoodi ETH** | **about 1.5 ETH in your deployer account**: ~0.07 for gas, 1 ETH is passed on to the batch submitter (which then spends ~0.09 ETH/day), 0.2 ETH to the challenger (`CHALLENGER_FUND_ETH`). Faucet: https://hoodi.ethpandaops.io | | A deployer key | one private key you control and fund. Other keys are generated for you | If your tools are not on `PATH` by default, put the `PATH`/build settings in a file and `export MORPH_ENV_FILE=/path/to/that/file`; every script sources it first (`scripts/lib/env.sh`) and prints exactly what is missing if a tool is absent. Ports used on 127.0.0.1 (stop other local devnets first): 18546, 8545/8546/8551, 8645/8646/8651, 8745/8746/8751, -30303-30305, 26656/26657/26660, 26666/26667/26670, 27660, 6160-6162, 6070, 8060. +30303-30305, 26656/26657/26660, 26666/26667/26670, 27660, 6160-6162, 6070, 8060, and 8090 / 6065 if you run the challenger +(`CHALLENGER_HTTP_PORT` / `CHALLENGER_METRICS_PORT`; not its defaults 8080 / 6060, which are commonly taken). ## 3. From zero to a running chain @@ -54,7 +56,8 @@ All commands from this directory (`ops/native-hoodi/`). # 1. build all binaries into ./bin (about 5-10 minutes the first time) scripts/build-all.sh -# 2. keys: your funded deployer key + three generated ones. Prints addresses only. Then fund the DEPLOYER address. +# 2. keys: your funded deployer key + four generated ones (sequencer, batch submitter, gas oracle, challenger). Prints +# addresses only. Then fund the DEPLOYER address. DEPLOYER_PRIVATE_KEY=0x... scripts/init-secrets.sh # 3. (optional, free) rehearse the whole L1 deployment on a local anvil fork of Hoodi (~5 minutes when the RPC behaves). @@ -67,12 +70,17 @@ scripts/dryrun-fork.sh source env/secrets.env RPC_URL="$L1_ETH_RPC" RUN_DIR="$PWD/run/l1" WAIT_FINALIZED=1 SUBMITTER_FUND_ETH=1 scripts/deploy-l1.sh RPC_URL="$L1_ETH_RPC" scripts/verify-l1.sh # reads the chain: expect "53 passed, 0 failed" +# deploy-l1.sh also runs step s34: it adds the challenger to Rollup.isChallenger and tops it up to 0.2 ETH. The step is +# skipped when env/secrets.env has no CHALLENGER_PRIVATE_KEY; for an older deployment run scripts/register-challenger.sh. # 5. create the node directories, start everything, bootstrap L2 balances and the gas-oracle permission scripts/morph-native.sh setup scripts/morph-native.sh up scripts/l2-bootstrap.sh scripts/morph-native.sh status + +# 6. (optional) the challenger, see section 4a. It is not started by a plain `up` unless CHALLENGER_ENABLE=1 is set in env/secrets.env +scripts/morph-native.sh up challenger ``` Do not trust a hardhat task's exit code: they often print an error and exit 0. `verify-l1.sh` reads the actual on-chain state. @@ -89,6 +97,33 @@ cast call $ROLLUP 'lastCommittedBatchIndex()(uint256)' --rpc-url "$L1_ETH_RPC" cast call $ROLLUP 'lastFinalizedBatchIndex()(uint256)' --rpc-url "$L1_ETH_RPC" ``` +### 4a. The challenger (optional) + +The challenger is the `challenger/` service of this repo (built into `bin/challenger/challenger` by `scripts/build-all.sh`). +It is an HTTP service, not a watcher: it acts only when it is asked. + +- `GET /batch/{index}` reads the batch's commit transaction on L1 and the same block on el-0 and compares the state root and + the withdraw root. `"verdict":"match"` while the chain is honest; `mismatch` or `inconclusive` otherwise. It sends nothing. +- `POST /challenge` with `{"batchIndex":N,"batchHash":"0x..."}` sends `Rollup.challengeState` **only** when that exact batch + hash is the one committed on L1 and the roots differ. Everything else is refused with a 4xx and no transaction. +- It listens on `127.0.0.1:8090` (metrics `127.0.0.1:6065`) with auth off, reads the L1 through the l1-proxy and the L2 from + el-0. el-0 is an archive node (`--gcmode=archive`), which the withdraw-root read needs. +- The account is `CHALLENGER_PRIVATE_KEY` from `env/secrets.env`, a new key per `init-secrets.sh` run (it is not the deployer). + `deploy-l1.sh` (step s34) or `scripts/register-challenger.sh` adds it to `Rollup.isChallenger` and funds it. + +```bash +scripts/morph-native.sh up challenger # needs bin/challenger/challenger and the key above +scripts/morph-native.sh status # lists challenger as [optional] +curl -s http://127.0.0.1:8090/health # {"status":"ok"} +FIN=$(cast call $ROLLUP 'lastFinalizedBatchIndex()(uint256)' --rpc-url "$L1_ETH_RPC") +curl -s http://127.0.0.1:8090/batch/$FIN # 409 "batch already finalized": finalized batches are refused +curl -s http://127.0.0.1:8090/batch/$((FIN + 1)) # "verdict":"match" for a committed, not yet finalized batch (404 if there is none yet) +``` + +A successful challenge is a real transaction that locks the challenge deposit and stops finalization until the Rollup owner +calls `revertBatch`; once `proofWindow` has passed, the submitter that committed the batch can be slashed. Run it only on +purpose. All options are in `challenger/env.example`. + End-to-end tests (each uses a few mETH; read the header of each script): | script | what it proves | time | @@ -104,6 +139,7 @@ End-to-end tests (each uses a few mETH; read the header of each script): |---|---| | `scripts/morph-native.sh status|up|down|logs NAME|kill NAME|start NAME` | operate the stack; `down` keeps chain data | | `scripts/reset-env.sh plan|run|restore|list` | move run data (and with `--with-build` the binaries, with `--new-keys` the keys) into `run/archive/`; nothing is deleted. A new L2 genesis needs a new L1 deployment | +| `scripts/register-challenger.sh` | add `CHALLENGER_PRIVATE_KEY`'s address to `Rollup.isChallenger` and top it up (idempotent; `deploy-l1.sh` runs it as step s34) | | `scripts/sweep-submitter.sh` | send the submitter's remaining Hoodi ETH back to the deployer (stack must be down) | | `scripts/export-deployment.sh NAME` | save contract addresses, genesis files and test outputs (no private keys) to `deployments/NAME/` | | `scripts/check-no-secrets.sh` | run before committing: fails if anything looks like a private key | @@ -115,5 +151,6 @@ End-to-end tests (each uses a few mETH; read the header of each script): - Do not remove node-2: after a restart node-0 only resumes block production if it has a tendermint peer (`notes/issues.md` I-028). - Resetting the L2 means redeploying L1: the Rollup on Hoodi is bound to this chain's batches. Old deployments stay on Hoodi as orphan contracts. - Deposit gas limits must be generous (use ≥ 400000), see `RUNBOOK.md` section 7. -- Not covered: HA sequencer cluster, reth, multi-day soak, several withdrawals in one batch. +- The challenger does not poll: nothing challenges automatically. Something has to `POST /challenge`. +- Not covered: HA sequencer cluster, reth, multi-day soak, several withdrawals in one batch, the challenger with an external signer. - L2 chain id 53077 is shared with other Morph-style devnets; do not join them. diff --git a/ops/native-hoodi/RUNBOOK.md b/ops/native-hoodi/RUNBOOK.md index d358c74c5..9c5f3914b 100644 --- a/ops/native-hoodi/RUNBOOK.md +++ b/ops/native-hoodi/RUNBOOK.md @@ -17,14 +17,15 @@ │ morph-el-2 ◀▶ node-2 全节点:跑 tendermint,没有出块密钥。**只为让 node-0 能重启** │ │ tx-submitter 把 L2 批次提交到 Hoodi 的 Rollup,并最终化 │ │ gas-price-oracle 把 L1 费用写入 L2 的 GasPriceOracle │ + │ challenger(可选) 比对批次根,不一致时发起 Rollup.challengeState │ └────────────────────────────────────────────────────────────────────────────────┘ ``` ## 2. 前置条件 - 构建环境见 README 第 2 节。所有脚本通过 `scripts/lib/env.sh` 检查工具链;工具不在 PATH 上时,用环境变量 `MORPH_ENV_FILE` 指向一个设置 PATH 的文件。手工调用 `cast` 时需要自己保证它在 PATH 上。 -- 二进制在 `bin/`:`morph-geth/geth`、`morphnode/morphnode`、`morphnode/tendermint`、`tx-submitter/tx-submitter`、`gas-oracle/app`(构建方法见 `notes/versions.md` 和 `TODO.md` 的 P1)。 -- 密钥在 `env/secrets.env`(权限 600,**不要提交、不要贴到任何地方**),模板是 `env/hoodi.env.example`。4 个角色:deployer、sequencer、batch submitter、gas oracle。 +- 二进制在 `bin/`:`morph-geth/geth`、`morphnode/morphnode`、`morphnode/tendermint`、`tx-submitter/tx-submitter`、`gas-oracle/app`、`challenger/challenger`(构建方法见 `notes/versions.md` 和 `TODO.md` 的 P1;`build-all.sh` 一并构建)。 +- 密钥在 `env/secrets.env`(权限 600,**不要提交、不要贴到任何地方**),模板是 `env/hoodi.env.example`。5 个角色:deployer、sequencer、batch submitter、gas oracle、challenger(可选,`init-secrets.sh` 每次生成新的)。 ## 3. 日常操作 @@ -32,15 +33,15 @@ | 命令 | 作用 | |---|---| -| `status` | 9 个进程、三个 L2 的高度、Hoodi 高度、代理统计、Rollup 已提交批次 | -| `up [NAME...]` | 启动全部或指定进程(按依赖顺序) | -| `down` | 停止全部进程,**保留链数据** | +| `status` | 9 个进程(加可选的 challenger)、三个 L2 的高度、Hoodi 高度、代理统计、Rollup 已提交批次 | +| `up [NAME...]` | 启动全部或指定进程(按依赖顺序)。`challenger` 不在默认列表里:用 `up challenger` 启动,或在 `env/secrets.env` 设 `CHALLENGER_ENABLE=1` | +| `down` | 停止全部进程(含 challenger),**保留链数据** | | `kill NAME` / `start NAME` | 停 / 启动单个进程(`kill` 后不会被自动重启) | | `logs NAME` | 跟随某个进程的日志(文件在 `run/l2/logs/`) | | `setup` | 用 `deploy-l1.sh` 产出的创世文件生成运行目录(含 node-2) | | `clean logs` / `clean l2` | **不删除**,只把数据挪到 `run/archive/`。`clean l2` 有重要后果,见第 7 节 | -进程名:`l1-proxy morph-el-0 node-0 morph-el-1 node-1 morph-el-2 node-2 tx-submitter gas-price-oracle`。每个进程都在一个自动重启的守护外壳里,崩溃后 2 秒内被拉起。 +进程名:`l1-proxy morph-el-0 node-0 morph-el-1 node-1 morph-el-2 node-2 tx-submitter gas-price-oracle`,另有可选的 `challenger`。每个进程都在一个自动重启的守护外壳里,崩溃后 2 秒内被拉起。 ## 4. 端口(全部 127.0.0.1) @@ -55,8 +56,9 @@ | tx-submitter | | | | | 8060 | | gas-price-oracle | | | | | 6070 | | l1-proxy | 18546(`/stats` 看统计) | | | | | +| challenger(可选) | 8090 | | | | 6065 | -geth 的 metrics 端口用 6160 起,是因为有些环境里 6060 已被占用。**这些端口(8545、8551、30303 等)与其他本地以太坊 devnet 常用端口相同**,不能同时跑;先 `down` 或换端口。 +geth 的 metrics 端口用 6160 起,是因为有些环境里 6060 已被占用;challenger 同理避开它默认的 8080 / 6060(用 `CHALLENGER_HTTP_PORT` / `CHALLENGER_METRICS_PORT` 可改)。**这些端口(8545、8551、30303 等)与其他本地以太坊 devnet 常用端口相同**,不能同时跑;先 `down` 或换端口。 ## 5. 从零开始的流程 @@ -68,9 +70,11 @@ geth 的 metrics 端口用 6160 起,是因为有些环境里 6060 已被占用 RPC_URL=https://rpc.hoodi.ethpandaops.io scripts/verify-l1.sh # 读链上状态核对,不信退出码 ``` 约 20 分钟(其中约 13 分钟是等 Hoodi finalized)。**在公共链上花测试币、不可撤销。** + `deploy-l1.sh` 最后还会跑 s34:把 challenger 加入 `Rollup.isChallenger` 并充值到 0.2 ETH(`CHALLENGER_FUND_ETH`)。`env/secrets.env` 里没有 `CHALLENGER_PRIVATE_KEY` 时跳过;已有的旧部署用 `scripts/register-challenger.sh` 补做。 4. `scripts/morph-native.sh setup`,然后 `up`。 5. `scripts/l2-bootstrap.sh`:给 deployer 和 oracle 在 L2 上转余额,并把 oracle 密钥加入 GasPriceOracle 白名单(否则 gas-price-oracle 没权限更新)。 6. 用第 6 节的脚本验证。 +7. (可选)`scripts/morph-native.sh up challenger`,按第 6 节“挑战者”验证。 ## 6. 验证脚本 @@ -83,9 +87,26 @@ geth 的 metrics 端口用 6160 起,是因为有些环境里 6060 已被占用 | `scripts/rpc-consistency-proxy.selftest.js` | 代理的 6 项行为(不碰网络) | 10 秒 | | `scripts/withdraw-proof.selftest.js` | 默克尔证明算法与合约逐行一致(210 组) | 5 秒 | | `scripts/probe-hoodi.sh` | 公共 RPC 的限流探测 | 1 分钟 | +| `scripts/register-challenger.sh` | 把 challenger 加入 `Rollup.isChallenger` 并充值(幂等,读回链上结果确认;`deploy-l1.sh` 的 s34 就是它) | 1 分钟 | 比较 node-1 与 node-0 是否一致,用 `cast block N --field hash --rpc-url http://127.0.0.1:8545 / 8645 / 8745` 逐块比对(已在三个节点间比过 0 到 7562 共 7563 个块,0 个不一致)。 +**挑战者(可选)。** challenger 是个 HTTP 服务,**不会自己轮询**,只在被请求时才动作: + +- `GET /batch/{index}`:读该批次在 L1 的提交交易和 el-0 上同一个块,比对 state root 与 withdraw root。链正常时返回 `"verdict":"match"`,否则 `mismatch` / `inconclusive`。不发交易。 +- `POST /challenge`,body `{"batchIndex":N,"batchHash":"0x..."}`:**只有**该 hash 正是 L1 上当前提交的那个、且根不一致时才发 `Rollup.challengeState`;其它情况都返回 4xx、不发交易。 +- 监听 `127.0.0.1:8090`(无鉴权,所以只绑本机),指标 `127.0.0.1:6065`;L1 走 l1-proxy,L2 读 el-0(归档节点,`--gcmode=archive`,读 withdraw root 需要)。账户是 `env/secrets.env` 里的 `CHALLENGER_PRIVATE_KEY`(不是 deployer)。 + +```bash +scripts/morph-native.sh up challenger +curl -s http://127.0.0.1:8090/health # {"status":"ok"} +FIN=$(cast call $ROLLUP 'lastFinalizedBatchIndex()(uint256)' --rpc-url "$L1_ETH_RPC") +curl -s http://127.0.0.1:8090/batch/$FIN # 409 "batch already finalized" +curl -s http://127.0.0.1:8090/batch/$((FIN + 1)) # 已提交未 finalized 的批次:"verdict":"match"(还没有则 404) +``` + +成功的挑战是一笔真实交易:锁定保证金(`challengeDeposit`),并让 finalize 停住,直到 Rollup owner 调 `revertBatch`;超过 `proofWindow` 后,提交该批次的 submitter 会被罚没。不要随手发。全部配置项见 `challenger/env.example`。 + ## 7. 必须知道的限制和坑 1. **node-2 不能去掉。** 出块节点 node-0 重启后,必须有至少一个 tendermint 对端它才会恢复出块;没有时它静默停转(进程在、RPC 在、日志无错误、高度冻结)。node-1 是 layer1 校验模式,不算 tendermint 对端。见 `notes/issues.md` I-028。 @@ -95,6 +116,7 @@ geth 的 metrics 端口用 6160 起,是因为有些环境里 6060 已被占用 5. **node-1 不是实时的。** 它按批次推进,批次提交到 L1 后才前进,所以总会落后几百个块(约一个批次)。 6. **不要把 `hardhat` 任务的退出码当成功。** 它们出错时常常只打印一行然后退出码为 0。部署后用 `verify-l1.sh` 读链上状态。 7. **改动在 git 里。** 对上游仓库的改动只有 4 个文件:`contracts/hardhat.config.ts`(加网络 `hoodidev`)、`contracts/src/deploy-config/hoodidev.ts`、`ops/l2-genesis/deploy-config/hoodidev-deploy-config.json`、`contracts/src/deploy-utils.ts`(可选的读重试)。 +8. **challenger 不会自动挑战。** 它不轮询 L1,必须有人 `POST /challenge`。挑战成功后 finalize 会停住,需要 owner `revertBatch` 收尾;`proofWindow` 过后调 `proveState` 判挑战方胜,会罚没提交该批次的 submitter 并让合约进入 `pending revert request`。 ## 8. 成本(实测) @@ -102,6 +124,7 @@ geth 的 metrics 端口用 6160 起,是因为有些环境里 6060 已被占用 |---|---| | L1 合约部署 | 77 笔交易、5130 万 gas;按 1 gwei 约 0.06 ETH(含 0.01 ETH 的 submitter 质押) | | tx-submitter 运行 | 约 0.0004 ETH / 批次;批次约每 7 分钟一个,约 0.09 ETH / 天 | +| challenger 充值 | 部署时转 0.2 ETH(`CHALLENGER_FUND_ETH`);一次挑战锁定 0.01 ETH 保证金 + 约 0.0002 ETH gas | | 部署期间的损耗 | 前几次失败遗留的孤儿合约,合计不到 0.2 ETH | ## 9. 故障排查 @@ -114,6 +137,9 @@ geth 的 metrics 端口用 6160 起,是因为有些环境里 6060 已被占用 | gas-price-oracle 报 `ErrCallerNotAllowed` | 没跑 `l2-bootstrap.sh`,oracle 不在白名单 | | 存款后 L2 没到账,但 L1 消息已入队 | 在 L2 上找类型 `0x7e` 的交易看回执:状态 0 通常是 `_gasLimit` 太小 | | 起不来,端口被占 | 先 `scripts/morph-native.sh down`;本机上别的 devnet 或节点在用同样的端口也会冲突(`ss -ltn` 查) | +| `up challenger` 报缺 `CHALLENGER_PRIVATE_KEY` / `bin/challenger/challenger` | 旧的 `env/secrets.env` 没有该密钥(加一把 `cast wallet new`,再跑 `register-challenger.sh`);二进制要先跑 `build-all.sh` | +| `POST /challenge` 返回 `only challenger allowed` | challenger 账户没加入 `Rollup.isChallenger`:跑 `scripts/register-challenger.sh` | +| challenger 进程反复重启 | 看 `logs challenger`:L2 RPC 的链与 Rollup 对不上时它拒绝启动;确认 el-0 在跑、`L1_RUN` 指向当前部署 | ## 10. 重置与部署记录(2026-11-19 新增,已用这套流程完整重做过一次) From 34a20e8fb8ae1c8ab20755617c73b27bdaddd740 Mon Sep 17 00:00:00 2001 From: Agnar Song Date: Wed, 25 Nov 2026 22:43:26 +0000 Subject: [PATCH 06/23] ops(native-hoodi): top the challenger up to the target balance register-challenger.sh sent the whole CHALLENGER_FUND_ETH whenever the balance was below it, so an account that already held some ETH ended up above the target (0.05 ETH + 0.2 ETH = 0.25 ETH on a fork run). It now sends only the difference. Co-Authored-By: Claude Sonnet 5.5 --- ops/native-hoodi/scripts/register-challenger.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ops/native-hoodi/scripts/register-challenger.sh b/ops/native-hoodi/scripts/register-challenger.sh index 0ae609b56..e2db0d076 100755 --- a/ops/native-hoodi/scripts/register-challenger.sh +++ b/ops/native-hoodi/scripts/register-challenger.sh @@ -67,7 +67,9 @@ has() { node -e 'process.exit(BigInt(process.argv[1]) >= BigInt(process.argv[2]) if has; then say "challenger balance $(cast balance "${CHALLENGER}" --ether --rpc-url "${RPC_URL}") ETH (>= ${FUND_ETH}): not funding" else - KEY="${DEPLOYER_PRIVATE_KEY}" node "${ROOT}/scripts/send-tx.js" "${RPC_URL}" "${CHALLENGER}" --value-ether "${FUND_ETH}" + # send only the difference, so the balance ends at CHALLENGER_FUND_ETH + top_up="$(cast from-wei "$(node -e 'console.log((BigInt(process.argv[1]) - BigInt(process.argv[2])).toString())' "${want}" "$(cast balance "${CHALLENGER}" --rpc-url "${RPC_URL}")")")" + KEY="${DEPLOYER_PRIVATE_KEY}" node "${ROOT}/scripts/send-tx.js" "${RPC_URL}" "${CHALLENGER}" --value-ether "${top_up}" wait_for has || { echo "challenger balance is still below ${FUND_ETH} ETH after funding" >&2; exit 1; } say "challenger funded: $(cast balance "${CHALLENGER}" --ether --rpc-url "${RPC_URL}") ETH" fi From a4e4683bc65aa695bf1cc335a25c7f4594f02304 Mon Sep 17 00:00:00 2001 From: Agnar Song Date: Wed, 25 Nov 2026 22:44:27 +0000 Subject: [PATCH 07/23] ops(native-hoodi): take owner, admin and fee-recipient addresses from the deployer key hoodidev.ts and the L2 genesis config had one account's address written into them (contract admin, Submitter owner, challenger, L1/L2 fee recipients, token and oracle owners). Anyone else deploying got a chain whose L2 genesis owners were not theirs. - hoodidev.ts reads MORPH_DEPLOYER_ADDRESS, MORPH_CHALLENGER_ADDRESS and MORPH_BATCH_SUBMITTER_ADDRESS; an empty value is rejected by the deploy tasks instead of silently using another address. - The genesis config keeps a REPLACE_WITH_DEPLOYER_ADDRESS placeholder (like l1StartingBlockTag); deploy-l1.sh s00_preflight fills it into the generated copy and stops if any placeholder is left. - deploy-l1.sh derives the addresses from env/secrets.env, refuses the public Anvil key, checks the deployer balance covers the run, and prints who will own the deployment. rollupChallenger is the generated challenger (the deployer when no challenger key is configured). - s31_register reads Submitter.isActive back: the hardhat task exits 0 even when it fails, which is what happens when the Submitter owner is not the deployer. - init-secrets.sh validates the deployer key and refuses the public Anvil key. The sequencer set and the Tendermint and BLS keys are unchanged. Checked with two fork dry runs: the existing deployer, and a throwaway one (all eleven steps, owners follow the key, no leftover address or placeholder in the generated config, submitter active). Co-Authored-By: Claude Sonnet 5.5 --- contracts/src/deploy-config/hoodidev.ts | 16 ++++++--- .../deploy-config/hoodidev-deploy-config.json | 16 ++++----- ops/native-hoodi/README.md | 8 ++++- ops/native-hoodi/RUNBOOK.md | 5 +-- ops/native-hoodi/scripts/deploy-l1.sh | 35 ++++++++++++++++--- ops/native-hoodi/scripts/init-secrets.sh | 3 ++ 6 files changed, 63 insertions(+), 20 deletions(-) diff --git a/contracts/src/deploy-config/hoodidev.ts b/contracts/src/deploy-config/hoodidev.ts index 99a215b91..9a153bac2 100644 --- a/contracts/src/deploy-config/hoodidev.ts +++ b/contracts/src/deploy-config/hoodidev.ts @@ -1,9 +1,14 @@ // hoodidev: a private Morph L2 (chain 53077) whose L1 is the public Ethereum Hoodi testnet (chain 560048). // Derived from l1.ts (the local devnet). Do NOT reuse hoodi.ts: that is Morph's official Hoodi deployment. +// Addresses that follow whoever runs the deploy come from the environment, not from this file: deploy-l1.sh derives them +// from the keys in env/secrets.env and exports them. An empty value is rejected by the deploy tasks (isAddress checks, or the +// contract constructor), so a missing variable stops the run instead of silently using someone else's address. +const addr = (name: string): string => process.env[name] || '' + const config = { // Global configuration - contractAdmin: '0x2d66b081246b93caC31dEdC03421ee863AE0624D', - l1FeeVaultRecipient: '0x2d66b081246b93caC31dEdC03421ee863AE0624D', + contractAdmin: addr('MORPH_DEPLOYER_ADDRESS'), + l1FeeVaultRecipient: addr('MORPH_DEPLOYER_ADDRESS'), l1WETHAddress: "", l1USDCAddress: "", @@ -28,8 +33,9 @@ const config = { rollupDelayPeriod: 86400, // challenge config - batchSubmitterAddresses: ['0x988709F4B219faC95440CEF25F2c50c554201008'], - rollupChallenger: '0x2d66b081246b93caC31dEdC03421ee863AE0624D', + // `register` uses the keys in $batchSubmitterPks when they are set (deploy-l1.sh does); this list is only the fallback. + batchSubmitterAddresses: process.env.MORPH_BATCH_SUBMITTER_ADDRESS ? [process.env.MORPH_BATCH_SUBMITTER_ADDRESS] : [], + rollupChallenger: addr('MORPH_CHALLENGER_ADDRESS'), // genesis config // The genesis batch header comes out of the L2 genesis tool, so it is passed in through MORPH_BATCH_HEADER instead of // being rewritten into this file (l1.ts is rewritten in place by the devnet's main.py). Empty means "not generated yet": @@ -37,7 +43,7 @@ const config = { batchHeader: process.env.MORPH_BATCH_HEADER || '', // submitter initialize config - submitterOwner: '0x2d66b081246b93caC31dEdC03421ee863AE0624D', + submitterOwner: addr('MORPH_DEPLOYER_ADDRESS'), submitterChallengeDeposit: 0.01, // 0.01 ether (devnet: l1.ts uses 1) submitterMinimumStake: 0.01, // 0.01 ether (devnet: l1.ts uses 1); `register` stakes this from the owner submitterRewardPercentage: 100, diff --git a/ops/l2-genesis/deploy-config/hoodidev-deploy-config.json b/ops/l2-genesis/deploy-config/hoodidev-deploy-config.json index a1c700acd..b6c32e598 100644 --- a/ops/l2-genesis/deploy-config/hoodidev-deploy-config.json +++ b/ops/l2-genesis/deploy-config/hoodidev-deploy-config.json @@ -1,28 +1,28 @@ { "l1ChainID": 560048, "l2ChainID": 53077, - "finalSystemOwner": "0x2d66b081246b93caC31dEdC03421ee863AE0624D", - "proxyAdminOwner": "0x2d66b081246b93caC31dEdC03421ee863AE0624D", + "finalSystemOwner": "REPLACE_WITH_DEPLOYER_ADDRESS", + "proxyAdminOwner": "REPLACE_WITH_DEPLOYER_ADDRESS", "BLOCK_SIGNER_ADDRESS": "0xaEcFF2a7E677cEFa56643Ff0aD06e233a3FdC402", - "l1FeeVaultRecipient": "0x2d66b081246b93caC31dEdC03421ee863AE0624D", - "sequencerFeeVaultRecipient": "0x2d66b081246b93caC31dEdC03421ee863AE0624D", - "l2BridgeFeeVaultRecipient": "0x2d66b081246b93caC31dEdC03421ee863AE0624D", + "l1FeeVaultRecipient": "REPLACE_WITH_DEPLOYER_ADDRESS", + "sequencerFeeVaultRecipient": "REPLACE_WITH_DEPLOYER_ADDRESS", + "l2BridgeFeeVaultRecipient": "REPLACE_WITH_DEPLOYER_ADDRESS", "fundDevAccounts": true, "l1StartingBlockTag": "REPLACE_WITH_HOODI_START_BLOCK_HEX", "maxTxPerBlock": 1000, "maxTxPayloadBytesPerBlock": 737280, "gasPriceOracleOverhead": 2500, "gasPriceOracleScalar": 1000000000, - "gasPriceOracleOwner": "0x2d66b081246b93caC31dEdC03421ee863AE0624D", + "gasPriceOracleOwner": "REPLACE_WITH_DEPLOYER_ADDRESS", "govVotingDuration": 1000, "govBatchBlockInterval": 200, "govBatchTimeout": 600, "govRollupEpoch": 100, - "recordOracleAddress": "0x2d66b081246b93caC31dEdC03421ee863AE0624D", + "recordOracleAddress": "REPLACE_WITH_DEPLOYER_ADDRESS", "recordNextBatchSubmissionIndex": 1, "morphTokenName": "Morph Token", "morphTokenSymbol": "Morph", - "morphTokenOwner": "0x2d66b081246b93caC31dEdC03421ee863AE0624D", + "morphTokenOwner": "REPLACE_WITH_DEPLOYER_ADDRESS", "morphTokenInitialSupply": 1000000000, "morphTokenDailyInflationRate": 1, "morph203Time": 0, diff --git a/ops/native-hoodi/README.md b/ops/native-hoodi/README.md index 707c5cc61..99dd02367 100644 --- a/ops/native-hoodi/README.md +++ b/ops/native-hoodi/README.md @@ -28,6 +28,12 @@ Four small, already-committed changes on this branch (everything else is in this - `contracts/hardhat.config.ts`: a `hoodidev` network (chain 560048, RPC from `HOODIDEV_RPC_URL`, key from `DEPLOYER_PRIVATE_KEY`) - `contracts/src/deploy-config/hoodidev.ts`: deploy config for it - `ops/l2-genesis/deploy-config/hoodidev-deploy-config.json`: L2 genesis config for it + +No owner, admin, fee-recipient or challenger address is fixed in these two files. `deploy-l1.sh` derives them from the keys in +`env/secrets.env` and passes them in (`MORPH_DEPLOYER_ADDRESS`, `MORPH_CHALLENGER_ADDRESS`, `MORPH_BATCH_SUBMITTER_ADDRESS` for `hoodidev.ts`; +a `REPLACE_WITH_DEPLOYER_ADDRESS` placeholder in the genesis config, filled into `run/l1/hoodidev-deploy-config.generated.json`). +Owner, admin and fee recipient are **the deployer**, so whoever runs the deployment holds them; the challenger, sequencer, batch +submitter and gas oracle are separate generated keys. The sequencer set, Tendermint and BLS keys in the configs are fixed. - `contracts/src/deploy-utils.ts`: optional read retries (`MORPH_READ_RETRIES`), used because public RPCs are read-after-write inconsistent ## 2. What you need @@ -56,7 +62,7 @@ All commands from this directory (`ops/native-hoodi/`). # 1. build all binaries into ./bin (about 5-10 minutes the first time) scripts/build-all.sh -# 2. keys: your funded deployer key + four generated ones (sequencer, batch submitter, gas oracle, challenger). Prints +# 2. keys: your funded deployer key (it becomes the owner of everything; the public Anvil key is refused) + four generated ones (sequencer, batch submitter, gas oracle, challenger). Prints # addresses only. Then fund the DEPLOYER address. DEPLOYER_PRIVATE_KEY=0x... scripts/init-secrets.sh diff --git a/ops/native-hoodi/RUNBOOK.md b/ops/native-hoodi/RUNBOOK.md index 9c5f3914b..be2a9f372 100644 --- a/ops/native-hoodi/RUNBOOK.md +++ b/ops/native-hoodi/RUNBOOK.md @@ -115,8 +115,9 @@ curl -s http://127.0.0.1:8090/batch/$((FIN + 1)) # 已提交未 finalized 的 4. **公共 RPC 不可靠。** 背后是多个节点:刚上链的区块可能读不到,偶尔限流。`l1-proxy` 解决这两件事,所有进程都应经过它,不要直接连 Hoodi。 5. **node-1 不是实时的。** 它按批次推进,批次提交到 L1 后才前进,所以总会落后几百个块(约一个批次)。 6. **不要把 `hardhat` 任务的退出码当成功。** 它们出错时常常只打印一行然后退出码为 0。部署后用 `verify-l1.sh` 读链上状态。 -7. **改动在 git 里。** 对上游仓库的改动只有 4 个文件:`contracts/hardhat.config.ts`(加网络 `hoodidev`)、`contracts/src/deploy-config/hoodidev.ts`、`ops/l2-genesis/deploy-config/hoodidev-deploy-config.json`、`contracts/src/deploy-utils.ts`(可选的读重试)。 -8. **challenger 不会自动挑战。** 它不轮询 L1,必须有人 `POST /challenge`。挑战成功后 finalize 会停住,需要 owner `revertBatch` 收尾;`proofWindow` 过后调 `proveState` 判挑战方胜,会罚没提交该批次的 submitter 并让合约进入 `pending revert request`。 +7. **owner / 管理员 / 费用接收方都是 deployer,不是写死在仓库里的地址。** `deploy-l1.sh` 从 `env/secrets.env` 的密钥推导出地址,经环境变量传给 `hoodidev.ts`,并填进生成的创世配置(`run/l1/hoodidev-deploy-config.generated.json`)。谁来部署,谁就是 owner。序列器集合、Tendermint 与 BLS 公钥是固定的。 +8. **改动在 git 里。** 对上游仓库的改动只有 4 个文件:`contracts/hardhat.config.ts`(加网络 `hoodidev`)、`contracts/src/deploy-config/hoodidev.ts`、`ops/l2-genesis/deploy-config/hoodidev-deploy-config.json`、`contracts/src/deploy-utils.ts`(可选的读重试)。 +9. **challenger 不会自动挑战。** 它不轮询 L1,必须有人 `POST /challenge`。挑战成功后 finalize 会停住,需要 owner `revertBatch` 收尾;`proofWindow` 过后调 `proveState` 判挑战方胜,会罚没提交该批次的 submitter 并让合约进入 `pending revert request`。 ## 8. 成本(实测) diff --git a/ops/native-hoodi/scripts/deploy-l1.sh b/ops/native-hoodi/scripts/deploy-l1.sh index f76d77372..dbf8d5bc0 100755 --- a/ops/native-hoodi/scripts/deploy-l1.sh +++ b/ops/native-hoodi/scripts/deploy-l1.sh @@ -82,6 +82,8 @@ export ETH_RPC_URL="${RPC_URL}" for v in DEPLOYER_PRIVATE_KEY SEQUENCER_PRIVATE_KEY BATCH_SUBMITTER_PRIVATE_KEY; do [[ "${!v:-}" =~ ^0x[0-9a-fA-F]{64}$ ]] || { echo "${v} is not set to a 32-byte hex key in ${SECRETS}" >&2; exit 1; } done +# The publicly known Anvil key must never own a public-chain deployment (hardhat.config.ts refuses it as well). +[[ "${DEPLOYER_PRIVATE_KEY,,}" != "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" ]] || { echo "DEPLOYER_PRIVATE_KEY is the public Anvil key: use a key only you hold" >&2; exit 1; } # the challenger key is optional (older secrets files do not have one); if set it must be well-formed [[ -z "${CHALLENGER_PRIVATE_KEY:-}" || "${CHALLENGER_PRIVATE_KEY}" =~ ^0x[0-9a-fA-F]{64}$ ]] || { echo "CHALLENGER_PRIVATE_KEY in ${SECRETS} is not a 32-byte hex key" >&2; exit 1; } @@ -91,6 +93,11 @@ addr_of() { ( cd "${MORPH}/contracts" && KEY="${!1}" node -e 'console.log(new (r DEPLOYER="$(addr_of DEPLOYER_PRIVATE_KEY)" SEQUENCER="$(addr_of SEQUENCER_PRIVATE_KEY)" SUBMITTER="$(addr_of BATCH_SUBMITTER_PRIVATE_KEY)" +# The challenger is its own account when a key is configured; otherwise the deployer doubles as challenger (older secrets files). +if [[ -n "${CHALLENGER_PRIVATE_KEY:-}" ]]; then CHALLENGER="$(addr_of CHALLENGER_PRIVATE_KEY)"; else CHALLENGER="${DEPLOYER}"; fi +# contracts/src/deploy-config/hoodidev.ts reads these; the L2 genesis config gets the deployer address in s00_preflight. +# Nothing about the owner / admin / fee-recipient accounts is fixed in the repo: they follow the key that runs this script. +export MORPH_DEPLOYER_ADDRESS="${DEPLOYER}" MORPH_CHALLENGER_ADDRESS="${CHALLENGER}" MORPH_BATCH_SUBMITTER_ADDRESS="${SUBMITTER}" say() { printf '%s %s\n' "$(date +%H:%M:%S)" "$*"; } @@ -126,20 +133,31 @@ s00_preflight() { [[ "${id}" == "${EXPECT_L1_CHAIN_ID}" ]] || { echo "L1 chain id is ${id}, expected ${EXPECT_L1_CHAIN_ID}"; return 1; } bal="$(cast balance "${DEPLOYER}" --rpc-url "${RPC_URL}")" [[ "${bal}" != "0" ]] || { echo "deployer ${DEPLOYER} has no balance on this L1"; return 1; } + # deploy gas (~0.07 ETH, 0.1 for margin) + what this run transfers on to the submitter and the challenger + local need_eth need_wei + need_eth="$(node -e 'console.log(String(0.1 + Number(process.argv[1]) + (process.argv[2] ? Number(process.argv[2]) : 0)))' "${SUBMITTER_FUND_ETH}" "$([[ -n "${CHALLENGER_PRIVATE_KEY:-}" ]] && echo "${CHALLENGER_FUND_ETH:-0.2}")")" + need_wei="$(cast to-wei "${need_eth}" ether)" + node -e 'process.exit(BigInt(process.argv[1]) >= BigInt(process.argv[2]) ? 0 : 1)' "${bal}" "${need_wei}" || + { echo "deployer ${DEPLOYER} has $(wei_to_eth "${bal}") ETH, this run needs about ${need_eth} ETH"; return 1; } + echo "owner / admin / fee recipient of this deployment: ${DEPLOYER} (the deployer)" + echo "challenger: ${CHALLENGER}$([[ "${CHALLENGER}" == "${DEPLOYER}" ]] && echo " (same as the deployer: no CHALLENGER_PRIVATE_KEY in ${SECRETS})")" echo "${bal}" >"${STATE}/deployer-balance-before.wei" cast balance "${SUBMITTER}" --rpc-url "${RPC_URL}" >"${STATE}/submitter-balance-before.wei" cast nonce "${DEPLOYER}" --rpc-url "${RPC_URL}" >"${STATE}/deployer-nonce-before" start_dec="$(cast block-number --rpc-url "${RPC_URL}")" echo "${start_dec}" >"${STATE}/start-block.dec" printf '0x%x\n' "${start_dec}" >"${STATE}/start-block.hex" - # generated copy of the genesis deploy config with the real L1 starting block (the tracked file keeps a placeholder) + # generated copy of the genesis deploy config: the tracked file keeps placeholders for the L1 starting block and for the + # deployer address (owners, admin, fee recipients); this fills both in and refuses to continue if any placeholder is left node -e ' const fs = require("fs"); - const [src, dst, tag] = process.argv.slice(1); - const c = JSON.parse(fs.readFileSync(src, "utf8")); + const [src, dst, tag, deployer] = process.argv.slice(1); + const c = JSON.parse(fs.readFileSync(src, "utf8").split("REPLACE_WITH_DEPLOYER_ADDRESS").join(deployer)); c.l1StartingBlockTag = tag; + const left = JSON.stringify(c).match(/REPLACE_WITH_[A-Z_]+/g); + if (left) { console.error("unreplaced placeholders in the genesis config: " + [...new Set(left)].join(", ")); process.exit(1); } fs.writeFileSync(dst, JSON.stringify(c, null, 2) + "\n"); - ' "${MORPH}/ops/l2-genesis/deploy-config/hoodidev-deploy-config.json" "${GEN_CONFIG}" "$(cat "${STATE}/start-block.hex")" + ' "${MORPH}/ops/l2-genesis/deploy-config/hoodidev-deploy-config.json" "${GEN_CONFIG}" "$(cat "${STATE}/start-block.hex")" "${DEPLOYER}" echo "chain ${id}; deployer ${DEPLOYER} balance $(wei_to_eth "${bal}") ETH; L1 start block ${start_dec}" } @@ -190,6 +208,15 @@ s31_register() { # NOT `hardhat fund`, which would send 100 ETH to the submitter. batchSubmitterPks="[\"${BATCH_SUBMITTER_PRIVATE_KEY}\"]" \ hardhat register --network hoodidev --storagepath "${DEPLOY_JSON}" + # the task exits 0 even when it fails (for instance when the Submitter owner is not the deployer): read the result back + local sub_proxy active + sub_proxy="$(node -e 'const d=JSON.parse(require("fs").readFileSync(process.argv[1],"utf8")).find(x=>x.name==="Proxy__Submitter"); if(!d){process.exit(1)} console.log(d.address)' "${DEPLOY_JSON}")" + for _ in $(seq 1 15); do + active="$(cast call "${sub_proxy}" 'isActive(address)(bool)' "${SUBMITTER}" --rpc-url "${RPC_URL}" 2>/dev/null || true)" + [[ "${active}" == "true" ]] && break; sleep 2 + done + [[ "${active}" == "true" ]] || { echo "Submitter.isActive(${SUBMITTER}) = ${active:-?} after register: it is not registered and staked"; return 1; } + echo "submitter ${SUBMITTER} is active on ${sub_proxy}" } s32_first_sequencer() { diff --git a/ops/native-hoodi/scripts/init-secrets.sh b/ops/native-hoodi/scripts/init-secrets.sh index 1bf5eb292..58b40212d 100755 --- a/ops/native-hoodi/scripts/init-secrets.sh +++ b/ops/native-hoodi/scripts/init-secrets.sh @@ -6,6 +6,8 @@ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" source "${ROOT}/scripts/lib/env.sh" OUT="${ROOT}/env/secrets.env" [[ -n "${DEPLOYER_PRIVATE_KEY:-}" ]] || { echo "error: set DEPLOYER_PRIVATE_KEY in the environment first" >&2; exit 1; } +[[ "${DEPLOYER_PRIVATE_KEY}" =~ ^0x[0-9a-fA-F]{64}$ ]] || { echo "error: DEPLOYER_PRIVATE_KEY must be 0x followed by 64 hex characters" >&2; exit 1; } +[[ "${DEPLOYER_PRIVATE_KEY,,}" != "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" ]] || { echo "error: that is the public Anvil key; use a key only you hold" >&2; exit 1; } [[ ! -e "${OUT}" ]] || { echo "error: ${OUT} exists; move it away first (scripts/reset-env.sh --new-keys does that)" >&2; exit 1; } python3 -I - "${ROOT}/env/hoodi.env.example" "${OUT}" <<'PY' import json, os, re, subprocess, sys @@ -27,4 +29,5 @@ with os.fdopen(fd, "w") as f: f.write(text) PY set -a; source "${OUT}"; set +a for r in DEPLOYER SEQUENCER BATCH_SUBMITTER L2_GAS_ORACLE CHALLENGER; do v="${r}_PRIVATE_KEY"; printf '%-16s %s\n' "${r}" "$(cast wallet address --private-key "${!v}")"; done +echo "The DEPLOYER address becomes the owner, admin and fee recipient of this deployment (nothing of the kind is fixed in the repo)." echo "written ${OUT} (mode 600). Fund the DEPLOYER address with ~1.5 Hoodi ETH, then follow README.md." From a1432613d82591d3d80e148d312aa42cbfc6973d Mon Sep 17 00:00:00 2001 From: Agnar Song Date: Fri, 27 Nov 2026 06:44:03 +0000 Subject: [PATCH 08/23] ops(native-hoodi): build node-2 from the genesis of L1_RUN, not run/l1 add-node2.py read the L2 genesis from run/l1/genesis, whatever L1_RUN pointed at. With a second deployment in another L1_RUN directory (for example after a reset, or when two deployments live side by side) node-2 was initialised from the other deployment's genesis. Its block 0 hash differed from node-0's, so it rejected every block ("wrong parent hash"), and node-0, which needs a Tendermint peer to resume after a restart (notes/issues.md I-028), stopped producing blocks. morph-native.sh setup now passes --genesis "${L1_RUN}/genesis/genesis-l2.json"; without the flag the old default is kept. Found while re-running the deployment in run/l1-v2 next to the old run/l1. After rebuilding node-2 with the right genesis, el-0 and el-2 have the same block 0 hash and follow each other again. Co-Authored-By: Claude Sonnet 5.5 --- ops/native-hoodi/scripts/add-node2.py | 5 ++++- ops/native-hoodi/scripts/morph-native.sh | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/ops/native-hoodi/scripts/add-node2.py b/ops/native-hoodi/scripts/add-node2.py index 0b9294770..8f71420a5 100755 --- a/ops/native-hoodi/scripts/add-node2.py +++ b/ops/native-hoodi/scripts/add-node2.py @@ -32,6 +32,7 @@ def main(): ap.add_argument("--run-dir", required=True) ap.add_argument("--tendermint", required=True) ap.add_argument("--geth", required=True) + ap.add_argument("--genesis", help="L2 genesis file (genesis-l2.json); default: run/l1/genesis/genesis-l2.json next to the run dir") a = ap.parse_args() docker_dir = os.path.join(a.morph, "ops", "docker") run_dir = os.path.abspath(a.run_dir) @@ -85,7 +86,9 @@ def main(): open(p0, "w").write(c0) # ---- morph-el-2: same genesis as the others, nodekey2, static peers to el-0 / el-1 (loopback ports from morph-native.sh) - genesis = os.path.join(run_dir, "..", "l1", "genesis", "genesis-l2.json") + # must be the genesis of the deployment this chain belongs to (L1_RUN), not whatever sits in run/l1: a different genesis hash + # makes node-2 reject node-0's blocks ("wrong parent hash") and node-0 then has no tendermint peer + genesis = a.genesis or os.path.join(run_dir, "..", "l1", "genesis", "genesis-l2.json") os.makedirs(os.path.join(el2, "geth")) shutil.copyfile(os.path.join(docker_dir, "nodekey2"), os.path.join(el2, "geth", "nodekey")) subprocess.run([a.geth, "--verbosity=3", "init", f"--datadir={el2}", os.path.abspath(genesis)], check=True, diff --git a/ops/native-hoodi/scripts/morph-native.sh b/ops/native-hoodi/scripts/morph-native.sh index 79b5e9ffc..3414cc60b 100755 --- a/ops/native-hoodi/scripts/morph-native.sh +++ b/ops/native-hoodi/scripts/morph-native.sh @@ -236,7 +236,7 @@ cmd_setup() { --genesis "${L1_RUN}/genesis/genesis-l2.json" \ --tendermint "${BIN}/morphnode/tendermint" --geth "${BIN}/morph-geth/geth" # node-0 cannot resume block production after a restart unless another tendermint node is its peer (notes/issues.md I-028) - python3 -I "${ROOT}/scripts/add-node2.py" --morph "${MORPH}" --run-dir "${L2_RUN}" \ + python3 -I "${ROOT}/scripts/add-node2.py" --morph "${MORPH}" --run-dir "${L2_RUN}" --genesis "${L1_RUN}/genesis/genesis-l2.json" \ --tendermint "${BIN}/morphnode/tendermint" --geth "${BIN}/morph-geth/geth" } From 61fa94a89df87f108494cb72f70379e64e3b5a66 Mon Sep 17 00:00:00 2001 From: Agnar Song Date: Mon, 30 Nov 2026 07:12:09 +0000 Subject: [PATCH 09/23] ops(native-hoodi): keep private keys out of the repository No private key literal is left in what this branch adds. - hardhat.config.ts: the hoodidev network no longer repeats the public Anvil key. It parses the signer and compares its address with the public Anvil account #0 address; an unset, malformed or public key leaves hoodidev without a signer, as before. - deploy-l1.sh and init-secrets.sh: the guard against the public Anvil key compares the derived deployer address, not the key. - l2-bootstrap.sh: the pre-funded L2 dev account is derived at run time from the public Hardhat mnemonic, and its transfers go through send-tx.js (the key stays out of the argument list). - hoodidev-deploy-config.json: drop l2StakingPks (the upstream devnet test private keys). Nothing in this repository reads the field; the genesis step still passes (checked on a fork dry run). - check-no-secrets.sh: the Anvil key is no longer on the allow list. Co-Authored-By: Claude Sonnet 5.5 --- contracts/hardhat.config.ts | 10 ++++++++-- .../deploy-config/hoodidev-deploy-config.json | 6 ------ ops/native-hoodi/scripts/check-no-secrets.sh | 4 ++-- ops/native-hoodi/scripts/deploy-l1.sh | 5 +++-- ops/native-hoodi/scripts/init-secrets.sh | 3 ++- ops/native-hoodi/scripts/l2-bootstrap.sh | 6 ++++-- 6 files changed, 19 insertions(+), 15 deletions(-) diff --git a/contracts/hardhat.config.ts b/contracts/hardhat.config.ts index b913c4833..b855bc0ae 100644 --- a/contracts/hardhat.config.ts +++ b/contracts/hardhat.config.ts @@ -21,6 +21,7 @@ import "./tasks/token_deploy" import "./tasks/mainnet_upgrade" import "./src/plugin" import * as process from "process"; +import { Wallet } from "ethers"; function getRemappings() { return fs @@ -44,10 +45,15 @@ const HOODI_URL = process.env.HOODI_RPC_URL || 'http://127.0.0.1:8545' // hoodidev: a private Morph L2 whose L1 is the public Ethereum Hoodi testnet. Unlike the networks above it does NOT // fall back to the publicly known Anvil key: without DEPLOYER_PRIVATE_KEY (or with that public key) there is no // signer, so a deployment fails instead of putting admin rights behind a key that anyone can use. -const PUBLIC_ANVIL_KEY = '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80' +const PUBLIC_ANVIL_ADDRESS = '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266' +// a key is usable for hoodidev when it parses and is not the public Anvil account #0 (the key behind the fallback above) +const usableHoodidevKey = (pk?: string): boolean => { + if (!pk) return false + try { return new Wallet(pk).address.toLowerCase() !== PUBLIC_ANVIL_ADDRESS } catch (e) { return false } +} const HOODIDEV_URL = process.env.HOODIDEV_RPC_URL || 'http://127.0.0.1:8545' const HOODIDEV_PK = process.env.DEPLOYER_PRIVATE_KEY -const HOODIDEV_ACCOUNTS = HOODIDEV_PK && HOODIDEV_PK.toLowerCase() !== PUBLIC_ANVIL_KEY ? [HOODIDEV_PK] : [] +const HOODIDEV_ACCOUNTS = usableHoodidevKey(HOODIDEV_PK) ? [HOODIDEV_PK as string] : [] module.exports = { defaultNetwork: 'hardhat', diff --git a/ops/l2-genesis/deploy-config/hoodidev-deploy-config.json b/ops/l2-genesis/deploy-config/hoodidev-deploy-config.json index b6c32e598..6eb7b8e1d 100644 --- a/ops/l2-genesis/deploy-config/hoodidev-deploy-config.json +++ b/ops/l2-genesis/deploy-config/hoodidev-deploy-config.json @@ -32,12 +32,6 @@ "l2StakingSequencerMaxSize": 4, "l2StakingUnDelegatedLockEpochs": 2, "l2StakingRewardStartTime": 1728000000, - "l2StakingPks": [ - "0xd99870855d97327d20c666abc78588f1449b1fac76ed0c86c1afb9ce2db85f32", - "0x0890c388c3bf5e04fee1d8f3c117e5f44f435ced7baf7bfd66c10e1f3a3f4b10", - "0x6fd437eef7a83c486bd2e0a802ae071b3912d125ac31ac08f60841fd891559ae", - "0x9ae53aecdaebe4dcbfec96f3123a2a8c53f9596bf4b3d5adc9a388ccb361b4c0" - ], "l2StakingAddresses": [ "0x783698dCDEBdc96785c5c60ED96113612bA09c2b", "0x310824AA27a29D269d2F9C0a8563C0e3C98dD226", diff --git a/ops/native-hoodi/scripts/check-no-secrets.sh b/ops/native-hoodi/scripts/check-no-secrets.sh index 5d6f7dcc6..d798cef63 100755 --- a/ops/native-hoodi/scripts/check-no-secrets.sh +++ b/ops/native-hoodi/scripts/check-no-secrets.sh @@ -4,8 +4,8 @@ set -uo pipefail cd "$(dirname "${BASH_SOURCE[0]}")/.." bad=0 -# well-known PUBLIC values: Anvil/Hardhat account #0 dev key, EIP-1967 implementation / admin storage slots -ALLOW='ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80|360894a13ba1a3210667c828492db98dca3e2076cc373|b53127684a568b3173ae13b9f8a6016e243e63b6e8ee' +# well-known PUBLIC values: EIP-1967 implementation / admin storage slots (no private key is allowed, not even a public one) +ALLOW='360894a13ba1a3210667c828492db98dca3e2076cc373|b53127684a568b3173ae13b9f8a6016e243e63b6e8ee' PAT='(^|[^0-9a-fA-F])(0x)?[0-9a-fA-F]{64}([^0-9a-fA-F]|$)' hits() { grep -nE "${PAT}" "$1" | grep -vE "${ALLOW}"; } while IFS= read -r f; do diff --git a/ops/native-hoodi/scripts/deploy-l1.sh b/ops/native-hoodi/scripts/deploy-l1.sh index dbf8d5bc0..7378f74fd 100755 --- a/ops/native-hoodi/scripts/deploy-l1.sh +++ b/ops/native-hoodi/scripts/deploy-l1.sh @@ -82,8 +82,6 @@ export ETH_RPC_URL="${RPC_URL}" for v in DEPLOYER_PRIVATE_KEY SEQUENCER_PRIVATE_KEY BATCH_SUBMITTER_PRIVATE_KEY; do [[ "${!v:-}" =~ ^0x[0-9a-fA-F]{64}$ ]] || { echo "${v} is not set to a 32-byte hex key in ${SECRETS}" >&2; exit 1; } done -# The publicly known Anvil key must never own a public-chain deployment (hardhat.config.ts refuses it as well). -[[ "${DEPLOYER_PRIVATE_KEY,,}" != "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" ]] || { echo "DEPLOYER_PRIVATE_KEY is the public Anvil key: use a key only you hold" >&2; exit 1; } # the challenger key is optional (older secrets files do not have one); if set it must be well-formed [[ -z "${CHALLENGER_PRIVATE_KEY:-}" || "${CHALLENGER_PRIVATE_KEY}" =~ ^0x[0-9a-fA-F]{64}$ ]] || { echo "CHALLENGER_PRIVATE_KEY in ${SECRETS} is not a 32-byte hex key" >&2; exit 1; } @@ -93,6 +91,9 @@ addr_of() { ( cd "${MORPH}/contracts" && KEY="${!1}" node -e 'console.log(new (r DEPLOYER="$(addr_of DEPLOYER_PRIVATE_KEY)" SEQUENCER="$(addr_of SEQUENCER_PRIVATE_KEY)" SUBMITTER="$(addr_of BATCH_SUBMITTER_PRIVATE_KEY)" +# The well-known Anvil / Hardhat account #0 has a public key: it must never own a public-chain deployment +# (hardhat.config.ts refuses it as well). +[[ "${DEPLOYER,,}" != "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266" ]] || { echo "DEPLOYER_PRIVATE_KEY is the public Anvil key: use a key only you hold" >&2; exit 1; } # The challenger is its own account when a key is configured; otherwise the deployer doubles as challenger (older secrets files). if [[ -n "${CHALLENGER_PRIVATE_KEY:-}" ]]; then CHALLENGER="$(addr_of CHALLENGER_PRIVATE_KEY)"; else CHALLENGER="${DEPLOYER}"; fi # contracts/src/deploy-config/hoodidev.ts reads these; the L2 genesis config gets the deployer address in s00_preflight. diff --git a/ops/native-hoodi/scripts/init-secrets.sh b/ops/native-hoodi/scripts/init-secrets.sh index 58b40212d..764fb9bba 100755 --- a/ops/native-hoodi/scripts/init-secrets.sh +++ b/ops/native-hoodi/scripts/init-secrets.sh @@ -7,7 +7,8 @@ source "${ROOT}/scripts/lib/env.sh" OUT="${ROOT}/env/secrets.env" [[ -n "${DEPLOYER_PRIVATE_KEY:-}" ]] || { echo "error: set DEPLOYER_PRIVATE_KEY in the environment first" >&2; exit 1; } [[ "${DEPLOYER_PRIVATE_KEY}" =~ ^0x[0-9a-fA-F]{64}$ ]] || { echo "error: DEPLOYER_PRIVATE_KEY must be 0x followed by 64 hex characters" >&2; exit 1; } -[[ "${DEPLOYER_PRIVATE_KEY,,}" != "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" ]] || { echo "error: that is the public Anvil key; use a key only you hold" >&2; exit 1; } +# the well-known Anvil / Hardhat account #0 (public address): its key is public too, so it must not own a real deployment +[[ "$(addr_of DEPLOYER_PRIVATE_KEY | tr 'A-F' 'a-f')" != "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266" ]] || { echo "error: that is the public Anvil key; use a key only you hold" >&2; exit 1; } [[ ! -e "${OUT}" ]] || { echo "error: ${OUT} exists; move it away first (scripts/reset-env.sh --new-keys does that)" >&2; exit 1; } python3 -I - "${ROOT}/env/hoodi.env.example" "${OUT}" <<'PY' import json, os, re, subprocess, sys diff --git a/ops/native-hoodi/scripts/l2-bootstrap.sh b/ops/native-hoodi/scripts/l2-bootstrap.sh index cd578b4a0..a82173f8b 100755 --- a/ops/native-hoodi/scripts/l2-bootstrap.sh +++ b/ops/native-hoodi/scripts/l2-bootstrap.sh @@ -14,13 +14,15 @@ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" MORPH="${MORPH:-$(cd "${ROOT}/../.." && pwd)}" L2_RPC="${L2_RPC:-http://127.0.0.1:8545}" ORACLE_CONTRACT=0x530000000000000000000000000000000000000F -DEV_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 # Anvil #0: public, local-only L2 +DEV_MNEMONIC="test test test test test test test test test test test junk" # the public Hardhat / Anvil mnemonic: account #0 is pre-funded on this L2 FUND_DEPLOYER_ETH="${FUND_DEPLOYER_ETH:-100}" FUND_ORACLE_ETH="${FUND_ORACLE_ETH:-10}" # shellcheck disable=SC1090 source "${ROOT}/scripts/lib/env.sh" set -a; source "${ROOT}/env/secrets.env"; set +a export MORPH_CONTRACTS="${MORPH}/contracts" +# derived here, passed on through the environment only; the key is public and this L2 listens on 127.0.0.1 and holds nothing of value +DEV_KEY="$(cd "${MORPH}/contracts" && MNEMONIC="${DEV_MNEMONIC}" node -e 'console.log(require("ethers").Wallet.fromMnemonic(process.env.MNEMONIC).privateKey)')" addr_of() { ( cd "${MORPH}/contracts" && KEY="${!1}" node -e 'console.log(new (require("ethers").Wallet)(process.env.KEY).address)' ); } DEPLOYER="$(addr_of DEPLOYER_PRIVATE_KEY)"; ORACLE="$(addr_of L2_GAS_ORACLE_PRIVATE_KEY)" @@ -30,7 +32,7 @@ say() { printf '%s %s\n' "$(date +%H:%M:%S)" "$*"; } fund() { # fund NAME ADDRESS ETH local bal; bal="$(cast balance "$2" --rpc-url "${L2_RPC}")" if [[ "${bal}" != "0" ]]; then say "$1 $2 already has L2 balance $(cast from-wei "${bal}") ETH"; return 0; fi - cast send "$2" --value "$3ether" --private-key "${DEV_KEY}" --rpc-url "${L2_RPC}" >/dev/null + KEY="${DEV_KEY}" node "${ROOT}/scripts/send-tx.js" "${L2_RPC}" "$2" --value-ether "$3" >/dev/null bal="$(cast balance "$2" --rpc-url "${L2_RPC}")" [[ "${bal}" != "0" ]] || { echo "funding $1 failed" >&2; exit 1; } say "$1 $2 funded on L2: $(cast from-wei "${bal}") ETH" From 8056bd346c17a3a5928c13a0f8d028ed525d07d0 Mon Sep 17 00:00:00 2001 From: Agnar Song Date: Mon, 30 Nov 2026 07:12:29 +0000 Subject: [PATCH 10/23] ops(native-hoodi): keep private keys off command lines Arguments of a running process are visible to every user of the machine in `ps`. Two places put keys there: - Deriving an address with `cast wallet address --private-key` (init-secrets.sh, export-deployment.sh, sweep-submitter.sh, reset-env.sh). They now use a small helper, scripts/addr-of.js (the shell function addr_of in lib/env.sh), which takes the key from the environment and uses ethers from the contracts' node_modules. It fails with a clear message when those are not installed yet. - morph-native.sh started every process as `env VAR=value ... command` inside a supervisor `bash -c`, so the keys of tx-submitter, gas-oracle and the challenger were in the argument list of both. The variables are now exported in a subshell and reach the supervisor and the program as environment. Checked with a random key: the supervisor and its children have no 64-hex string in their arguments, the variable is in their environment, and addr-of.js agrees with cast. Co-Authored-By: Claude Sonnet 5.5 --- ops/native-hoodi/scripts/addr-of.js | 16 ++++++++++++++++ ops/native-hoodi/scripts/export-deployment.sh | 10 +++++----- ops/native-hoodi/scripts/init-secrets.sh | 2 +- ops/native-hoodi/scripts/lib/env.sh | 7 +++++++ ops/native-hoodi/scripts/morph-native.sh | 19 ++++++++++++------- ops/native-hoodi/scripts/reset-env.sh | 2 +- ops/native-hoodi/scripts/sweep-submitter.sh | 4 ++-- 7 files changed, 44 insertions(+), 16 deletions(-) create mode 100755 ops/native-hoodi/scripts/addr-of.js diff --git a/ops/native-hoodi/scripts/addr-of.js b/ops/native-hoodi/scripts/addr-of.js new file mode 100755 index 000000000..785a61c2b --- /dev/null +++ b/ops/native-hoodi/scripts/addr-of.js @@ -0,0 +1,16 @@ +#!/usr/bin/env node +/* + * addr-of.js — print the address of a private key without putting the key on a command line (it would show up in `ps`). + * The key comes from the environment (KEY); ethers v5 is loaded from $MORPH_CONTRACTS/node_modules. + * + * Usage: KEY=0x... MORPH_CONTRACTS=/path/to/contracts addr-of.js + */ +const path = require("path"); +const contracts = process.env.MORPH_CONTRACTS; +if (!contracts) { console.error("MORPH_CONTRACTS is not set"); process.exit(2); } +let ethers; +try { ethers = require(path.join(contracts, "node_modules", "ethers")); } +catch (e) { console.error("ethers not found under " + contracts + "/node_modules: run scripts/build-all.sh first (it installs the contracts' dependencies)"); process.exit(2); } +if (!process.env.KEY) { console.error("KEY is not set"); process.exit(2); } +try { console.log(new ethers.Wallet(process.env.KEY).address); } +catch (e) { console.error("KEY is not a valid private key"); process.exit(1); } diff --git a/ops/native-hoodi/scripts/export-deployment.sh b/ops/native-hoodi/scripts/export-deployment.sh index 1dfe125dd..abb7bd106 100755 --- a/ops/native-hoodi/scripts/export-deployment.sh +++ b/ops/native-hoodi/scripts/export-deployment.sh @@ -16,11 +16,11 @@ cp "${L1}"/genesis/*.json "${D}/genesis/" 2>/dev/null || true cp "${ROOT}/notes/versions.md" "${D}/versions.md" for f in "${ROOT}"/run/*test*.out "${ROOT}"/run/verify*.out "${L1}"/../verify*.out; do [[ -f "$f" ]] && cp "$f" "${D}/verification/"; done 2>/dev/null || true set -a; source "${ROOT}/env/secrets.env"; set +a -DEP="$(cast wallet address --private-key "${DEPLOYER_PRIVATE_KEY}")" -SEQ="$(cast wallet address --private-key "${SEQUENCER_PRIVATE_KEY}")" -SUB="$(cast wallet address --private-key "${BATCH_SUBMITTER_PRIVATE_KEY}")" -ORA="$(cast wallet address --private-key "${L2_GAS_ORACLE_PRIVATE_KEY}")" -CHA=""; [[ -n "${CHALLENGER_PRIVATE_KEY:-}" ]] && CHA="$(cast wallet address --private-key "${CHALLENGER_PRIVATE_KEY}")" +DEP="$(addr_of DEPLOYER_PRIVATE_KEY)" +SEQ="$(addr_of SEQUENCER_PRIVATE_KEY)" +SUB="$(addr_of BATCH_SUBMITTER_PRIVATE_KEY)" +ORA="$(addr_of L2_GAS_ORACLE_PRIVATE_KEY)" +CHA=""; [[ -n "${CHALLENGER_PRIVATE_KEY:-}" ]] && CHA="$(addr_of CHALLENGER_PRIVATE_KEY)" { echo "# Deployment ${NAME}"; echo echo "- exported: $(date -Is)" diff --git a/ops/native-hoodi/scripts/init-secrets.sh b/ops/native-hoodi/scripts/init-secrets.sh index 764fb9bba..fc1325b4d 100755 --- a/ops/native-hoodi/scripts/init-secrets.sh +++ b/ops/native-hoodi/scripts/init-secrets.sh @@ -29,6 +29,6 @@ fd = os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, "w") as f: f.write(text) PY set -a; source "${OUT}"; set +a -for r in DEPLOYER SEQUENCER BATCH_SUBMITTER L2_GAS_ORACLE CHALLENGER; do v="${r}_PRIVATE_KEY"; printf '%-16s %s\n' "${r}" "$(cast wallet address --private-key "${!v}")"; done +for r in DEPLOYER SEQUENCER BATCH_SUBMITTER L2_GAS_ORACLE CHALLENGER; do v="${r}_PRIVATE_KEY"; printf '%-16s %s\n' "${r}" "$(addr_of "${v}")"; done echo "The DEPLOYER address becomes the owner, admin and fee recipient of this deployment (nothing of the kind is fixed in the repo)." echo "written ${OUT} (mode 600). Fund the DEPLOYER address with ~1.5 Hoodi ETH, then follow README.md." diff --git a/ops/native-hoodi/scripts/lib/env.sh b/ops/native-hoodi/scripts/lib/env.sh index 39e73d8e0..3bbbd0340 100644 --- a/ops/native-hoodi/scripts/lib/env.sh +++ b/ops/native-hoodi/scripts/lib/env.sh @@ -38,3 +38,10 @@ require_build_tools() { exit 1 fi } + +# addr_of VARNAME: the address of the private key held in that variable. The key goes through the environment, never +# through a command line (arguments are visible to every user of the machine in `ps`). Needs the contracts' node_modules. +addr_of() { + local root="${ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)}" + KEY="${!1}" MORPH_CONTRACTS="${MORPH_CONTRACTS:-${MORPH:-$(cd "${root}/../.." && pwd)}/contracts}" node "${root}/scripts/addr-of.js" +} diff --git a/ops/native-hoodi/scripts/morph-native.sh b/ops/native-hoodi/scripts/morph-native.sh index 3414cc60b..7be33d8c9 100755 --- a/ops/native-hoodi/scripts/morph-native.sh +++ b/ops/native-hoodi/scripts/morph-native.sh @@ -93,13 +93,18 @@ spawn() { if alive "${name}"; then say "${name}: already running (pid $(cat "${PIDS}/${name}.pid"))"; return 0; fi # cwd = state dir, so programs that write relative files (tx-submitter: journal.rlp, leveldb) stay inside run/ cd "${STATE}" - setsid bash -c ' - echo $$ > "$1"; shift - while :; do - "$@"; rc=$? - echo "--- $(date +%FT%T) exited with status ${rc}; restarting in 2s" - sleep 2 - done' _ "${PIDS}/${name}.pid" env "${envs[@]}" "$@" >>"${LOGS}/${name}.log" 2>&1 & + # The variables (they include private keys) are exported inside a subshell and reach the supervisor and the program as + # environment. They must not be put on the command line: arguments are visible to every user of the machine in `ps`. + ( + for kv in "${envs[@]}"; do export "${kv}"; done + exec setsid bash -c ' + echo $$ > "$1"; shift + while :; do + "$@"; rc=$? + echo "--- $(date +%FT%T) exited with status ${rc}; restarting in 2s" + sleep 2 + done' _ "${PIDS}/${name}.pid" "$@" >>"${LOGS}/${name}.log" 2>&1 + ) & for _ in $(seq 1 20); do [[ -s "${PIDS}/${name}.pid" ]] && break; sleep 0.1; done say "${name}: started (pid $(cat "${PIDS}/${name}.pid" 2>/dev/null || echo ?))" } diff --git a/ops/native-hoodi/scripts/reset-env.sh b/ops/native-hoodi/scripts/reset-env.sh index 9b2b6d88d..9f6bef153 100755 --- a/ops/native-hoodi/scripts/reset-env.sh +++ b/ops/native-hoodi/scripts/reset-env.sh @@ -65,7 +65,7 @@ submitter_balance_eth() { local key rpc addr key="$(secret BATCH_SUBMITTER_PRIVATE_KEY)"; rpc="${HOODI_RPC:-https://rpc.hoodi.ethpandaops.io}" [[ -n "${key}" ]] || { echo "?"; return; } - addr="$(cast wallet address --private-key "${key}" 2>/dev/null)" || { echo "?"; return; } + addr="$(BATCH_SUBMITTER_PRIVATE_KEY="${key}" addr_of BATCH_SUBMITTER_PRIVATE_KEY 2>/dev/null)" || { echo "?"; return; } cast balance "${addr}" --ether --rpc-url "${rpc}" 2>/dev/null || echo "?" } diff --git a/ops/native-hoodi/scripts/sweep-submitter.sh b/ops/native-hoodi/scripts/sweep-submitter.sh index 2ea101e83..cb6641e90 100755 --- a/ops/native-hoodi/scripts/sweep-submitter.sh +++ b/ops/native-hoodi/scripts/sweep-submitter.sh @@ -8,8 +8,8 @@ set -a; source "${ROOT}/env/secrets.env"; set +a RPC="${HOODI_RPC:-https://rpc.hoodi.ethpandaops.io}" RESERVE="${1:-0.01}" export MORPH_CONTRACTS="$(cd "${ROOT}/../../contracts" && pwd)" -SUB="$(cast wallet address --private-key "${BATCH_SUBMITTER_PRIVATE_KEY}")" -DEP="$(cast wallet address --private-key "${DEPLOYER_PRIVATE_KEY}")" +SUB="$(addr_of BATCH_SUBMITTER_PRIVATE_KEY)" +DEP="$(addr_of DEPLOYER_PRIVATE_KEY)" BAL="$(cast balance "${SUB}" --ether --rpc-url "${RPC}")" AMT="$(awk -v b="${BAL}" -v r="${RESERVE}" 'BEGIN{printf "%.6f", b-r}')" echo "submitter ${SUB}: ${BAL} ETH -> sending ${AMT} to deployer ${DEP}" From 75234bcdd1290846dce14983499c6893d85b5854 Mon Sep 17 00:00:00 2001 From: Agnar Song Date: Mon, 30 Nov 2026 07:12:31 +0000 Subject: [PATCH 11/23] ops(native-hoodi): size the challenger top-up from the same balance read that decided it register-challenger.sh read the challenger's balance once to decide whether to fund it and again to compute how much to send. On a public RPC two reads can come from nodes at different heights, so the amount could be computed from a different balance than the decision. It now reads once and uses that value for both. Co-Authored-By: Claude Sonnet 5.5 --- ops/native-hoodi/scripts/register-challenger.sh | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/ops/native-hoodi/scripts/register-challenger.sh b/ops/native-hoodi/scripts/register-challenger.sh index e2db0d076..4bd15e052 100755 --- a/ops/native-hoodi/scripts/register-challenger.sh +++ b/ops/native-hoodi/scripts/register-challenger.sh @@ -64,11 +64,13 @@ fi want="$(cast to-wei "${FUND_ETH}" ether)" has() { node -e 'process.exit(BigInt(process.argv[1]) >= BigInt(process.argv[2]) ? 0 : 1)' "$(cast balance "${CHALLENGER}" --rpc-url "${RPC_URL}")" "${want}"; } -if has; then - say "challenger balance $(cast balance "${CHALLENGER}" --ether --rpc-url "${RPC_URL}") ETH (>= ${FUND_ETH}): not funding" +# one balance read decides whether to fund and how much; a second read could see a different node's view of the chain +bal="$(cast balance "${CHALLENGER}" --rpc-url "${RPC_URL}")" +if node -e 'process.exit(BigInt(process.argv[1]) >= BigInt(process.argv[2]) ? 0 : 1)' "${bal}" "${want}"; then + say "challenger balance $(cast from-wei "${bal}") ETH (>= ${FUND_ETH}): not funding" else # send only the difference, so the balance ends at CHALLENGER_FUND_ETH - top_up="$(cast from-wei "$(node -e 'console.log((BigInt(process.argv[1]) - BigInt(process.argv[2])).toString())' "${want}" "$(cast balance "${CHALLENGER}" --rpc-url "${RPC_URL}")")")" + top_up="$(cast from-wei "$(node -e 'console.log((BigInt(process.argv[1]) - BigInt(process.argv[2])).toString())' "${want}" "${bal}")")" KEY="${DEPLOYER_PRIVATE_KEY}" node "${ROOT}/scripts/send-tx.js" "${RPC_URL}" "${CHALLENGER}" --value-ether "${top_up}" wait_for has || { echo "challenger balance is still below ${FUND_ETH} ETH after funding" >&2; exit 1; } say "challenger funded: $(cast balance "${CHALLENGER}" --ether --rpc-url "${RPC_URL}") ETH" From 315140356d3ec1e8ddc355fa7ba209e5aa9ea111 Mon Sep 17 00:00:00 2001 From: Agnar Song Date: Mon, 30 Nov 2026 07:12:44 +0000 Subject: [PATCH 12/23] ops(native-hoodi): translate the script comments and messages to English Header comments, usage text, argument help and a few echo lines of deploy-l1.sh, morph-native.sh, reset-env.sh, dryrun-fork.sh, probe-hoodi.sh and setup-nodes.py. No behaviour change; the usage text printed by morph-native.sh keeps its line numbers (it is cut out of the header by line range). Co-Authored-By: Claude Sonnet 5.5 --- ops/native-hoodi/scripts/deploy-l1.sh | 42 ++++++++++++------------ ops/native-hoodi/scripts/dryrun-fork.sh | 12 +++---- ops/native-hoodi/scripts/morph-native.sh | 40 +++++++++++----------- ops/native-hoodi/scripts/probe-hoodi.sh | 14 ++++---- ops/native-hoodi/scripts/reset-env.sh | 34 +++++++++---------- ops/native-hoodi/scripts/setup-nodes.py | 40 +++++++++++----------- 6 files changed, 91 insertions(+), 91 deletions(-) diff --git a/ops/native-hoodi/scripts/deploy-l1.sh b/ops/native-hoodi/scripts/deploy-l1.sh index 7378f74fd..a414d7e4b 100755 --- a/ops/native-hoodi/scripts/deploy-l1.sh +++ b/ops/native-hoodi/scripts/deploy-l1.sh @@ -1,29 +1,29 @@ #!/usr/bin/env bash # -# deploy-l1.sh — 在 L1(公共 Hoodi,或其 anvil 分叉)上部署 Morph 合约,并生成 L2 创世。 +# deploy-l1.sh — deploy the Morph contracts on L1 (public Hoodi, or an anvil fork of it) and generate the L2 genesis. # -# 对应上游 ops/devnet-morph/devnet/__init__.py 的 devnet_deploy(),但: -# - 不调用 docker compose,不改写仓库里被 git 跟踪的 .env / l1.ts(batchHeader 走环境变量 MORPH_BATCH_HEADER) -# - 不调用 `hardhat fund`(它会转 100 ETH);提交者资金由 SUBMITTER_FUND_ETH 控制,默认不转 -# - 每一步幂等:成功后在 $RUN_DIR/state/ 落标记文件,重跑会跳过已完成的步骤 -# - 私钥只通过环境变量传递,不出现在命令行参数或输出里 +# Counterpart of devnet_deploy() in upstream ops/devnet-morph/devnet/__init__.py, but: +# - no docker compose, and it does not rewrite the git-tracked .env / l1.ts (the batchHeader goes through MORPH_BATCH_HEADER) +# - no `hardhat fund` (it would send 100 ETH); the submitter's funds are set by SUBMITTER_FUND_ETH, default none +# - every step is idempotent: on success it leaves a marker file in $RUN_DIR/state/, and a re-run skips finished steps +# - private keys travel through the environment only, never on a command line or in the output # -# 必需环境变量: -# RPC_URL L1 执行层 RPC(Hoodi 或 anvil 分叉),链 ID 必须是 560048 -# RUN_DIR 本次运行的输出目录(部署产物、创世文件、日志、状态) -# 可选: -# SECRETS 密钥文件,默认 env/secrets.env -# WAIT_FINALIZED 1(默认)= 部署完等 L1 finalized 越过当前块;分叉干跑设 0 -# FINALIZED_TIMEOUT_SEC 等待 finalized 的超时,默认 1800(Hoodi 约需 13 分钟) -# SUBMITTER_FUND_ETH 向 batch submitter 转多少 ETH(默认 0 = 不转) -# STOP_AFTER 执行到指定步骤后停止,如 s21_batchheader(用于分段验证) -# USE_CONSISTENCY_PROXY auto(默认:RPC 是 https 就启用)/ 1 / 0。启用时在本机起 rpc-consistency-proxy.js, -# 所有读都经它转发,解决公共 RPC 多节点造成的"刚上链就读不到"(见 notes/issues.md I-018、I-019) -# PROXY_PORT 代理端口,默认 18546 -# RPC_FALLBACK_URLS 代理的备用上游(逗号分隔),主上游限流或不可达时自动切换。 -# 默认 0xrpc.io 与 publicnode;设为空字符串则不用备用 +# Required environment: +# RPC_URL L1 execution RPC (Hoodi or an anvil fork); the chain id must be 560048 +# RUN_DIR output directory of this run (deployment, genesis files, logs, state) +# Optional: +# SECRETS secrets file, default env/secrets.env +# WAIT_FINALIZED 1 (default) = after deploying wait until L1 finalized has passed the current block; use 0 on a fork +# FINALIZED_TIMEOUT_SEC timeout of that wait, default 1800 (Hoodi needs about 13 minutes) +# SUBMITTER_FUND_ETH how much ETH to send to the batch submitter (default 0 = none) +# STOP_AFTER stop after the given step, for example s21_batchheader (to verify in stages) +# USE_CONSISTENCY_PROXY auto (default: on when the RPC is https) / 1 / 0. When on, rpc-consistency-proxy.js is started locally +# and every read goes through it, which fixes the public RPC's "not readable right after it was mined" (notes/issues.md I-018, I-019) +# PROXY_PORT proxy port, default 18546 +# RPC_FALLBACK_URLS fallback upstreams of the proxy (comma separated), used when the primary is rate-limited or unreachable. +# Default: 0xrpc.io and publicnode; an empty string disables the fallbacks # -# 退出码:0 成功;1 某步骤失败(日志路径会打印)。 +# Exit code: 0 success; 1 a step failed (the log path is printed). set -euo pipefail diff --git a/ops/native-hoodi/scripts/dryrun-fork.sh b/ops/native-hoodi/scripts/dryrun-fork.sh index af3145a95..03b26e9dd 100755 --- a/ops/native-hoodi/scripts/dryrun-fork.sh +++ b/ops/native-hoodi/scripts/dryrun-fork.sh @@ -1,14 +1,14 @@ #!/usr/bin/env bash # -# dryrun-fork.sh — P2-5:在 Hoodi 的 anvil 分叉上把 deploy-l1.sh 完整干跑一遍,量出真实的 gas / ETH 需求。 +# dryrun-fork.sh — P2-5: rehearse the whole deploy-l1.sh on an anvil fork of Hoodi and measure the real gas / ETH need. # -# anvil 从公共 Hoodi 分叉出一个本地链(链 ID 560048),给 deployer / submitter 凭空设置余额; -# 部署只发生在本地分叉里,**不会向公共 Hoodi 发送任何交易,也不花任何测试币**。 +# anvil forks a local chain (chain id 560048) from public Hoodi and sets the deployer / submitter balances out of thin air; +# the deployment happens inside the local fork only: **no transaction is sent to public Hoodi and no testnet coin is spent**. # -# 用法:dryrun-fork.sh [RUN_DIR] (默认 run/dryrun-<时间戳>) -# 环境:FORK_URL 默认 https://rpc.hoodi.ethpandaops.io;PORT 默认 18545 +# Usage: dryrun-fork.sh [RUN_DIR] (default run/dryrun-) +# Environment: FORK_URL defaults to https://rpc.hoodi.ethpandaops.io; PORT defaults to 18545 # -# 退出时会停掉自己启动的 anvil(按 pid 文件)。 +# On exit it stops the anvil it started (by its pid file). set -euo pipefail ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" diff --git a/ops/native-hoodi/scripts/morph-native.sh b/ops/native-hoodi/scripts/morph-native.sh index 7be33d8c9..a2ce4b6b9 100755 --- a/ops/native-hoodi/scripts/morph-native.sh +++ b/ops/native-hoodi/scripts/morph-native.sh @@ -1,31 +1,31 @@ #!/usr/bin/env bash # -# morph-native.sh — 用原生进程运行 Morph L2(L1 = 公共 Hoodi),代替上游的 docker compose。 +# morph-native.sh — run the Morph L2 as native processes (L1 = public Hoodi), instead of the upstream docker compose. # -# 进程(启动顺序): +# Processes (start order): # l1-proxy → morph-el-0 → node-0 → morph-el-1 → node-1 → morph-el-2 → node-2 → tx-submitter → gas-price-oracle # node-2 exists only so that node-0 can be restarted: see notes/issues.md I-028 -# l1-proxy 是本机的 rpc-consistency-proxy.js:所有进程访问 L1 都走它(限流时切换备用端点、读写一致性),见 notes/issues.md I-018~I-021 -# node-0 是 tendermint 验证者(出块);node-1 以 layer1 校验模式运行,不启动 tendermint。 -# 可选进程 challenger(不在上面的默认列表里):比对 L1/L2 的 batch 根并在不一致时发起 challengeState。 -# 用 `up challenger` 启动,或在 env/secrets.env 里设 CHALLENGER_ENABLE=1 让 `up` 一并启动。仅监听 127.0.0.1。 +# l1-proxy is the local rpc-consistency-proxy.js: every process reaches L1 through it (fallback endpoints on rate limits, read-after-write consistency), see notes/issues.md I-018~I-021 +# node-0 is the Tendermint validator (produces blocks); node-1 runs in layer1 verify mode and starts no Tendermint. +# The optional process challenger (not in the default list above) compares the L1 and L2 batch roots and sends challengeState when they differ. +# Start it with `up challenger`, or set CHALLENGER_ENABLE=1 in env/secrets.env so that `up` starts it too. It listens on 127.0.0.1 only. # -# 用法: -# morph-native.sh setup 生成 tendermint / geth 运行目录(用 deploy-l1.sh 产出的创世文件) -# morph-native.sh up [NAME...] 启动全部或指定进程(challenger 需显式指定或设 CHALLENGER_ENABLE=1) -# morph-native.sh down 停止全部进程(保留链数据) -# morph-native.sh status 进程、L2 高度、L1 同步高度、Rollup 批次 -# morph-native.sh logs NAME 跟随某个进程的日志 -# morph-native.sh clean logs 把日志挪到 run/archive/(需先 down) -# morph-native.sh clean l2 把 L2 链数据挪到 run/archive/(需先 down)。**会让 L2 与 L1 上的 Rollup 对不上**,见下 -# morph-native.sh kill NAME 停掉某个进程(不会被自动重启) -# morph-native.sh start NAME 启动某个进程 +# Usage: +# morph-native.sh setup create the Tendermint / geth run directories (from the genesis that deploy-l1.sh produced) +# morph-native.sh up [NAME...] start all processes or the named ones (challenger must be named, or CHALLENGER_ENABLE=1) +# morph-native.sh down stop all processes (chain data is kept) +# morph-native.sh status processes, L2 heights, L1 head, Rollup batches +# morph-native.sh logs NAME follow the log of one process +# morph-native.sh clean logs move the logs to run/archive/ (run `down` first) +# morph-native.sh clean l2 move the L2 chain data to run/archive/ (run `down` first). **The L2 then no longer matches the Rollup on L1**, see below +# morph-native.sh kill NAME stop one process (it is not restarted) +# morph-native.sh start NAME start one process # -# 路径(可用环境变量改): -# L1_RUN deploy-l1.sh 的输出目录,默认 run/l1(其中 deployment/hoodidev.json、genesis/、state/start-block.dec) -# L2_RUN 本脚本的运行目录,默认 run/l2 +# Paths (can be changed with environment variables): +# L1_RUN output directory of deploy-l1.sh, default run/l1 (with deployment/hoodidev.json, genesis/, state/start-block.dec) +# L2_RUN run directory of this script, default run/l2 # -# 密钥取自 env/secrets.env,只经环境变量传给子进程,不出现在命令行参数里。 +# Keys are read from env/secrets.env and reach the child processes through the environment only, never on a command line. set -euo pipefail diff --git a/ops/native-hoodi/scripts/probe-hoodi.sh b/ops/native-hoodi/scripts/probe-hoodi.sh index f450ec579..4fa6171e7 100755 --- a/ops/native-hoodi/scripts/probe-hoodi.sh +++ b/ops/native-hoodi/scripts/probe-hoodi.sh @@ -1,9 +1,9 @@ #!/usr/bin/env bash -# probe-hoodi.sh — 对 Hoodi 的公共 EL / 信标端点做温和的限流与能力探测(只读,不发交易)。 +# probe-hoodi.sh — a gentle probe of the rate limits and capabilities of the public Hoodi EL / beacon endpoints (read-only, sends no transactions). # -# 用法:probe-hoodi.sh [并发数,默认 20] [轮数,默认 3] -# 输出:每个端点的 HTTP 状态分布、平均延迟,以及几项 Morph 实际会用到的接口。 -# 注意:对公共服务只做小规模并发,不是压测。 +# Usage: probe-hoodi.sh [concurrency, default 20] [rounds, default 3] +# Output: per endpoint the distribution of HTTP statuses and the mean latency, plus a few calls that Morph really uses. +# Note: only small-scale concurrency is used against public services; this is not a load test. set -uo pipefail CONC="${1:-20}" @@ -27,7 +27,7 @@ summarize() { # summarize FILE -> "codes: 200x20 429x0 ...; avg=..s max=..s" s=""; for(k in c) s=s k "x" c[k] " "; printf "%s avg=%.2fs max=%.2fs n=%d\n", s, (n?t/n:0), m, n}' "$1" } -echo "== 并发 ${CONC} × ${ROUNDS} 轮" +echo "== concurrency ${CONC} x ${ROUNDS} rounds" for u in "${EL_ENDPOINTS[@]}"; do : >"${tmp}/el.txt" for _ in $(seq 1 "${ROUNDS}"); do @@ -47,7 +47,7 @@ for u in "${BEACON_ENDPOINTS[@]}"; do done echo -echo "== eth_getLogs:区间上限(Morph 的 L1 同步会用)" +echo "== eth_getLogs: range limit (Morph's L1 sync uses it)" for u in "${EL_ENDPOINTS[@]}"; do head_hex="$(curl -s -m 15 -X POST "${u}" -H 'content-type: application/json' --data '{"jsonrpc":"2.0","id":1,"method":"eth_blockNumber","params":[]}' | sed -E 's/.*"result":"(0x[0-9a-f]+)".*/\1/')" head=$((head_hex)) @@ -61,7 +61,7 @@ for u in "${EL_ENDPOINTS[@]}"; do done echo -echo "== 信标:近期 slot 的 blob_sidecars 连续取 5 个" +echo "== beacon: blob_sidecars of 5 consecutive recent slots" for u in "${BEACON_ENDPOINTS[@]}"; do head_slot="$(curl -s -m 15 "${u}/eth/v1/beacon/headers/head" | sed -E 's/.*"slot":"([0-9]+)".*/\1/')" ok=0; fail=0 diff --git a/ops/native-hoodi/scripts/reset-env.sh b/ops/native-hoodi/scripts/reset-env.sh index 9f6bef153..d5b47c871 100755 --- a/ops/native-hoodi/scripts/reset-env.sh +++ b/ops/native-hoodi/scripts/reset-env.sh @@ -1,25 +1,25 @@ #!/usr/bin/env bash # -# reset-env.sh — 把本机环境重置到"干净状态",并且可以原样恢复。从不删除任何东西,只 mv。 +# reset-env.sh — put this machine's environment back into a clean state, and be able to restore it exactly. Nothing is ever deleted, only moved (mv). # -# 用法: -# reset-env.sh plan [--with-build] [--new-keys] 只打印会做什么(默认命令,不改任何东西) -# reset-env.sh run [--with-build] [--new-keys] --yes 真正执行 -# reset-env.sh restore <时间戳> --yes 把某次 reset 挪走的东西原样挪回 -# reset-env.sh list 列出已有的归档 +# Usage: +# reset-env.sh plan [--with-build] [--new-keys] only print what would be done (default command, changes nothing) +# reset-env.sh run [--with-build] [--new-keys] --yes really do it +# reset-env.sh restore --yes move what one earlier reset moved away back where it was +# reset-env.sh list list the existing archives # -# run 做的事(按顺序): -# 1. 检查 submitter 在 L1 上的余额;高于 SWEEP_THRESHOLD_ETH(默认 0.02)就拒绝,先回收资金再来(--ignore-balance 可跳过) -# 2. morph-native.sh down(停全部进程) -# 3. 把 run/ 下的运行数据(l1、l2、失败尝试、测试输出、日志)挪到 run/archive/<时间戳>/ -# 4. --with-build:把二进制和构建产物也挪进去(bin/、go-ethereum/build/bin、node/build/bin、tx-submitter 二进制、 -# gas-oracle/app/target、contracts 的 node_modules/artifacts/dist/typechain-types)。这些在 git 里都是被忽略的 -# 5. --new-keys:旧 env/secrets.env 挪到 env/archive/secrets-<时间戳>.env,新建一份:deployer 和 RPC 配置原样保留, -# sequencer / batch submitter / gas oracle 三个密钥重新生成(私钥不会被打印) -# 6. 写 run/archive/<时间戳>/MANIFEST.tsv(原路径现路径),restore 就靠它 +# What run does (in order): +# 1. Check the submitter's balance on L1; above SWEEP_THRESHOLD_ETH (default 0.02) it refuses, so recover the funds first (--ignore-balance skips this) +# 2. morph-native.sh down (stops every process) +# 3. Move the run data under run/ (l1, l2, failed attempts, test output, logs) to run/archive// +# 4. --with-build: also move the binaries and build products (bin/, go-ethereum/build/bin, node/build/bin, the tx-submitter binary, +# gas-oracle/app/target, and contracts' node_modules/artifacts/dist/typechain-types). All of these are ignored by git +# 5. --new-keys: move the old env/secrets.env to env/archive/secrets-.env and create a new one: the deployer key and the RPC settings are kept, +# the sequencer / batch submitter / gas oracle keys (and the challenger key, if the file has one) are generated again (private keys are never printed) +# 6. Write run/archive//MANIFEST.tsv (original path new path); restore relies on it # -# 不碰:仓库里被 git 跟踪的文件、deployer 密钥、notes/ 与 docs、deployments/(部署记录)。 -# 公共 Hoodi 上已部署的合约不受影响(链上的东西没法"清空")。 +# Not touched: files tracked by git, the deployer key, notes/ and docs, deployments/ (deployment records). +# Contracts already deployed on public Hoodi are not affected (nothing on a chain can be "emptied"). set -euo pipefail ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" diff --git a/ops/native-hoodi/scripts/setup-nodes.py b/ops/native-hoodi/scripts/setup-nodes.py index 8c9d47099..e54d6aa98 100755 --- a/ops/native-hoodi/scripts/setup-nodes.py +++ b/ops/native-hoodi/scripts/setup-nodes.py @@ -1,17 +1,17 @@ #!/usr/bin/env python3 -"""setup-nodes.py — 生成 2 节点(单序列器)Morph L2 的本地运行目录,不依赖 Docker。 - -改编自上游 ops/devnet-morph/devnet/setup_nodes.py,差异: - - 只做 node-0(tendermint 验证者,出块)和 node-1(layer1 校验模式,不启动 tendermint)两个节点 - - 所有路径落在 --run-dir 下;所有主机名换成 127.0.0.1;端口按 PLAN.md 第 6 节分开 - - 不依赖 PATH 里的 tendermint,用 --tendermint 指定全路径 - - 同时初始化两个 morph-geth 的数据目录(geth init)并放好 nodekey / static-nodes.json - -输出(都在 --run-dir 下): - nodes/node0, nodes/node1 tendermint / morphnode 的 home - el0, el1 morph-geth 的 datadir(已 init) - jwt-secret.txt 引擎 API 的 JWT -幂等:目标目录已存在则拒绝覆盖(不删除任何东西,换一个 --run-dir 或自行处理)。 +"""setup-nodes.py — create the local run directories of a 2-node (single sequencer) Morph L2, without Docker. + +Adapted from upstream ops/devnet-morph/devnet/setup_nodes.py. Differences: + - only node-0 (Tendermint validator, produces blocks) and node-1 (layer1 verify mode, no Tendermint) + - every path is under --run-dir; every hostname is 127.0.0.1; the ports are split as in PLAN.md section 6 + - does not rely on a tendermint on PATH: the full path is given with --tendermint + - also initialises the data directories of both morph-geth instances (geth init) and places nodekey / static-nodes.json + +Output (all under --run-dir): + nodes/node0, nodes/node1 Tendermint / morphnode home directories + el0, el1 morph-geth data directories (already initialised) + jwt-secret.txt JWT of the engine API +Idempotent: it refuses to overwrite an existing target directory (nothing is deleted; use another --run-dir or deal with it yourself). """ import argparse import base64 @@ -23,7 +23,7 @@ import subprocess import sys -# 端口规划(PLAN.md 第 6 节) +# Port plan (PLAN.md section 6) EL = { "el0": dict(http=8545, ws=8546, authrpc=8551, p2p=30303, metrics=6060), "el1": dict(http=8645, ws=8646, authrpc=8651, p2p=30304, metrics=6061), @@ -32,7 +32,7 @@ def node_id(node_key_path): - """tendermint 节点 ID = sha256(ed25519 公钥)前 20 字节;私钥 = seed(32) || pubkey(32)。""" + """Tendermint node ID = the first 20 bytes of sha256(ed25519 public key); private key = seed(32) || pubkey(32).""" with open(node_key_path) as f: priv = json.load(f)["priv_key"]["value"] return hashlib.sha256(base64.b64decode(priv)[32:]).hexdigest()[:40] @@ -45,11 +45,11 @@ def run(cmd, **kw): def main(): ap = argparse.ArgumentParser() - ap.add_argument("--morph", required=True, help="Morph 仓库根目录") - ap.add_argument("--run-dir", required=True, help="输出目录(必须不存在或为空)") - ap.add_argument("--genesis", required=True, help="L2 创世文件 genesis-l2.json") - ap.add_argument("--tendermint", required=True, help="tendermint 二进制的全路径") - ap.add_argument("--geth", required=True, help="morph-geth 二进制的全路径") + ap.add_argument("--morph", required=True, help="root directory of the Morph repository") + ap.add_argument("--run-dir", required=True, help="output directory (must not exist, or be empty)") + ap.add_argument("--genesis", required=True, help="L2 genesis file genesis-l2.json") + ap.add_argument("--tendermint", required=True, help="full path of the tendermint binary") + ap.add_argument("--geth", required=True, help="full path of the morph-geth binary") a = ap.parse_args() docker_dir = os.path.join(a.morph, "ops", "docker") From 4bda90c0fd824ad8ac1edfe0f73ad04329e2a3b9 Mon Sep 17 00:00:00 2001 From: Agnar Song Date: Mon, 30 Nov 2026 07:12:46 +0000 Subject: [PATCH 13/23] docs(native-hoodi): translate the runbook and the notes to English, and add the submodule step RUNBOOK.md and notes/ (issues, budget, config-audit, hoodi-probe, versions) were in Chinese. Same content in English. A few statements were brought in line with the current scripts while translating: the keys are made by init-secrets.sh (not by hand with cast), owner and fee-recipient addresses come from the deployer, l2StakingPks is gone from the genesis config, references to PLAN.md and TODO.md (not in the repository) are dropped, and the budget now includes the funds that go on to the submitter and the challenger. Two entries are added to issues.md (node-2 genesis, fixed deployer addresses). README and RUNBOOK also get the step that was missing from the from-zero flow: go-ethereum is a git submodule and is empty after a plain clone, so build-all.sh fails at its first step without git submodule update --init go-ethereum. Co-Authored-By: Claude Sonnet 5.5 --- ops/native-hoodi/README.md | 3 +- ops/native-hoodi/RUNBOOK.md | 200 +++++----- ops/native-hoodi/notes/budget.md | 52 +-- ops/native-hoodi/notes/config-audit.md | 61 +-- ops/native-hoodi/notes/hoodi-probe-raw.txt | 6 +- ops/native-hoodi/notes/hoodi-probe.md | 38 +- ops/native-hoodi/notes/issues.md | 444 +++++++++++---------- ops/native-hoodi/notes/versions.md | 54 +-- 8 files changed, 443 insertions(+), 415 deletions(-) diff --git a/ops/native-hoodi/README.md b/ops/native-hoodi/README.md index 99dd02367..2f51b682e 100644 --- a/ops/native-hoodi/README.md +++ b/ops/native-hoodi/README.md @@ -59,7 +59,8 @@ Ports used on 127.0.0.1 (stop other local devnets first): 18546, 8545/8546/8551, All commands from this directory (`ops/native-hoodi/`). ```bash -# 1. build all binaries into ./bin (about 5-10 minutes the first time) +# 1. fetch the go-ethereum submodule (empty after a plain clone), then build all binaries into ./bin (about 5-10 minutes the first time) +git submodule update --init go-ethereum scripts/build-all.sh # 2. keys: your funded deployer key (it becomes the owner of everything; the public Anvil key is refused) + four generated ones (sequencer, batch submitter, gas oracle, challenger). Prints diff --git a/ops/native-hoodi/RUNBOOK.md b/ops/native-hoodi/RUNBOOK.md index be2a9f372..e7adc6269 100644 --- a/ops/native-hoodi/RUNBOOK.md +++ b/ops/native-hoodi/RUNBOOK.md @@ -1,150 +1,152 @@ -# 运行手册:Morph L2(原生进程)+ 公共 Hoodi 作为 L1 +# Runbook: Morph L2 (native processes) with public Hoodi as L1 -这份手册讲**怎么用**这套环境。想了解**为什么这样设计、中间踩过什么坑**,看 `PLAN.md` 和 `notes/issues.md`。 +This runbook is about **how to use** this setup. For **why it is built this way and the problems met on the way**, see `notes/issues.md`. -## 1. 它是什么 +## 1. What it is -在本机用原生进程(不用 Docker)跑一条私有的 Morph L2(链 ID 53077),它的 L1 是**公共的以太坊 Hoodi 测试网**(链 ID 560048)。合约部署在 Hoodi 上,批次以 EIP-4844 blob 交易提交到 Hoodi。 +A private Morph L2 (chain id 53077) runs on this machine as native processes (no Docker). Its L1 is the **public Ethereum Hoodi testnet** (chain id 560048). The contracts are deployed on Hoodi, and batches are submitted to Hoodi as EIP-4844 blob transactions. ``` - 公共 Hoodi:执行层 RPC(主 ethpandaops,备 0xrpc.io / publicnode)+ 信标 RPC(ethpandaops / publicnode) + public Hoodi: execution RPC (main ethpandaops, fallbacks 0xrpc.io / publicnode) + beacon RPC (ethpandaops / publicnode) ▲ - l1-proxy(本机 127.0.0.1:18546,rpc-consistency-proxy.js)——所有进程访问 L1 都经过它 + l1-proxy (local 127.0.0.1:18546, rpc-consistency-proxy.js) - every process reaches L1 through it ▲ - ┌──────┴────────────────────────────────────────────────────────────────────────┐ - │ morph-el-0 ◀▶ node-0 出块节点(tendermint 单验证者,持有出块密钥) │ - │ morph-el-1 ◀▶ node-1 layer1 校验模式:不跑 tendermint,独立从 L1 的 blob 还原 │ - │ morph-el-2 ◀▶ node-2 全节点:跑 tendermint,没有出块密钥。**只为让 node-0 能重启** │ - │ tx-submitter 把 L2 批次提交到 Hoodi 的 Rollup,并最终化 │ - │ gas-price-oracle 把 L1 费用写入 L2 的 GasPriceOracle │ - │ challenger(可选) 比对批次根,不一致时发起 Rollup.challengeState │ - └────────────────────────────────────────────────────────────────────────────────┘ + ┌──────┴─────────────────────────────────────────────────────────────────────────────┐ + │ morph-el-0 ◀▶ node-0 block producer (Tendermint, single validator, sequencer key) │ + │ morph-el-1 ◀▶ node-1 layer1 verify mode: no Tendermint, re-derives from L1 blobs │ + │ morph-el-2 ◀▶ node-2 full node with Tendermint, no sequencer key. **Only so node-0 can restart** │ + │ tx-submitter submits the L2 batches to the Rollup on Hoodi and finalizes them │ + │ gas-price-oracle writes the L1 fees into the L2 GasPriceOracle │ + │ challenger (optional) compares batch roots, sends Rollup.challengeState on a mismatch │ + └──────────────────────────────────────────────────────────────────────────────────────┘ ``` -## 2. 前置条件 +## 2. Prerequisites -- 构建环境见 README 第 2 节。所有脚本通过 `scripts/lib/env.sh` 检查工具链;工具不在 PATH 上时,用环境变量 `MORPH_ENV_FILE` 指向一个设置 PATH 的文件。手工调用 `cast` 时需要自己保证它在 PATH 上。 -- 二进制在 `bin/`:`morph-geth/geth`、`morphnode/morphnode`、`morphnode/tendermint`、`tx-submitter/tx-submitter`、`gas-oracle/app`、`challenger/challenger`(构建方法见 `notes/versions.md` 和 `TODO.md` 的 P1;`build-all.sh` 一并构建)。 -- 密钥在 `env/secrets.env`(权限 600,**不要提交、不要贴到任何地方**),模板是 `env/hoodi.env.example`。5 个角色:deployer、sequencer、batch submitter、gas oracle、challenger(可选,`init-secrets.sh` 每次生成新的)。 +- The build environment is in section 2 of the README. Every script checks the toolchain through `scripts/lib/env.sh`; when a tool is not on PATH, point the environment variable `MORPH_ENV_FILE` at a file that sets PATH. When you call `cast` by hand, make sure it is on PATH yourself. +- `go-ethereum` is a git submodule and is empty after a plain clone: run `git submodule update --init go-ethereum` once before `scripts/build-all.sh`. +- The binaries are in `bin/`: `morph-geth/geth`, `morphnode/morphnode`, `morphnode/tendermint`, `tx-submitter/tx-submitter`, `gas-oracle/app`, `challenger/challenger` (`build-all.sh` builds them all; versions in `notes/versions.md`). +- The keys are in `env/secrets.env` (mode 600, **never commit it or paste it anywhere**); the template is `env/hoodi.env.example`. Five roles: deployer, sequencer, batch submitter, gas oracle, challenger (optional). You supply the deployer key; `scripts/init-secrets.sh` generates the other four, new ones every run. -## 3. 日常操作 +## 3. Daily operation -全部通过 `scripts/morph-native.sh`: +Everything goes through `scripts/morph-native.sh`: -| 命令 | 作用 | +| Command | What it does | |---|---| -| `status` | 9 个进程(加可选的 challenger)、三个 L2 的高度、Hoodi 高度、代理统计、Rollup 已提交批次 | -| `up [NAME...]` | 启动全部或指定进程(按依赖顺序)。`challenger` 不在默认列表里:用 `up challenger` 启动,或在 `env/secrets.env` 设 `CHALLENGER_ENABLE=1` | -| `down` | 停止全部进程(含 challenger),**保留链数据** | -| `kill NAME` / `start NAME` | 停 / 启动单个进程(`kill` 后不会被自动重启) | -| `logs NAME` | 跟随某个进程的日志(文件在 `run/l2/logs/`) | -| `setup` | 用 `deploy-l1.sh` 产出的创世文件生成运行目录(含 node-2) | -| `clean logs` / `clean l2` | **不删除**,只把数据挪到 `run/archive/`。`clean l2` 有重要后果,见第 7 节 | +| `status` | the 9 processes (plus the optional challenger), the heights of the three L2 nodes, the Hoodi height, proxy statistics, the batches committed on the Rollup | +| `up [NAME...]` | start all or the named processes (in dependency order). `challenger` is not in the default list: start it with `up challenger`, or set `CHALLENGER_ENABLE=1` in `env/secrets.env` | +| `down` | stop all processes (including the challenger), **chain data is kept** | +| `kill NAME` / `start NAME` | stop / start one process (after `kill` it is not restarted automatically) | +| `logs NAME` | follow the log of a process (files are in `run/l2/logs/`) | +| `setup` | create the run directories (including node-2) from the genesis that `deploy-l1.sh` produced | +| `clean logs` / `clean l2` | **nothing is deleted**, the data is only moved to `run/archive/`. `clean l2` has an important consequence, see section 7 | -进程名:`l1-proxy morph-el-0 node-0 morph-el-1 node-1 morph-el-2 node-2 tx-submitter gas-price-oracle`,另有可选的 `challenger`。每个进程都在一个自动重启的守护外壳里,崩溃后 2 秒内被拉起。 +Process names: `l1-proxy morph-el-0 node-0 morph-el-1 node-1 morph-el-2 node-2 tx-submitter gas-price-oracle`, and the optional `challenger`. Every process runs inside a self-restarting supervisor shell, so a crashed process is started again within 2 seconds. -## 4. 端口(全部 127.0.0.1) +## 4. Ports (all on 127.0.0.1) -| 进程 | HTTP | WS | 引擎 | p2p | metrics | +| Process | HTTP | WS | Engine | p2p | metrics | |---|---|---|---|---|---| | morph-el-0 | 8545 | 8546 | 8551 | 30303 | 6160 | | morph-el-1 | 8645 | 8646 | 8651 | 30304 | 6161 | | morph-el-2 | 8745 | 8746 | 8751 | 30305 | 6162 | -| node-0(tendermint) | | | | 26656 | 26660;tendermint rpc 26657 | -| node-1 | | | | 不跑 tendermint | 27660 | -| node-2(tendermint) | | | | 26666 | 26670;tendermint rpc 26667 | +| node-0 (Tendermint) | | | | 26656 | 26660; Tendermint rpc 26657 | +| node-1 | | | | no Tendermint | 27660 | +| node-2 (Tendermint) | | | | 26666 | 26670; Tendermint rpc 26667 | | tx-submitter | | | | | 8060 | | gas-price-oracle | | | | | 6070 | -| l1-proxy | 18546(`/stats` 看统计) | | | | | -| challenger(可选) | 8090 | | | | 6065 | +| l1-proxy | 18546 (`/stats` shows statistics) | | | | | +| challenger (optional) | 8090 | | | | 6065 | -geth 的 metrics 端口用 6160 起,是因为有些环境里 6060 已被占用;challenger 同理避开它默认的 8080 / 6060(用 `CHALLENGER_HTTP_PORT` / `CHALLENGER_METRICS_PORT` 可改)。**这些端口(8545、8551、30303 等)与其他本地以太坊 devnet 常用端口相同**,不能同时跑;先 `down` 或换端口。 +The geth metrics ports start at 6160 because 6060 is already taken in some environments; the challenger likewise avoids its defaults 8080 / 6060 (change them with `CHALLENGER_HTTP_PORT` / `CHALLENGER_METRICS_PORT`). **These ports (8545, 8551, 30303 and so on) are the same ones other local Ethereum devnets commonly use**, so two of them cannot run at the same time: `down` one first, or change the ports. -## 5. 从零开始的流程 +## 5. From zero -1. `scripts/build-all.sh`:编译全部二进制、安装合约依赖(P1)。 -2. 生成密钥(`cast wallet new`),写入 `env/secrets.env`;给 **deployer** 和 **batch submitter** 在 Hoodi 上领测试币。 -3. 部署 L1 合约并生成 L2 创世: +1. `git submodule update --init go-ethereum`, then `scripts/build-all.sh`: build every binary and install the contracts' dependencies. +2. `DEPLOYER_PRIVATE_KEY=0x... scripts/init-secrets.sh`: write `env/secrets.env` with your deployer key and four generated keys, and print the addresses. Get Hoodi test coins for the **deployer** address (it pays for the deployment and sends funds on to the batch submitter and the challenger). +3. Deploy the L1 contracts and generate the L2 genesis: ```bash + source env/secrets.env RPC_URL=https://rpc.hoodi.ethpandaops.io RUN_DIR=$PWD/run/l1 WAIT_FINALIZED=1 SUBMITTER_FUND_ETH=1 scripts/deploy-l1.sh - RPC_URL=https://rpc.hoodi.ethpandaops.io scripts/verify-l1.sh # 读链上状态核对,不信退出码 + RPC_URL=https://rpc.hoodi.ethpandaops.io scripts/verify-l1.sh # checks the on-chain state, does not trust exit codes ``` - 约 20 分钟(其中约 13 分钟是等 Hoodi finalized)。**在公共链上花测试币、不可撤销。** - `deploy-l1.sh` 最后还会跑 s34:把 challenger 加入 `Rollup.isChallenger` 并充值到 0.2 ETH(`CHALLENGER_FUND_ETH`)。`env/secrets.env` 里没有 `CHALLENGER_PRIVATE_KEY` 时跳过;已有的旧部署用 `scripts/register-challenger.sh` 补做。 -4. `scripts/morph-native.sh setup`,然后 `up`。 -5. `scripts/l2-bootstrap.sh`:给 deployer 和 oracle 在 L2 上转余额,并把 oracle 密钥加入 GasPriceOracle 白名单(否则 gas-price-oracle 没权限更新)。 -6. 用第 6 节的脚本验证。 -7. (可选)`scripts/morph-native.sh up challenger`,按第 6 节“挑战者”验证。 + About 20 to 45 minutes (about 13 of them waiting for Hoodi to finalize). **It spends testnet coins on a public chain and cannot be undone.** + At the end `deploy-l1.sh` also runs s34: it adds the challenger to `Rollup.isChallenger` and tops it up to 0.2 ETH (`CHALLENGER_FUND_ETH`). The step is skipped when `env/secrets.env` has no `CHALLENGER_PRIVATE_KEY`; for an existing deployment run `scripts/register-challenger.sh`. +4. `scripts/morph-native.sh setup`, then `up`. +5. `scripts/l2-bootstrap.sh`: give the deployer and the oracle a balance on the L2 and put the oracle key on the GasPriceOracle allow list (without it gas-price-oracle has no permission to update). +6. Verify with the scripts of section 6. +7. (Optional) `scripts/morph-native.sh up challenger`, and verify as in "The challenger" of section 6. -## 6. 验证脚本 +## 6. Verification scripts -| 脚本 | 验证什么 | 耗时 | +| Script | What it verifies | Time | |---|---|---| -| `scripts/verify-l1.sh` | 读 Hoodi 上的合约状态:owner、互相引用、创世批次、submitter 质押、所有代理的 implementation 与 admin、第一个序列器(53 项) | 1 分钟 | -| `scripts/deposit-test.sh` | L1→L2 存款到一个全新地址,等两个节点都到账 | 约 7 分钟 | -| `scripts/withdraw-test.sh` | L2→L1 提款:本地生成默克尔证明,在 L1 上领取 | 约 10 分钟 | -| `scripts/restart-test.sh` | 崩溃与重启恢复(T1 到 T8,T7 需单独指定) | 约 35 分钟 | -| `scripts/rpc-consistency-proxy.selftest.js` | 代理的 6 项行为(不碰网络) | 10 秒 | -| `scripts/withdraw-proof.selftest.js` | 默克尔证明算法与合约逐行一致(210 组) | 5 秒 | -| `scripts/probe-hoodi.sh` | 公共 RPC 的限流探测 | 1 分钟 | -| `scripts/register-challenger.sh` | 把 challenger 加入 `Rollup.isChallenger` 并充值(幂等,读回链上结果确认;`deploy-l1.sh` 的 s34 就是它) | 1 分钟 | +| `scripts/verify-l1.sh` | reads the contract state on Hoodi: owners, cross references, the genesis batch, the submitter's stake, implementation and admin of every proxy, the first sequencer (53 checks) | 1 minute | +| `scripts/deposit-test.sh` | L1 to L2 deposit to a fresh address, waits until both nodes have it | about 7 minutes | +| `scripts/withdraw-test.sh` | L2 to L1 withdrawal: builds the Merkle proof locally and claims on L1 | about 10 minutes | +| `scripts/restart-test.sh` | crash and restart recovery (T1 to T8, T7 has to be named separately) | about 35 minutes | +| `scripts/rpc-consistency-proxy.selftest.js` | 6 behaviours of the proxy (no network) | 10 seconds | +| `scripts/withdraw-proof.selftest.js` | the Merkle proof algorithm matches the contract line by line (210 cases) | 5 seconds | +| `scripts/probe-hoodi.sh` | rate-limit probe of the public RPCs | 1 minute | +| `scripts/register-challenger.sh` | adds the challenger to `Rollup.isChallenger` and funds it (idempotent, reads each result back from the chain; it is what s34 of `deploy-l1.sh` runs) | 1 minute | -比较 node-1 与 node-0 是否一致,用 `cast block N --field hash --rpc-url http://127.0.0.1:8545 / 8645 / 8745` 逐块比对(已在三个节点间比过 0 到 7562 共 7563 个块,0 个不一致)。 +To check that node-1 agrees with node-0, compare block by block with `cast block N --field hash --rpc-url http://127.0.0.1:8545 / 8645 / 8745` (blocks 0 to 7562, 7563 in total, were compared across the three nodes with 0 differences). -**挑战者(可选)。** challenger 是个 HTTP 服务,**不会自己轮询**,只在被请求时才动作: +**The challenger (optional).** The challenger is an HTTP service that **does not poll**; it only acts when it is asked: -- `GET /batch/{index}`:读该批次在 L1 的提交交易和 el-0 上同一个块,比对 state root 与 withdraw root。链正常时返回 `"verdict":"match"`,否则 `mismatch` / `inconclusive`。不发交易。 -- `POST /challenge`,body `{"batchIndex":N,"batchHash":"0x..."}`:**只有**该 hash 正是 L1 上当前提交的那个、且根不一致时才发 `Rollup.challengeState`;其它情况都返回 4xx、不发交易。 -- 监听 `127.0.0.1:8090`(无鉴权,所以只绑本机),指标 `127.0.0.1:6065`;L1 走 l1-proxy,L2 读 el-0(归档节点,`--gcmode=archive`,读 withdraw root 需要)。账户是 `env/secrets.env` 里的 `CHALLENGER_PRIVATE_KEY`(不是 deployer)。 +- `GET /batch/{index}`: reads the commit transaction of that batch on L1 and the same block on el-0, and compares the state root and the withdraw root. While the chain is honest it returns `"verdict":"match"`, otherwise `mismatch` / `inconclusive`. It sends no transaction. +- `POST /challenge` with body `{"batchIndex":N,"batchHash":"0x..."}`: it sends `Rollup.challengeState` **only** when that hash is exactly the one currently committed on L1 and the roots differ; every other case returns 4xx and sends nothing. +- It listens on `127.0.0.1:8090` (no authentication, so it only binds to localhost) with metrics on `127.0.0.1:6065`; it reaches L1 through the l1-proxy and reads the L2 from el-0 (an archive node, `--gcmode=archive`, which reading the withdraw root needs). Its account is `CHALLENGER_PRIVATE_KEY` from `env/secrets.env` (not the deployer). ```bash scripts/morph-native.sh up challenger curl -s http://127.0.0.1:8090/health # {"status":"ok"} FIN=$(cast call $ROLLUP 'lastFinalizedBatchIndex()(uint256)' --rpc-url "$L1_ETH_RPC") curl -s http://127.0.0.1:8090/batch/$FIN # 409 "batch already finalized" -curl -s http://127.0.0.1:8090/batch/$((FIN + 1)) # 已提交未 finalized 的批次:"verdict":"match"(还没有则 404) +curl -s http://127.0.0.1:8090/batch/$((FIN + 1)) # a committed, not yet finalized batch: "verdict":"match" (404 when there is none yet) ``` -成功的挑战是一笔真实交易:锁定保证金(`challengeDeposit`),并让 finalize 停住,直到 Rollup owner 调 `revertBatch`;超过 `proofWindow` 后,提交该批次的 submitter 会被罚没。不要随手发。全部配置项见 `challenger/env.example`。 +A successful challenge is a real transaction: it locks the deposit (`challengeDeposit`) and stops finalization until the Rollup owner calls `revertBatch`; once `proofWindow` has passed, the submitter that committed the batch is slashed. Do not send one casually. All options are in `challenger/env.example`. -## 7. 必须知道的限制和坑 +## 7. Limits and pitfalls you must know -1. **node-2 不能去掉。** 出块节点 node-0 重启后,必须有至少一个 tendermint 对端它才会恢复出块;没有时它静默停转(进程在、RPC 在、日志无错误、高度冻结)。node-1 是 layer1 校验模式,不算 tendermint 对端。见 `notes/issues.md` I-028。 -2. **L2 和 L1 上的 Rollup 是一一绑定的。** L1 上已提交的批次绑定着当前这条 L2 链。把 L2 清空重新从创世出块,新区块与旧批次对不上,tx-submitter 无法继续。**重置 L2 必须同时重新部署 L1 合约**(新的 `RUN_DIR`),所以 `clean l2` 只是把数据挪走。 -3. **存款的 gas 上限要给够。** 仓库示例里的 `110000` 在这套部署上会让 L2 上的执行失败(钱锁在 L1 网关里)。`deposit-test.sh` 默认 400000。 -4. **公共 RPC 不可靠。** 背后是多个节点:刚上链的区块可能读不到,偶尔限流。`l1-proxy` 解决这两件事,所有进程都应经过它,不要直接连 Hoodi。 -5. **node-1 不是实时的。** 它按批次推进,批次提交到 L1 后才前进,所以总会落后几百个块(约一个批次)。 -6. **不要把 `hardhat` 任务的退出码当成功。** 它们出错时常常只打印一行然后退出码为 0。部署后用 `verify-l1.sh` 读链上状态。 -7. **owner / 管理员 / 费用接收方都是 deployer,不是写死在仓库里的地址。** `deploy-l1.sh` 从 `env/secrets.env` 的密钥推导出地址,经环境变量传给 `hoodidev.ts`,并填进生成的创世配置(`run/l1/hoodidev-deploy-config.generated.json`)。谁来部署,谁就是 owner。序列器集合、Tendermint 与 BLS 公钥是固定的。 -8. **改动在 git 里。** 对上游仓库的改动只有 4 个文件:`contracts/hardhat.config.ts`(加网络 `hoodidev`)、`contracts/src/deploy-config/hoodidev.ts`、`ops/l2-genesis/deploy-config/hoodidev-deploy-config.json`、`contracts/src/deploy-utils.ts`(可选的读重试)。 -9. **challenger 不会自动挑战。** 它不轮询 L1,必须有人 `POST /challenge`。挑战成功后 finalize 会停住,需要 owner `revertBatch` 收尾;`proofWindow` 过后调 `proveState` 判挑战方胜,会罚没提交该批次的 submitter 并让合约进入 `pending revert request`。 +1. **node-2 cannot be removed.** After a restart the block producer node-0 only resumes block production when it has at least one Tendermint peer; without one it stalls silently (the process is up, the RPC is up, the log shows no error, the height is frozen). node-1 runs in layer1 verify mode and does not count as a Tendermint peer. See `notes/issues.md` I-028. node-2 must be built from the genesis of the deployment it belongs to (`L1_RUN`); a different genesis makes it reject every block with `wrong parent hash`. +2. **The L2 and the Rollup on L1 are bound one to one.** The batches already committed on L1 are bound to this L2 chain. If you empty the L2 and produce blocks from genesis again, the new blocks do not match the old batches and tx-submitter cannot continue. **Resetting the L2 means deploying the L1 contracts again** (with a new `RUN_DIR`), which is why `clean l2` only moves the data away. +3. **Give deposits enough gas.** The `110000` in the repository's examples makes the execution fail on the L2 in this deployment (the money stays locked in the L1 gateway). `deposit-test.sh` defaults to 400000. +4. **Public RPCs are unreliable.** Several nodes sit behind them: a block that was just mined may not be readable, and there is occasional rate limiting. `l1-proxy` solves both; every process should go through it, do not connect to Hoodi directly. +5. **node-1 is not real time.** It advances per batch, only after the batch is committed to L1, so it always lags by a few hundred blocks (about one batch). +6. **Do not treat the exit code of a `hardhat` task as success.** On errors they often print one line and still exit with 0. After deploying, read the on-chain state with `verify-l1.sh`. +7. **Owner, admin and fee recipient are the deployer; no such address is fixed in the repository.** `deploy-l1.sh` derives the addresses from the keys in `env/secrets.env`, passes them to `hoodidev.ts` through the environment and fills them into the generated genesis config (`run/l1/hoodidev-deploy-config.generated.json`). Whoever deploys is the owner. The sequencer set and the Tendermint and BLS public keys are fixed. +8. **The changes outside this directory are in git.** Only 4 files of the upstream repository are changed: `contracts/hardhat.config.ts` (adds the network `hoodidev`), `contracts/src/deploy-config/hoodidev.ts`, `ops/l2-genesis/deploy-config/hoodidev-deploy-config.json`, `contracts/src/deploy-utils.ts` (optional read retries). +9. **The challenger does not challenge by itself.** It does not poll L1; someone has to `POST /challenge`. After a successful challenge finalization stops and the owner has to close it with `revertBatch`; after `proofWindow`, `proveState` rules for the challenger, slashes the submitter that committed the batch, and puts the contract into `pending revert request`. -## 8. 成本(实测) +## 8. Cost (measured) -| 项目 | 数值 | +| Item | Value | |---|---| -| L1 合约部署 | 77 笔交易、5130 万 gas;按 1 gwei 约 0.06 ETH(含 0.01 ETH 的 submitter 质押) | -| tx-submitter 运行 | 约 0.0004 ETH / 批次;批次约每 7 分钟一个,约 0.09 ETH / 天 | -| challenger 充值 | 部署时转 0.2 ETH(`CHALLENGER_FUND_ETH`);一次挑战锁定 0.01 ETH 保证金 + 约 0.0002 ETH gas | -| 部署期间的损耗 | 前几次失败遗留的孤儿合约,合计不到 0.2 ETH | +| L1 contract deployment | 77 transactions, 51.3 million gas; about 0.06 ETH at 1 gwei (including the 0.01 ETH submitter stake) | +| tx-submitter running | about 0.0004 ETH per batch; one batch about every 7 minutes, about 0.09 ETH per day | +| Challenger funding | 0.2 ETH sent at deployment (`CHALLENGER_FUND_ETH`); one challenge locks a 0.01 ETH deposit plus about 0.0002 ETH of gas | +| Losses while deploying | orphan contracts left by the first failed attempts, less than 0.2 ETH in total | -## 9. 故障排查 +## 9. Troubleshooting -| 现象 | 可能原因与做法 | +| Symptom | Likely cause and what to do | |---|---| -| L2 高度不动,进程都在 | 先看 node-0 日志是否停在 `derivation skipped: sequencer mode`:node-2 没跑,或没连上。`status` 看 node-2,日志里应有 `Added peer` | -| node-1 高度不涨 | 正常:等下一个批次提交。`status` 里 `lastCommittedBatchIndex` 在涨就没问题 | -| `failed to fetch L1 messages ... beyond current head` | 落后的 L1 后端;代理会重试。偶发无需处理 | -| gas-price-oracle 报 `ErrCallerNotAllowed` | 没跑 `l2-bootstrap.sh`,oracle 不在白名单 | -| 存款后 L2 没到账,但 L1 消息已入队 | 在 L2 上找类型 `0x7e` 的交易看回执:状态 0 通常是 `_gasLimit` 太小 | -| 起不来,端口被占 | 先 `scripts/morph-native.sh down`;本机上别的 devnet 或节点在用同样的端口也会冲突(`ss -ltn` 查) | -| `up challenger` 报缺 `CHALLENGER_PRIVATE_KEY` / `bin/challenger/challenger` | 旧的 `env/secrets.env` 没有该密钥(加一把 `cast wallet new`,再跑 `register-challenger.sh`);二进制要先跑 `build-all.sh` | -| `POST /challenge` 返回 `only challenger allowed` | challenger 账户没加入 `Rollup.isChallenger`:跑 `scripts/register-challenger.sh` | -| challenger 进程反复重启 | 看 `logs challenger`:L2 RPC 的链与 Rollup 对不上时它拒绝启动;确认 el-0 在跑、`L1_RUN` 指向当前部署 | - -## 10. 重置与部署记录(2026-11-19 新增,已用这套流程完整重做过一次) - -- `scripts/reset-env.sh plan|run|restore|list`:把运行数据(和可选的构建产物 `--with-build`、密钥 `--new-keys`)用 `mv` 归档到 `run/archive/<时间戳>/`,`restore` 可原样挪回。不删除任何东西。submitter 在 L1 上余额高于 0.02 ETH 时拒绝执行,先用 `scripts/sweep-submitter.sh`(要先 `down`)把钱转回 deployer。 -- `scripts/export-deployment.sh NAME`:把一次部署的合约地址、创世文件、账户地址(无私钥)、版本、测试输出存到 `deployments/NAME/`。重置之前先导出。 -- 已有记录:`deployments/devnet-1/`(旧)、`deployments/devnet-2/`(当前)。 -- 重做顺序:sweep → export 旧部署 → reset-env run --with-build --new-keys → build-all → deploy-l1(约 43 分钟,其中 `s30_initialize` 约 20 分钟)→ verify-l1 → setup → up → l2-bootstrap → 存款/提款/重启测试。 +| L2 height does not move, all processes are up | First check whether the node-0 log stops at `derivation skipped: sequencer mode`: node-2 is not running or not connected. Look at node-2 in `status`; its log should contain `Added peer`. If node-2 logs `wrong parent hash`, its genesis differs from node-0's: compare `cast block 0 --field hash` on 8545 and 8745 | +| node-1 height does not grow | Normal: it waits for the next batch to be committed. As long as `lastCommittedBatchIndex` in `status` grows, it is fine | +| `failed to fetch L1 messages ... beyond current head` | A lagging L1 backend; the proxy retries. Occasional, no action needed | +| gas-price-oracle reports `ErrCallerNotAllowed` | `l2-bootstrap.sh` was not run, so the oracle is not on the allow list | +| After a deposit the L2 shows nothing, but the L1 message is queued | Find the transaction of type `0x7e` on the L2 and look at its receipt: status 0 usually means `_gasLimit` was too small | +| Cannot start, port in use | First `scripts/morph-native.sh down`; another devnet or node on this machine using the same ports also conflicts (check with `ss -ltn`) | +| `up challenger` complains about a missing `CHALLENGER_PRIVATE_KEY` / `bin/challenger/challenger` | An old `env/secrets.env` has no such key (add one made with `cast wallet new`, then run `register-challenger.sh`); the binary needs `build-all.sh` first | +| `POST /challenge` returns `only challenger allowed` | The challenger account is not on `Rollup.isChallenger`: run `scripts/register-challenger.sh` | +| The challenger process keeps restarting | Look at `logs challenger`: it refuses to start when the chain behind the L2 RPC does not match the Rollup; make sure el-0 is running and `L1_RUN` points at the current deployment | + +## 10. Reset and deployment records (added 2026-11-19, the whole flow has been redone once) + +- `scripts/reset-env.sh plan|run|restore|list`: archives the run data (and optionally the build products with `--with-build`, and the keys with `--new-keys`) with `mv` into `run/archive//`; `restore` moves everything back as it was. Nothing is deleted. It refuses to run when the submitter holds more than 0.02 ETH on L1; first move the money back to the deployer with `scripts/sweep-submitter.sh` (run `down` first). +- `scripts/export-deployment.sh NAME`: stores the contract addresses, the genesis files, the account addresses (no private keys), the versions and the test output of a deployment in `deployments/NAME/`. Export before resetting. +- Existing records: `deployments/devnet-1/` (old), `deployments/devnet-2/` (current). +- Order of a redo: sweep, export the old deployment, `reset-env run --with-build --new-keys`, `build-all`, `deploy-l1` (about 43 minutes, of which `s30_initialize` takes about 20), `verify-l1`, `setup`, `up`, `l2-bootstrap`, then the deposit / withdrawal / restart tests. diff --git a/ops/native-hoodi/notes/budget.md b/ops/native-hoodi/notes/budget.md index 13f57b9b8..406566fa4 100644 --- a/ops/native-hoodi/notes/budget.md +++ b/ops/native-hoodi/notes/budget.md @@ -1,38 +1,40 @@ -# 资金预算(P2-5 的结果) +# Funds budget (result of P2-5) -依据:在 Hoodi 的 anvil 分叉上把 `scripts/deploy-l1.sh` 完整干跑了一遍(`run/dryrun-1/`),**所有步骤成功**。分叉里的交易不花公共 Hoodi 的任何币。 +Basis: the whole of `scripts/deploy-l1.sh` was rehearsed on an anvil fork of Hoodi (`run/dryrun-1/`), and **every step succeeded**. Transactions in the fork do not spend any coin of public Hoodi. -## 实测 +## Measured -| 项 | 数值 | +| Item | Value | |---|---| -| deployer 发出的交易数 | **77** | -| 总 gas | **51,304,680**(最大的一笔 4,780,806,远低于区块 gas 上限 6000 万) | -| submitter 质押(由 deployer 代付) | 0.01 ETH(配置里调低过,默认是 1 ETH) | -| 干跑时 deployer 实际花费 | 0.0179 ETH(= 约 0.0079 ETH gas + 0.01 ETH 质押),对应分叉里约 0.15 gwei 的 gas 价格 | -| 耗时 | 部署约 2 分钟,初始化约 2 分钟,总共约 4 分钟(分叉里无需等待确认) | +| Transactions sent by the deployer | **77** | +| Total gas | **51,304,680** (the largest one 4,780,806, far below the 60 million block gas limit) | +| Submitter stake (paid by the deployer) | 0.01 ETH (lowered in the configuration; the default is 1 ETH) | +| What the deployer actually spent in the dry run | 0.0179 ETH (about 0.0079 ETH gas + 0.01 ETH stake), at a gas price of about 0.15 gwei in the fork | +| Duration | about 2 minutes to deploy, about 2 minutes to initialise, about 4 minutes in total (no confirmations to wait for in the fork) | -## 按不同 gas 价格换算 deployer 的需求 +## The deployer's need at different gas prices -(51,304,680 gas × 价格 + 0.01 ETH 质押) +(51,304,680 gas x price + 0.01 ETH stake) -| Hoodi gas 价格 | deployer 需要 | +| Hoodi gas price | The deployer needs | |---|---| -| 0.15 gwei | 约 0.018 ETH | -| 0.5 gwei | 约 0.036 ETH | -| 1 gwei(我 09:19 测到的 1.08 gwei) | 约 0.061 ETH | -| 2 gwei | 约 0.113 ETH | -| 5 gwei | 约 0.267 ETH | +| 0.15 gwei | about 0.018 ETH | +| 0.5 gwei | about 0.036 ETH | +| 1 gwei (I measured 1.08 gwei at 09:19) | about 0.061 ETH | +| 2 gwei | about 0.113 ETH | +| 5 gwei | about 0.267 ETH | -**建议 deployer 备 0.2 ETH**(覆盖 gas 涨到约 3 gwei,并留余量)。真正部署前再查一次当时的 gas 价格。 +**Keep 0.2 ETH on the deployer** (it covers gas rising to about 3 gwei and leaves a margin). Check the gas price again right before the real deployment. -## submitter +This covers the contract deployment only. A full run of `deploy-l1.sh` also sends `SUBMITTER_FUND_ETH` (1 ETH in the README flow) to the batch submitter and, when a challenger key is configured, `CHALLENGER_FUND_ETH` (0.2 ETH) to the challenger. The preflight of `deploy-l1.sh` checks that the deployer's balance covers all of it. -- 这次**没有实测**:干跑里 submitter 没发交易(批次提交要等 L2 跑起来)。 -- 它每个批次要发一笔 blob 交易。blob 费用本身很低(Hoodi 当时 blob base fee 约 0.05 gwei),主要成本是执行 gas。 -- 批次间隔由配置决定(`govBatchBlockInterval=200` 个块 / `govBatchTimeout=600` 秒),大致每 10 分钟一个批次(L2 有交易时更快)。 -- **估算(未实测):** 先备 **0.1 ETH**,P6 跑起来后按实际消耗再调;`TX_SUBMITTER_TX_FEE_LIMIT` 要调低。 +## Submitter -## 结论 +- It was **not measured** this time: the submitter sent no transaction in the dry run (batches are only submitted once the L2 is running). +- It sends one blob transaction per batch. The blob fee itself is very low (the Hoodi blob base fee was about 0.05 gwei at the time); the main cost is execution gas. +- The batch interval is set by the configuration (`govBatchBlockInterval=200` blocks / `govBatchTimeout=600` seconds), roughly one batch every 10 minutes (faster when the L2 has transactions). +- **Estimate (not measured):** start with **0.1 ETH** and adjust to the real consumption once P6 is running; `TX_SUBMITTER_TX_FEE_LIMIT` has to be lowered. -**所需的测试币比我最初担心的少很多:合计约 0.3 ETH 量级就够。** 水龙头单次通常能领到这个数量级,所以 R2(领不到足够测试币)的风险下降,但领币本身还没有验证过。 +## Conclusion + +**The testnet coins needed are far fewer than I first feared: about 0.3 ETH in total is enough.** A faucet can usually give an amount of that order in one claim, so the risk R2 (not getting enough testnet coins) goes down, but claiming from a faucet has not been verified yet. diff --git a/ops/native-hoodi/notes/config-audit.md b/ops/native-hoodi/notes/config-audit.md index a0c12cf6b..4b50a765e 100644 --- a/ops/native-hoodi/notes/config-audit.md +++ b/ops/native-hoodi/notes/config-audit.md @@ -1,43 +1,44 @@ -# 配置审计(P3-4 ~ P3-7) +# Configuration audit (P3-4 ~ P3-7) -结论先行:**Hoodi 上不需要给任何 staking 地址或 BLOCK_SIGNER 打币;但 deployer 要多备一笔 submitter 的质押。** +Conclusion first: **nobody needs to send coins to any staking address or to BLOCK_SIGNER on Hoodi; the deployer, however, must keep extra funds for the submitter's stake.** -## 1. 配置里的密钥与地址 +## 1. Keys and addresses in the configuration -| 配置项 | 性质 | 在哪里用 | Hoodi 上怎么办 | +| Config item | Nature | Where it is used | What to do on Hoodi | |---|---|---|---| -| `BLOCK_SIGNER_PRIVATE_KEY` | **Anvil 公开私钥** | 只在 `ops/devnet-morph/devnet/__init__.py:190`,用来在 devnet 的 L1 上给 `l2StakingAddresses` 打 10 ETH;Go 创世工具**完全不读它** | 删除 | -| `BLOCK_SIGNER_ADDRESS` | 地址 | 代码里没有任何读取 | 保留字段,换成 sequencer 地址,无实际作用 | -| `l2StakingAddresses / Pks / TmKeys / BlsKeys` | 地址与**公钥** | 只进入 **L2 创世**(`immutables.go`,L2Staking 合约的序列器集合);从不在 L1 发交易 | 沿用;**不需要在 Hoodi 上给它们打币** | -| `finalSystemOwner / proxyAdminOwner / gasPriceOracleOwner / recordOracleAddress / morphTokenOwner` | L2 合约的 owner | L2 创世 | 全部换成 deployer 地址 | -| `l1FeeVaultRecipient / sequencerFeeVaultRecipient / l2BridgeFeeVaultRecipient` | 费用接收地址 | L2 创世 | 换成 deployer 地址 | +| `BLOCK_SIGNER_PRIVATE_KEY` | **public Anvil key** | only in `ops/devnet-morph/devnet/__init__.py:190`, to send 10 ETH to `l2StakingAddresses` on the devnet's L1; the Go genesis tool **does not read it at all** | remove | +| `BLOCK_SIGNER_ADDRESS` | address | nothing in the code reads it | keep the field, put the sequencer address in it; no real effect | +| `l2StakingAddresses / TmKeys / BlsKeys` | addresses and **public keys** | only go into the **L2 genesis** (`immutables.go`, the sequencer set of the L2Staking contract); never used to send a transaction on L1 | keep as is; **no need to fund them on Hoodi** | +| `l2StakingPks` | upstream devnet test private keys | nothing in this repository reads it (the devnet driver used it for the funding above) | **removed from `hoodidev-deploy-config.json`**, so that no private key is stored in this configuration | +| `finalSystemOwner / proxyAdminOwner / gasPriceOracleOwner / recordOracleAddress / morphTokenOwner` | owners of L2 contracts | L2 genesis | the deployer address, filled in by `deploy-l1.sh` (placeholder `REPLACE_WITH_DEPLOYER_ADDRESS` in the tracked file) | +| `l1FeeVaultRecipient / sequencerFeeVaultRecipient / l2BridgeFeeVaultRecipient` | fee recipient addresses | L2 genesis | the deployer address, filled in the same way | -## 2. `l1StartingBlockTag`(P3-5) +## 2. `l1StartingBlockTag` (P3-5) -- 格式:geth 的 `rpc.BlockNumberOrHash`,可以是 `"earliest"` / `"latest"` 等标签、十六进制块号字符串(如 `"0x3da3eb"`),或 `{"blockHash": ...}`。 -- 创世工具(`cmd/genesis/cmd.go`)用 `BlockByNumber` / `BlockByHash` 取这个 L1 区块,取其**哈希、高度、时间戳**写进 `rollup.json`(`L2Time = l1StartBlock.Time()`)。 -- 默认 `earliest` = Hoodi 第 0 块,会让 rollup.json 的 L1 起点是 2025 年 3 月的创世块。 -- **取值方式:** 部署第一笔交易之前,取当时 Hoodi 的最新块号(十六进制),写进配置后再跑创世工具。 -- 当前文件里放的是**故意无法解析**的占位符 `REPLACE_WITH_HOODI_START_BLOCK_HEX`,忘记替换会立刻报错,而不会静默用错值。 -- 节点的 `MORPH_NODE_SYNC_START_HEIGHT` 也用这个块号。 +- Format: geth's `rpc.BlockNumberOrHash`. It can be a label such as `"earliest"` / `"latest"`, a hexadecimal block number string (for example `"0x3da3eb"`), or `{"blockHash": ...}`. +- The genesis tool (`cmd/genesis/cmd.go`) fetches this L1 block with `BlockByNumber` / `BlockByHash` and writes its **hash, height and timestamp** into `rollup.json` (`L2Time = l1StartBlock.Time()`). +- The default `earliest` is block 0 of Hoodi, which would make the L1 starting point of rollup.json the genesis block of March 2025. +- **How to set it:** before sending the first deployment transaction, take the latest Hoodi block number at that moment (hexadecimal), write it into the configuration, then run the genesis tool. +- The tracked file holds a placeholder that **cannot be parsed on purpose**, `REPLACE_WITH_HOODI_START_BLOCK_HEX`, so forgetting to replace it fails at once instead of silently using a wrong value. +- The node's `MORPH_NODE_SYNC_START_HEIGHT` uses the same block number. -## 3. main.py 运行时注入的字段(我们的 driver 要自己处理) +## 3. Fields that main.py injects at run time (our driver has to handle them itself) -| main.py 写入的字段 | 实际是否有效 | 我们怎么做 | +| Field written by main.py | Does it take effect | What we do | |---|---|---| -| `l1GenesisBlockTimestamp` | **无效**。`DeployConfig` 结构里没有这个字段,会被忽略 | 不写 | -| `l1StartingBlockTag = earliest` | 有效,但不适合 Hoodi | 部署时替换为起始块号 | -| `l1StakingProxy = 0x...dEaD` | **必需**。为 0 时 `config.go` 先去找已部署的 L1Staking,找不到就报错;L1Staking 已退役 | 直接写进 `hoodidev-deploy-config.json`(已写) | +| `l1GenesisBlockTimestamp` | **No.** The `DeployConfig` struct has no such field, so it is ignored | do not write it | +| `l1StartingBlockTag = earliest` | Yes, but it does not suit Hoodi | replace it with the starting block number at deployment time | +| `l1StakingProxy = 0x...dEaD` | **Required.** When it is 0, `config.go` first looks for a deployed L1Staking and fails if it finds none; L1Staking is retired | written straight into `hoodidev-deploy-config.json` (done) | -## 4. `register` 与质押(P3-6) +## 4. `register` and staking (P3-6) -- `hardhat register`(`contracts/deploy/021-SubmitterRegister.ts`):owner 先 `addSubmitter(submitter)`,再调用 `stake(submitter, {value: minimumStake - currentStake})`。 -- **质押的钱由 owner(deployer)付**,不是 submitter。 -- 配置里 `submitterMinimumStake`、`submitterChallengeDeposit` 默认都是 **1 ETH**。合约只要求它们大于 0。 -- 我们改成 **0.01 ETH**(`hoodidev.ts` 里),所以 deployer 额外只需要约 0.01 ETH 的质押。 -- 这个小数值能否被 `parseEther` 之类的换算正确处理,会在 anvil 分叉干跑时实测。 +- `hardhat register` (`contracts/deploy/021-SubmitterRegister.ts`): the owner first calls `addSubmitter(submitter)`, then `stake(submitter, {value: minimumStake - currentStake})`. +- **The owner (deployer) pays the stake**, not the submitter. +- `submitterMinimumStake` and `submitterChallengeDeposit` default to **1 ETH** each in the configuration. The contract only requires them to be greater than 0. +- We set both to **0.01 ETH** (in `hoodidev.ts`), so the deployer needs only about 0.01 ETH extra for the stake. +- Whether such a small value is converted correctly by `parseEther` and the like was checked in the anvil fork dry run. -## 5. `hardhat fund`(P3-7) +## 5. `hardhat fund` (P3-7) -- 会给每个 `batchSubmitterPks` 里的账户转 **100 ETH**(余额低于约 10 ETH 时)。Hoodi 上不可行。 -- **driver 不调用它。** 需要时手动向 submitter 转小额(额度由 P2-5 的干跑确定)。 +- It sends **100 ETH** to every account in `batchSubmitterPks` (when the balance is below about 10 ETH). That is not feasible on Hoodi. +- **The driver does not call it.** When needed, send the submitter a small amount by hand (the amount is determined by the dry run of P2-5). diff --git a/ops/native-hoodi/notes/hoodi-probe-raw.txt b/ops/native-hoodi/notes/hoodi-probe-raw.txt index 541939615..d04fc1bb5 100644 --- a/ops/native-hoodi/notes/hoodi-probe-raw.txt +++ b/ops/native-hoodi/notes/hoodi-probe-raw.txt @@ -1,10 +1,10 @@ -== 并发 20 × 3 轮 +== concurrency 20 x 3 rounds EL https://0xrpc.io/hoodi 200x60 avg=0.92s max=1.25s n=60 EL https://rpc.hoodi.ethpandaops.io 200x60 avg=0.39s max=0.63s n=60 BEACON https://beacon.hoodi.ethpandaops.io 200x60 avg=0.46s max=0.71s n=60 BEACON https://ethereum-hoodi-beacon-api.publicnode.com 200x60 avg=0.06s max=0.19s n=60 -== eth_getLogs:区间上限(Morph 的 L1 同步会用) +== eth_getLogs: range limit (Morph's L1 sync uses it) https://0xrpc.io/hoodi span=1000 ok https://0xrpc.io/hoodi span=5000 ok https://0xrpc.io/hoodi span=10000 Request contains invalid block params @@ -14,6 +14,6 @@ BEACON https://ethereum-hoodi-beacon-api.publicnode.com 200x60 avg=0.06s max=0 https://rpc.hoodi.ethpandaops.io span=10000 ok https://rpc.hoodi.ethpandaops.io span=50000 getLogs request exceeded max allowed range -== 信标:近期 slot 的 blob_sidecars 连续取 5 个 +== beacon: blob_sidecars of 5 consecutive recent slots https://beacon.hoodi.ethpandaops.io head_slot=4398552 ok=4 fail=1 https://ethereum-hoodi-beacon-api.publicnode.com head_slot=4398552 ok=4 fail=1 diff --git a/ops/native-hoodi/notes/hoodi-probe.md b/ops/native-hoodi/notes/hoodi-probe.md index 07e1f797c..f85edbc43 100644 --- a/ops/native-hoodi/notes/hoodi-probe.md +++ b/ops/native-hoodi/notes/hoodi-probe.md @@ -1,32 +1,32 @@ -# Hoodi 公共端点探测结果(P2-1、P2-2) +# Hoodi public endpoint probe results (P2-1, P2-2) -探测时间:2026-11-18。脚本:`scripts/probe-hoodi.sh`(并发 20 × 3 轮,只读,对公共服务只做小规模并发)。原始输出:`notes/hoodi-probe-raw.txt`。 +Probed on 2026-11-18. Script: `scripts/probe-hoodi.sh` (concurrency 20 x 3 rounds, read-only, only small-scale concurrency against public services). Raw output: `notes/hoodi-probe-raw.txt`. -## 限流 +## Rate limits -| 端点 | 类型 | 60 个请求的结果 | 平均延迟 | +| Endpoint | Type | Result of 60 requests | Mean latency | |---|---|---|---| -| `https://0xrpc.io/hoodi` | EL | 全部 200 | 0.92 秒 | -| `https://rpc.hoodi.ethpandaops.io` | EL | 全部 200 | 0.39 秒 | -| `https://beacon.hoodi.ethpandaops.io` | 信标 | 全部 200 | 0.46 秒 | -| `https://ethereum-hoodi-beacon-api.publicnode.com` | 信标 | 全部 200 | 0.06 秒 | +| `https://0xrpc.io/hoodi` | EL | all 200 | 0.92 s | +| `https://rpc.hoodi.ethpandaops.io` | EL | all 200 | 0.39 s | +| `https://beacon.hoodi.ethpandaops.io` | beacon | all 200 | 0.46 s | +| `https://ethereum-hoodi-beacon-api.publicnode.com` | beacon | all 200 | 0.06 s | -**这个并发量下没有任何限流。** 更高并发或长时间持续的上限没有测。 +**There was no rate limiting at this concurrency.** The limits under higher or sustained concurrency were not measured. -## eth_getLogs 区间上限 +## eth_getLogs range limit -| 端点 | 1000 | 5000 | 10000 | 50000 | +| Endpoint | 1000 | 5000 | 10000 | 50000 | |---|---|---|---|---| -| 0xrpc.io | ok | ok | 报 `invalid block params` | 报 `invalid block params` | -| ethpandaops | ok | ok | ok | 报 `exceeded max allowed range` | +| 0xrpc.io | ok | ok | `invalid block params` | `invalid block params` | +| ethpandaops | ok | ok | ok | `exceeded max allowed range` | -**Morph 的 L1 同步每次只拉 100 个块**(`node/sync/config.go` 的 `DefaultFetchBlockRange = 100`),远低于两者的上限,不受影响。 +**Morph's L1 sync fetches only 100 blocks at a time** (`DefaultFetchBlockRange = 100` in `node/sync/config.go`), far below the limit of both, so it is not affected. -## 信标 blob_sidecars +## Beacon blob_sidecars -两个信标端点对近期 slot 都能返回 sidecar。第一次连取 5 个 slot 时各有 1 个失败,第二次复查 5 个全部成功,推测是某个 slot 没有区块或没有 blob,属偶发。对 Morph 的影响:取 blob 失败会按序回退到下一个端点,见 `node/derivation/beacon.go`。 +Both beacon endpoints return sidecars for recent slots. When 5 consecutive slots were fetched the first time, one of them failed on each endpoint; a second check of the 5 slots succeeded in full. The likely explanation is a slot without a block or without blobs, so it is occasional. Effect on Morph: when fetching a blob fails, it falls back to the next endpoint in order, see `node/derivation/beacon.go`. -## 结论 +## Conclusion -- EL 主用 **ethpandaops**(延迟低、getLogs 上限高);0xrpc.io 作备用。**这与最初计划里"主用 0xrpc.io"相反**,`env/hoodi.env.example` 与 `env/secrets.env` 同步调整。 -- 信标 morphnode 配两个(ethpandaops 在前、publicnode 在后);gas-oracle 只能配一个。 +- Use **ethpandaops** as the main EL endpoint (low latency, higher getLogs limit) and 0xrpc.io as the fallback. **This is the opposite of the first plan ("0xrpc.io as the main one")**; `env/hoodi.env.example` and `env/secrets.env` were adjusted to match. +- morphnode gets two beacon endpoints (ethpandaops first, publicnode second); gas-oracle can take only one. diff --git a/ops/native-hoodi/notes/issues.md b/ops/native-hoodi/notes/issues.md index b36cbb980..eb339d84f 100644 --- a/ops/native-hoodi/notes/issues.md +++ b/ops/native-hoodi/notes/issues.md @@ -1,248 +1,270 @@ -# 问题与处理记录 +# Problems and how they were handled -按时间顺序,每条记录:现象 → 原因 → 处理 → 对计划的影响。 +In time order, one record per item: symptom, cause, handling, effect on the plan. --- ## 2026-11-18 -### I-001 morph-geth 按计划里的命令编译失败 — 已解决 +### I-001 morph-geth fails to build with the command in the plan - solved -- **现象:** `cd repos/morph/go-ethereum && go run build/ci.go install ./cmd/geth` 报 +- **Symptom:** `cd repos/morph/go-ethereum && go run build/ci.go install ./cmd/geth` fails with `build/ci.go:63:2: use of internal package github.com/morph-l2/go-ethereum/internal/build not allowed` -- **原因:** `go-ethereum` 目录位于 Morph 仓库内,仓库根有 `go.work`,但 `go.work` 没把 `./go-ethereum` 列进去。Go 于是把 `github.com/morph-l2/go-ethereum` 当成**下载的外部依赖**,而不是本地目录,`internal` 包就不允许访问。Docker 版没这个问题,是因为它把 `go-ethereum` 单独拷到 `/go-ethereum`,上面没有 `go.work`。 -- **处理:** 加 `GOWORK=off`。Morph 自己顶层 Makefile 的 `geth` 目标也是这么写的(`env GO111MODULE=on GOWORK=off go run build/ci.go install ./cmd/geth`)。我当初是从 Dockerfile 抄的命令,漏了这一点。 -- **结果:** 编译成功,23 秒;`geth version` 显示 `Version: 2.2.8-mainnet`,与子模块 tag `morph-v2.2.8` 一致。 -- **对计划的影响:** TODO P1-2 的命令已改。 +- **Cause:** the `go-ethereum` directory lives inside the Morph repository, the repository root has a `go.work`, but `go.work` does not list `./go-ethereum`. Go therefore treats `github.com/morph-l2/go-ethereum` as a **downloaded external dependency** instead of a local directory, and `internal` packages may not be accessed. The Docker build has no such problem because it copies `go-ethereum` on its own to `/go-ethereum`, where no `go.work` sits above it. +- **Handling:** add `GOWORK=off`. Morph's own top-level Makefile does the same for its `geth` target (`env GO111MODULE=on GOWORK=off go run build/ci.go install ./cmd/geth`). I had copied the command from the Dockerfile and missed this. +- **Result:** the build succeeds in 23 seconds; `geth version` shows `Version: 2.2.8-mainnet`, matching the submodule tag `morph-v2.2.8`. +- **Effect on the plan:** the command of TODO P1-2 was changed. -### I-002 morphnode 不支持 `--version` +### I-002 morphnode does not support `--version` -- **现象:** `morphnode --version` 报 `flag provided but not defined: -version`。 -- **处理:** 版本用 `morphnode --help` 确认可运行,用 `tendermint version`(0.37.0-alpha.1)确认 tendermint。tx-submitter 支持 `--version`,输出 `v1.0.0-2.2.8-mainnet-ae987b15-...`。 -- **对计划的影响:** 无。P1 的验收标准里"能打印版本"对 morphnode 改为"`--help` 正常输出"。 +- **Symptom:** `morphnode --version` fails with `flag provided but not defined: -version`. +- **Handling:** the version is confirmed by checking that `morphnode --help` runs, and by `tendermint version` (0.37.0-alpha.1) for tendermint. tx-submitter supports `--version` and prints `v1.0.0-2.2.8-mainnet-ae987b15-...`. +- **Effect on the plan:** none. In the acceptance criteria of P1, "can print its version" becomes "`--help` prints normally" for morphnode. -### I-003 tx-submitter 的版本串带 `mainnet` +### I-003 the version string of tx-submitter contains `mainnet` -- **现象:** `tx-submitter version v1.0.0-2.2.8-mainnet-ae987b15-...`;morph-geth 也是 `2.2.8-mainnet`。 -- **说明:** 这只是构建标签,不是说它们要连主网。运行时的链由配置和 genesis 决定(`TX_SUBMITTER_BUILD_ENV=dev`、`--networkid=53077`)。记录在此,避免以后看到 `mainnet` 字样产生误会。 +- **Symptom:** `tx-submitter version v1.0.0-2.2.8-mainnet-ae987b15-...`; morph-geth is also `2.2.8-mainnet`. +- **Note:** this is only a build tag, it does not mean they connect to mainnet. The chain used at run time is decided by the configuration and the genesis (`TX_SUBMITTER_BUILD_ENV=dev`, `--networkid=53077`). Recorded here to avoid confusion when the word `mainnet` shows up later. -### I-004 gas-oracle 启动即 panic:日志目录无写权限 — 已找到处理方式 +### I-004 gas-oracle panics at start: the log directory is not writable - a way around was found -- **现象:** 直接运行 `bin/gas-oracle/app`,在 `src/main.rs:58` panic,`OutputIo(PermissionDenied)`。 -- **原因:** 日志目录默认是 `/data/logs/morph-gas-price-oracle`(`main.rs` 的 `setup_logging`)。Docker 里以 root 运行,这个路径可写;本机没有 root,`/data` 不可写。 -- **处理:** 设置环境变量 `GAS_ORACLE_LOG_DIR` 指向可写目录(计划用 `run/logs/gas-oracle/`)。设置后程序正常启动,打印 `Starting update gas oracle...`,随后因缺少 `L2_GAS_ORACLE_PRIVATE_KEY` 而 panic,这是预期行为。 -- **对计划的影响:** P6-3 的 gas-oracle 环境变量清单要加上 `GAS_ORACLE_LOG_DIR`。 +- **Symptom:** running `bin/gas-oracle/app` directly panics at `src/main.rs:58` with `OutputIo(PermissionDenied)`. +- **Cause:** the log directory defaults to `/data/logs/morph-gas-price-oracle` (`setup_logging` in `main.rs`). In Docker it runs as root and the path is writable; on this machine there is no root and `/data` is not writable. +- **Handling:** set the environment variable `GAS_ORACLE_LOG_DIR` to a writable directory (the plan uses `run/logs/gas-oracle/`). With it set, the program starts normally and prints `Starting update gas oracle...`, then panics because `L2_GAS_ORACLE_PRIVATE_KEY` is missing, which is expected. +- **Effect on the plan:** the list of gas-oracle environment variables in P6-3 has to include `GAS_ORACLE_LOG_DIR`. -### I-005 gas-oracle 的信标地址只支持单个 — 已确认 +### I-005 the beacon address of gas-oracle supports only one endpoint - confirmed -- **现象/依据:** `gas_price_oracle.rs:36` 里 `l1_beacon_rpc: String`;`da_scalar/blob_client.rs` 里把它当 URL 前缀直接拼接 `/eth/v1/beacon/blob_sidecars/`,没有任何逗号拆分或回退。 -- **结论:** `GAS_ORACLE_L1_BEACON_RPC` **不能**配逗号分隔的多个端点,只能配一个。这与 morphnode(支持多个、按序回退)不同。 -- **处理:** gas-oracle 用 `https://beacon.hoodi.ethpandaops.io`;morphnode 配两个。 -- **对计划的影响:** 这就是 TODO P6-3 里"待确认"的那一项,现已确认,`env/hoodi.env.example` 的注释同步修正。 +- **Symptom / evidence:** `l1_beacon_rpc: String` at `gas_price_oracle.rs:36`; `da_scalar/blob_client.rs` uses it as a URL prefix and appends `/eth/v1/beacon/blob_sidecars/` directly, with no comma splitting and no fallback. +- **Conclusion:** `GAS_ORACLE_L1_BEACON_RPC` **cannot** take several comma separated endpoints, only one. This differs from morphnode (several, tried in order). +- **Handling:** gas-oracle uses `https://beacon.hoodi.ethpandaops.io`; morphnode gets two. +- **Effect on the plan:** this was the "to be confirmed" item of TODO P6-3; it is confirmed now and the comment in `env/hoodi.env.example` was corrected to match. -### I-006 合约工具链在 Node 24 上可用 — 风险 R8 解除 +### I-006 the contracts toolchain works on Node 24 - risk R8 is gone -- **结果:** `yarn hardhat compile` 与完整的 `yarn build` 都在 Node v24.19.0 上通过。 -- **对计划的影响:** TODO P1-6 里"若失败则装 Node 18/20"的备选不再需要。PLAN 风险 R8 可关闭。 +- **Result:** `yarn hardhat compile` and the full `yarn build` both pass on Node v24.19.0. +- **Effect on the plan:** the fallback "install Node 18/20 if it fails" of TODO P1-6 is no longer needed. Risk R8 of the PLAN can be closed. -### I-007 node-1 不运行 tendermint,只有 node-0 运行 — 简化了 P5 +### I-007 node-1 does not run Tendermint, only node-0 does - this simplified P5 -- **依据:** `ops/devnet-morph/devnet/setup_nodes.py` 的注释:"node-1 runs with `MORPH_NODE_DERIVATION_VERIFY_MODE=layer1` and never starts tendermint; node-2 has no compose service at all"。`TENDERMINT_PEERS = ("node0", "ha-node0", "ha-node1", "ha-node2")`,不含 node1。 -- **结论:** 单序列器模式下,只有 node-0 是 tendermint 节点;node-1 完全靠 L1 的批次和 blob 还原区块。因此 PBFT 对端的 `persistent_peers` 在这个模式下基本用不上。 -- **对计划的影响:** PLAN 第 6 节端口表里 node-1 去掉 tendermint 端口;TODO P5-1 缩小范围。这也意味着 **node-1 能否与 node-0 一致,完全取决于信标链 blob 是否取得到**,P7-2 因此更关键。 +- **Evidence:** the comment in `ops/devnet-morph/devnet/setup_nodes.py`: "node-1 runs with `MORPH_NODE_DERIVATION_VERIFY_MODE=layer1` and never starts tendermint; node-2 has no compose service at all". `TENDERMINT_PEERS = ("node0", "ha-node0", "ha-node1", "ha-node2")` does not contain node1. +- **Conclusion:** in single-sequencer mode only node-0 is a Tendermint node; node-1 rebuilds blocks entirely from the L1 batches and blobs. The `persistent_peers` of PBFT peers therefore has almost no use in this mode. +- **Effect on the plan:** node-1 loses its Tendermint ports in the port table of section 6 of the PLAN; TODO P5-1 gets a smaller scope. It also means that **whether node-1 agrees with node-0 depends entirely on whether the beacon chain blobs can be fetched**, which makes P7-2 more important. -### I-008 setup_nodes.py 只用标准库 — P1-8 通过 +### I-008 setup_nodes.py uses only the standard library - P1-8 passes -- **结果:** 依赖只有 `base64 hashlib json os re shutil subprocess sys`,Python 3.12.3 可直接运行,无需 `pip install`。 -- **注意:** 脚本开头会检查 PATH 里有没有 `tendermint`,没有就调用 `make install-tendermint`。我们的 driver 复制其逻辑时,要直接用 `bin/morphnode/tendermint` 的全路径,不依赖 PATH。 +- **Result:** its only imports are `base64 hashlib json os re shutil subprocess sys`; Python 3.12.3 runs it directly, no `pip install` needed. +- **Note:** the script starts by checking whether `tendermint` is on PATH and calls `make install-tendermint` if not. When our driver copies that logic it must use the full path `bin/morphnode/tendermint` and not depend on PATH. -### I-009 git 提交被 GPG 签名拦下 — 改为暂存区加补丁 +### I-009 a git commit is stopped by GPG signing - staged changes plus a patch instead -- **现象:** `git commit` 报 `gpg failed to sign the data ... Operation cancelled`。 -- **原因:** 该仓库的 git 配置强制提交签名,而当前环境没有可交互的 GPG 签名。 -- **处理:** 我**没有**为了提交去关闭签名(那是你的签名策略)。三个改动文件保留在 **git 暂存区**,并导出补丁到 `patches/0001-hoodidev-config.patch`(166 行)。 -- **核对:** 补丁里没有出现我们的任何私钥;公开 Anvil 私钥只出现一次,在 `hardhat.config.ts` 的"禁止使用"判断常量里。 -- **需要你做:** 如果要在 `native-hoodi` 分支上留下提交,请你自己提交一次(能走你的签名),或告诉我允许对这个分支临时不签名。 +- **Symptom:** `git commit` fails with `gpg failed to sign the data ... Operation cancelled`. +- **Cause:** the git configuration of the repository forces commit signing, and this environment has no interactive GPG signing. +- **Handling:** I did **not** turn signing off to be able to commit (that is your signing policy). The three changed files stay in the **git index**, and a patch was exported to `patches/0001-hoodidev-config.patch` (166 lines). +- **Check:** none of our private keys appears in the patch; the public Anvil private key appears once, in the "forbidden" comparison constant of `hardhat.config.ts`. +- **For you to do:** if you want a commit on the `native-hoodi` branch, commit once yourself (with your signing), or tell me that I may skip signing on this branch for now. -### I-010 原计划里 P3 的几个"待确认"现已全部确认 +### I-010 the "to be confirmed" items of P3 in the original plan are now all confirmed -见 `notes/config-audit.md`。最重要的两条:`BLOCK_SIGNER_PRIVATE_KEY` 只用于 devnet 给 staking 地址打币,Hoodi 上直接删除;`register` 的质押由 deployer 代付,已把额度从 1 ETH 降到 0.01 ETH。 +See `notes/config-audit.md`. The two most important: `BLOCK_SIGNER_PRIVATE_KEY` is only used by the devnet to fund the staking addresses and is simply deleted on Hoodi; the stake of `register` is paid by the deployer, and the amount was lowered from 1 ETH to 0.01 ETH. -### I-011 干跑脚本里 `printf '%x'` 对 1e20 溢出 — 已修 +### I-011 `printf '%x'` overflows for 1e20 in the dry-run script - fixed -- **现象:** `printf: warning: 100000000000000000000: Numerical result out of range`,给分叉里的账户设置的余额被截成 2^64-1(约 18.4 ETH)。 -- **原因:** bash 的 `printf` 只处理 64 位整数。 -- **处理:** 改用 `cast to-hex`。对这次干跑没有影响(18.4 ETH 足够),只是余额不是原本想设的 100 ETH。 +- **Symptom:** `printf: warning: 100000000000000000000: Numerical result out of range`; the balance set for the accounts in the fork was cut to 2^64-1 (about 18.4 ETH). +- **Cause:** bash `printf` only handles 64-bit integers. +- **Handling:** use `cast to-hex` instead. It made no difference to this dry run (18.4 ETH is enough), only the balance was not the 100 ETH that was intended. -### I-012 分叉里的 gas 价格比我实测的低很多 +### I-012 the gas price in the fork is much lower than what I measured -- **现象:** 我 09:19 直接问 Hoodi 得到 `eth_gasPrice ≈ 1.08 gwei`,而干跑里 deployer 的实际 gas 开销折算出约 0.15 gwei。 -- **原因(推测,未验证):** anvil 分叉按分叉点的区块 base fee 起算,而 Hoodi 的 gas 价格本身会波动。 -- **处理:** 预算按总 gas(这个才是确定的)乘以多档价格,见 `notes/budget.md`。正式部署前再查一次实时价格。 +- **Symptom:** at 09:19 I asked Hoodi directly and got `eth_gasPrice` of about 1.08 gwei, while the deployer's real gas spend in the dry run works out to about 0.15 gwei. +- **Cause (a guess, not verified):** the anvil fork starts from the base fee of the fork point block, and the gas price of Hoodi itself fluctuates. +- **Handling:** the budget multiplies the total gas (which is certain) by several price levels, see `notes/budget.md`. Check the live price again before the real deployment. -### I-013 干跑后分叉被关闭,无法对链上状态做抽样核对 +### I-013 the fork is closed after the dry run, so the on-chain state cannot be sampled -- **说明:** `dryrun-fork.sh` 结束时会停掉自己启动的 anvil,所以干跑后没法再 `cast call` 检查 Rollup / L1Sequencer 的状态(TODO P4-11)。 -- **已有的保证:** 每一步都成功退出;`s11_verify_deploy` 检查了所有部署的合约都有代码;`s32` 检查了 L1Sequencer 的 owner 等于 deployer。 -- **建议:** 正式部署后再做 P4-11 的抽样核对;或者另起一个**保持运行**的分叉,在上面继续做 P5~P7 的彩排(见下)。 +- **Note:** `dryrun-fork.sh` stops the anvil it started when it ends, so after the dry run `cast call` can no longer check the state of the Rollup / L1Sequencer (TODO P4-11). +- **Guarantees that exist:** every step exited successfully; `s11_verify_deploy` checked that every deployed contract has code; `s32` checked that the owner of the L1Sequencer equals the deployer. +- **Suggestion:** do the sampling of P4-11 after the real deployment; or start another fork that **stays up** and rehearse P5 to P7 on it (see below). -### I-014 `tendermint testnet --n` 是**非验证者**数量,不是总数 — 已修 +### I-014 `tendermint testnet --n` is the number of **non-validators**, not the total - fixed -- **现象:** `tendermint testnet --v 1 --n 2 --hostname ... --hostname ...` 报 `testnet needs precisely 3 hostnames (number of validators plus non-validators)`。 -- **原因:** 主机名个数 = `--v` + `--n`。上游用 `--v 1 --n 5` 配 6 个主机名,我误把 `--n` 当成总数。 -- **处理:** 改成 `--v 1 --n 1`(1 个验证者 node0 + 1 个非验证者 node1)。 -- **验证:** 用干跑留下的创世文件在 `run/nodes-test/` 里跑通 `scripts/setup-nodes.py`:两个 geth 初始化出的创世块哈希 `be3cbc..5540f9` 与干跑 `rollup.json` 里的 L2 创世哈希一致;node0 配置里 rpc/p2p/abci 为 26657/26656/26658,prometheus 为 26660,`block_sync=true`、`pex=false`、`persistent_peers=""`;node1 没有验证者密钥;创世里的验证者公钥与 node0 的 `priv_validator_key` 匹配。 -- **注意:** `run/nodes-test/` 只是测试产物(用的是干跑的 L1 起点),**不能**用于正式运行;正式运行时用 `--run-dir run/l2`,并传入真实部署产出的 `genesis-l2.json`。 +- **Symptom:** `tendermint testnet --v 1 --n 2 --hostname ... --hostname ...` fails with `testnet needs precisely 3 hostnames (number of validators plus non-validators)`. +- **Cause:** the number of hostnames is `--v` + `--n`. Upstream uses `--v 1 --n 5` with 6 hostnames; I took `--n` for the total. +- **Handling:** changed to `--v 1 --n 1` (1 validator node0 + 1 non-validator node1). +- **Verification:** `scripts/setup-nodes.py` was run in `run/nodes-test/` with the genesis files left by the dry run: the genesis block hash `be3cbc..5540f9` produced by both geth initialisations equals the L2 genesis hash in the `rollup.json` of the dry run; the node0 configuration has rpc/p2p/abci 26657/26656/26658, prometheus 26660, `block_sync=true`, `pex=false`, `persistent_peers=""`; node1 has no validator key; the validator public key in the genesis matches the `priv_validator_key` of node0. +- **Note:** `run/nodes-test/` is only a test product (it uses the L1 starting point of the dry run) and **cannot** be used for a real run; for a real run use `--run-dir run/l2` and the `genesis-l2.json` produced by the real deployment. -### I-015 三个进程的 metrics 端口默认值会互相冲突 — 已在 morph-native.sh 里分开 +### I-015 the default metrics ports of three processes collide - separated in morph-native.sh -| 进程 | 默认 | 冲突对象 | 处理 | +| Process | Default | Collides with | Handling | |---|---|---|---| -| gas-oracle | `GAS_ORACLE_METRIC_ADDRESS` 默认 `0.0.0.0:6060` | morph-el-0 的 metrics 6060 | 设为 `127.0.0.1:6070` | -| morphnode(node-1,layer1 校验模式) | `MORPH_NODE_METRICS_PORT` 默认 26660 | node-0 的 tendermint prometheus 26660 | 设 `MORPH_NODE_METRICS_SERVER_ENABLE=true`、`MORPH_NODE_METRICS_PORT=27660` | -| tx-submitter | metrics 默认关闭(compose 里也没开) | — | 启用并设 `TX_SUBMITTER_METRICS_PORT=8060`,方便观测 | - -### I-016 `scripts/morph-native.sh` 已写好并做了无副作用测试 - -- **已测:** 语法、无参数用法、`status`(无进程时)、部署前 `up` 会拒绝、未知进程名、从干跑的部署文件里读合约地址。 -- **未测:** 真正启动进程。原因:本机上另一个 devnet 还占着 8545 和 8551(`status` 里 `el-0 :8545` 读到的是别的链的高度,恰好证实了这个冲突)。要等它停掉,且 L1 部署完成后才能端到端验证。 - -### I-017 deployer 换成用户自带的账户 - -- **背景:** 用户提供了自己的 deployer 私钥(不记录),在 Hoodi 上有 36 ETH。 -- **提醒过:** 私钥最好不要经过对话。用户仍通过对话给出了私钥,所以该私钥已出现在对话记录里。它是测试网账户;**建议今后把它当作"已暴露"**,不要用它持有真实资产,也不要在主网复用。 -- **处理:** 写入权限 600 的 `env/secrets.env`;核对推导出的地址与所给地址一致;把 `hoodidev.ts`(4 处)和 `hoodidev-deploy-config.json`(8 处)里的旧 deployer 地址全部换成新地址,重新暂存并导出补丁。补丁里 0 处私钥。 -- **影响:** 所有合约的 owner 都是用户的这个账户。旧的生成账户 `0x0129…1A2c` 从未收到过币,作废。 -- **从 deployer 向 submitter 转 1 ETH** 作为批次提交的运行资金(`SUBMITTER_FUND_ETH=1`)。 - -### I-018 真实部署第一次失败:公共 RPC 上"刚上链就读不到" — 已加固,重跑 - -- **现象:** 在真实 Hoodi 上部署的第 1 个合约(ProxyAdmin)已经上链(交易 `0xbbcab7c1…`),但紧接着的 `owner()` 调用返回空数据(`CALL_EXCEPTION, data="0x"`),部署脚本退出。anvil 分叉上同一套脚本完全正常。 -- **验证:** 失败后立刻再查,这个合约有代码(2059 字节)、`owner()` 就是 deployer —— 合约本身没问题,是读请求早了一步。 -- **原因(部分验证):** 部署代码对每个合约都是 `await contract.deployed()` 后立刻 `assertContractVariable(...)` 读状态。公共 RPC 背后是多个节点,确认上链的节点和接着处理读请求的节点可能不同。我探测到 `0xrpc.io` 的区块高度会在相邻两个值之间跳动(符合这个模型);ethpandaops 在我的 30 次快速探测里很稳,所以**这个机制是推断,不是对失败那一次的直接证明**。 -- **处理:** 在 `contracts/src/deploy-utils.ts` 给两个断言函数(共 51 处调用)加**默认关闭**的重试:`MORPH_READ_RETRIES`(默认 0=原样)、`MORPH_READ_RETRY_DELAY_MS`(默认 2000)。`deploy-l1.sh` 默认设为 15 次、每次 2 秒。读不到或值不匹配都会重试,最后一次的结果原样抛出,断言报的仍是真实问题。 -- **副作用:** 失败的那次留下了一个孤儿合约 `0x2637…EEF45`(ProxyAdmin),deployer nonce 为 1。重跑会重新部署一套,孤儿合约不用管,花费只有几美分级别的测试币。 -- **局限:** 只覆盖断言函数里的读。`register` 步骤里还有几处别的读(如 `registered()`),如果在那里再遇到同类问题,需要同样处理。 - -### I-019 第二次真实部署失败 + 改用请求层的一致性代理 — 已重跑 - -- **现象:** 加了断言重试后再跑,失败点换到 `deploy/013-DeployProxys.ts:27/227` 的 `console.log(await IProxyContract.admin())`(一个调试打印)。这次已经部署了 9 笔交易(到 `Proxy__L1GatewayRouter`)。同一个根因的第二个读点;后面的 `register` 等步骤还有更多读点,逐个补不是办法。 -- **处理:** 写了 `scripts/rpc-consistency-proxy.js`(约 100 行,无依赖),放在 hardhat / 创世工具 / cast 与公共 RPC 之间: - 1. 记住"已经见过的最高区块"(来自收据和 `eth_blockNumber`),叫 floor; - 2. 把所有对 `latest`/`pending` 的状态读改写成 floor 这个具体块号; - 3. 上游还没同步到时,等待并重试(500 毫秒一次,最多 30 秒); - 4. 写交易、显式指定块号的请求、其余方法原样透传。 -- **一个必须验证才发现的细节:** 这个上游对"还没同步到的块"**不报错,而是返回 `result: null`**(`eth_call`、`getBalance`、`getCode`、`getTransactionCount`、`getStorageAt`、`getBlockByNumber` 都是;只有 `eth_estimateGas` 报 `header not found`)。我的第一版只认错误文字,等于没修。已改成:对被改写过的读,`null` 结果也视为"还没同步到"。 -- **验证:** (1) 透传、改写、`eth_blockNumber` 单调递增、批量请求都正常;(2) 用测试钩子让代理以为自己见过 head+2:`owner()` 被拦住 17 秒(21 次重试)后返回正确的 deployer 地址,之后的读 276 毫秒;(3) 显式块号的请求立即返回,不受影响。 -- **接入:** `deploy-l1.sh` 对 `https://` 的 RPC 默认启用(`USE_CONSISTENCY_PROXY=auto`),对本地 anvil 不启用;退出时自动停掉代理。 -- **局限:** 这是针对我们实测到的行为(`null`/`header not found`)写的。换一个上游,其"未同步"的表现可能不同;代理只保证单调的读,不保证在重组(reorg)时的正确性,对 devnet 部署够用。 -- **残留:** 前两次失败留下约 10 笔孤儿交易(几个孤儿合约),deployer 余额 35.99 ETH,影响可以忽略。 - -### I-020 第三次真实部署失败:上游返回 `rate-limit exceeded` — 代理加了退避与备用端点 - -- **现象:** 经一致性代理后部署推进了约 100 秒,在 `eth_call`(`admin()`)上收到 `ProviderError: rate-limit exceeded`,被 ethers 当作 `CALL_EXCEPTION` 抛出,部署退出。代理日志里没有一次读重试,说明这次不是读不一致,而是限流。 -- **排查:** 单独用 `curl` 连续发请求:`eth_blockNumber`、`eth_call`、`eth_estimateGas`、`eth_getTransactionCount`、`eth_getTransactionReceipt`、`eth_getBlockByNumber` 各 150 个,加上另两个端点各 150 个 `eth_blockNumber`,**全部没有被限流**。所以限流不是按"持续请求数"或"某个方法"稳定触发的,更像是公共服务的**瞬时限流**(共享额度)。这是推断,没有对那一次的直接证明。 -- **处理:** 代理新增: - 1. 限流(HTTP 429/503,或错误信息含 rate limit / too many requests / quota / exceeded)与网络错误时,**立刻切换到下一个上游**;所有上游都拒绝时,按 0.5→1→2→4→8 秒指数退避,最多 8 轮; - 2. 支持备用上游(逗号分隔);`deploy-l1.sh` 默认备用 `0xrpc.io` 和 `publicnode`; - 3. `/stats` 里按方法统计请求数、限流次数、故障切换次数,方便以后看流量构成。 -- **验证(用本地假上游):** (A) 主上游一直限流、备用是真实 Hoodi:332 毫秒内完成故障切换,返回正确的链 ID 和余额;(B) 单上游前 3 次限流后恢复:退避 0.5+1+2 秒,总耗时 3568 毫秒后成功。 -- **风险:** 多个上游的区块头可能略有先后。读请求已经被 floor 钉在具体块号上,落后的节点会返回 null 并被重试,所以这个风险被覆盖;发送交易可能去到任意一个上游,收据则由客户端轮询,最终一致。 -- **残留:** 三次失败共留下约 20 笔孤儿交易;deployer 余额 35.98 ETH,约花了 0.017 ETH。 - -### I-021 第四次真实部署卡死在 `initialize`:一致性代理的 floor 冻结 — 代理的 bug,已修 - -- **现象:** `s10_deploy`(部署)一次通过,`s11`、`s20`(创世)、`s21` 也通过,随后 `s30_initialize` 在 "Upgrading the L1CrossDomainMessenger proxy..." 上卡了 18 分钟以上。进程几乎不占 CPU;代理统计里 `rateLimited=0`、`retries=0`、`eth_sendRawTransaction` 停在 38,而 `eth_call` 和 `eth_chainId` 在缓慢增加。 -- **根因(已通过自测复现):** `deploy/015-MessengerInit.ts` 的写法是:发送 `upgradeToAndCall` 交易但**不等收据**,然后每 3 秒轮询 `implementation()` 等它变成新地址。我的代理把对 `latest` 的读钉在 floor 上,而 floor 只有在客户端调用 `eth_blockNumber` 或取到收据时才更新——这里两样都没有,floor 冻结在升级交易**之前**的区块,轮询永远读到旧状态。**这是我写的代理的 bug,不是 RPC 或链的问题。** -- **修复:** - 1. 每次处理被改写的读之前,最多每秒向上游问一次最新高度并更新 floor(`PROXY_HEAD_REFRESH_MS`,默认 1000); - 2. `pending` 的 nonce 单独处理:取"上游 pending"、"floor 区块的计数"、"代理自己记录的已发送交易下一个 nonce"三者的最大值,避免漏掉已发出但未打包的交易导致 nonce 重用; - 3. 新增可选节流 `PROXY_MIN_INTERVAL_MS`(默认 0=关),对应"限流时在请求之间加 sleep"的需求。 -- **验证:** `scripts/rpc-consistency-proxy.selftest.js` 用一条每秒出块的假链复现了这个 bug:关闭刷新后轮询 12 秒仍读到旧值(FAIL);开启后在链越过变化块后 3 秒读到新值。四项全部通过(floor 跟随链、pending nonce、latest nonce 不被污染、显式块号透传)。 -- **关于加 sleep:** 第四次运行里代理统计显示 `rateLimited=0`、`failovers=0`,**没有触发限流**,所以这次不需要在合约部署之间加 sleep。如果以后触发限流,打开 `PROXY_MIN_INTERVAL_MS`(例如 300)即可,不用改部署代码。 -- **善后:** 卡住的那次运行目录保留在 `run/l1-attempt4-stuck/`。它已部署的合约和升级交易留在链上成为孤儿合约;因为 `initialize` 会重新部署实现合约、创世文件又嵌入了合约地址,不能原地续跑,所以整套重来。 -- **另一个观察:** deployer 余额在此期间从 35.98 ETH 变成 68.93 ETH(不是我转的),看起来有人又转了币进来。 - -### I-022 `cast send` 不读 `ETH_PRIVATE_KEY`,且步骤运行器吞错误 — `setFirstSequencer` 一度没发出去,已修并核对 - -- **现象:** `s33_fund_submitter` 报 `Error accessing local wallet`;追查发现 `s32_first_sequencer` 其实**同样失败**,却在 0 秒内被标成 "ok"。链上 `getSequencer()` 仍是 `no sequencer configured`。 -- **根因 1:** 这个 cast 版本(Foundry 1.9.0)的 `cast send` 不会读 `ETH_PRIVATE_KEY` 环境变量(之前我只在 `cast wallet address` 上测过,并错误地把结论推广到 `cast send`)。 -- **根因 2:** `step()` 里 `if ! "${fn}" ...` 调用步骤函数。bash 在 `if` 条件上下文里**会关闭 `set -e`**,所以函数中间的命令失败不会中止,只有最后一条命令的状态决定结果;`s32` 的最后一条是 `echo`,于是"成功"。 -- **修复:** (1) 新增 `scripts/send-tx.js`,用 ethers 发送交易,私钥只经环境变量 `KEY` 传入,不出现在命令行;(2) `step()` 改为 `set +e; ( set -e; fn ) ...; rc=$?; set -e`,让 errexit 在步骤内真正生效;(3) `s32`、`s33` 在步骤内**读回链上结果**再判成功。 -- **教训:** 不能只看退出码。hardhat 任务出错时常常只打印一行然后 `return`,退出码仍是 0。所以新增 `scripts/verify-l1.sh`,完全不看步骤退出码,直接读链上状态与预期比对。 -- **结果:** 修复后续跑,`s32`、`s33`、`s40` 全部成功;`verify-l1.sh` **53 项通过、0 失败**(Rollup/Messenger/MessageQueue/Submitter/L1Sequencer 的 owner 与互相引用、Rollup 的 L2 链 ID 与创世批次、submitter 登记与质押、所有 21 个代理的 implementation 与 admin、第一个序列器)。 -- **善后:** 错误的 `s32` 标记保留为 `run/l1/state/s32_first_sequencer.done.WRONG-nothing-was-sent`。 - -### I-023 deployer 余额又增加了约 32 ETH - -- 部署期间 deployer 余额从 68.93 ETH 变成 100.87 ETH(`deploy-l1.sh` 的 summary 里"spent"显示为负数,是因为用的是第一次尝试前记录的余额)。不是我转的,应该是你又转了币。仅记录。 - -### I-024 6060 端口被 Coder 工作区代理占用 — morph-geth 的 metrics 改到 6160/6161 - -- **现象:** 检查 Morph 要用的端口时,6060 被工作区自身的 agent 占用,不能动。所以 geth 的 metrics 端口改用 6160 起。 -- **处理:** `morph-native.sh` 里 morph-geth 的 metrics 端口从 6060/6061 改为 6160/6161;PLAN 第 6 节端口表同步修改。 -- **提醒:** 这也是 geth 的默认 metrics 端口,以后在这台机器上起 geth 类进程都要避开 6060。 - -### I-025 oracle 密钥没有权限更新 GasPriceOracle — 上游 devnet 里 owner 与 oracle 是同一个账户,我们拆开了 - -- **现象(启动 oracle 前发现):** L2 创世里 `gasPriceOracleOwner` 是用户的 deployer,而 oracle 进程用我另外生成的 `L2_GAS_ORACLE_PRIVATE_KEY`。链上读到 `GasPriceOracle.owner()` 是 deployer,oracle 密钥 `isAllowed=false`、L2 余额为 0。所有更新函数(`setL1BaseFee…`)是 `onlyAllowed`(owner 或白名单)。 -- **原因:** 上游 devnet 里 `gasPriceOracleOwner` 和 `L2_GAS_ORACLE_PRIVATE_KEY` 是同一个 Anvil #0 账户,所以没人注意到这个耦合。 -- **处理:** `scripts/l2-bootstrap.sh`:用 L2 创世里预置了余额的开发账户(公开的 Anvil #0 密钥,仅在这个只监听 127.0.0.1 的本机私有 L2 上使用)给 deployer 转 100 ETH、给 oracle 转 10 ETH,再由 deployer 调 `setAllowList([oracle],[true])`,读回 `isAllowed=true`。 -- **结果:** oracle 随后第一次更新就成功(L2 交易 `0x7fa3…`)。 - -### I-026 node-1 对 L1 的扫描节奏只有每 15 秒 1~2 个块 - -- **现象:** node-1(layer1 校验模式)的日志里,每 15 秒拉取一次 L1 的 1~2 个区块(`derivation start pull rollupData form l1 startBlock=… end=…`)。Hoodi 每 12 秒一个块,即约 1.25 块/15 秒,而它每轮处理 1~2 块,追赶余量很小。 -- **影响:** 批次在 L1 区块 4043361,node-1 在 4043352,约 2 分钟后才追上并还原出区块。不影响正确性,但**还原延迟随 L1 出块时间和这个轮询节奏而定**,不是实时的。 -- **未做:** 没有去调轮询间隔或范围参数(未确认对应的 flag)。如果需要更低的还原延迟,这里是调优点。 - -### I-027 第一次 L1→L2 存款失败:L1 消息已被打包,但在 L2 上执行失败(状态 0) - -- **现象:** `scripts/deposit-test.sh` 第一次运行:L1 存款交易在 Hoodi 区块 4043381 成功(状态 1,gas 241464),消息入队(`L1MessageQueue.nextCrossDomainMessageIndex = 1`)。但 L2 上全新接收地址 `0x50d3…831b` 的余额 10 分钟内始终为 0,脚本超时失败。 -- **排查过程:** - 1. node-0 日志里只有 2 条 `failed to fetch L1 messages … block range extends beyond current head block`(见 I-026 之后加固代理的那一项),看起来像是读取问题; - 2. 但 node-0 的指标 `morphnode_syncer_message_count = 1`、`morphnode_executor_next_l1_message_queue_index = 1` 说明消息**已经被读到并被打进了区块**; - 3. 扫描 L2 全部区块,找到唯一一笔类型 `0x7e`(L1 消息)的交易,在 **L2 区块 342**:`to` 是 L2CrossDomainMessenger(`0x5300…0007`),`gas` 110000,**回执状态 0**,`gasUsed` 108798,0 条日志,调用的是 `relayMessage`。 -- **结论(推断,待第二次存款验证):** 我沿用了仓库示例任务 `deposit-l1-eth` 里的 `_gasLimit = 110000`,在这套合约上 `relayMessage` 的整个调用链把 gas 用到 98.9% 就失败了,基本是 **gas 不足**。**不是 L1 消息没送到,也不是 L2 没打包。** -- **第一次存款的 0.01 ETH:** 已经锁在 L1 的网关里,L2 上没到账。这是测试币。Morph 的 L1 Messenger 有 `replayMessage`(可用更大的 gas 重放),本次没有去做重放。 -- **另一个教训(我自己的):** 存款脚本我接了 `| cut`,输出被缓冲到脚本结束才显示,让我在等待的 10 分钟里看不到进展;已改成直接写文件。 -- **对计划的影响:** `deposit-test.sh` 的默认 gas 上限改为 400000,可用 `GAS_LIMIT` 覆盖。第二次存款的结果见下一条。 - -#### I-027 结论(第二次存款,gas 上限 400000)— 已证实 - -- 在 Hoodi 区块 4043433 存入 0.01 ETH 到新地址 `0xA2ac…6357`(L1 gas 224386)。**node-0 上约 25 秒后到账**;**node-1 在 391 秒后到账**(它要等包含该 L2 区块的批次 4 提交到 L1,再从 blob 还原)。 -- 所以第一次失败确实是 **`_gasLimit = 110000` 不足**,不是链路或配置问题。仓库示例任务里的 110000 在这套部署上不能用,存款至少给到几十万。 -- 之后把 node-1 已有的全部区块(0 到 796)逐个与 node-0 比对哈希:**0 个不一致**。这个范围同时包含区块 342(含失败的 L1 消息交易)和成功存款所在的区块,说明两条路径下 node-1 还原的结果也和 node-0 一致。 -- **未做:** 第一次失败存款的 0.01 ETH 的 `replayMessage` 重放(测试币,金额小)。 - -### I-028 出块节点 node-0 重启后永远不再出块 — 单个 tendermint 节点的拓扑不可重启(重启测试 T5 失败) - -- **现象:** `scripts/restart-test.sh` 的 T5(停 15 秒再起 node-0):进程是 running、RPC 能答、日志没有任何错误,但 L2 高度冻结(7675),**链停了**。重启前的区块哈希不变(T5b 通过,没有分叉)。 -- **日志特征(与 Morph `ops/README.md` 描述的"静默停转"一致):** `ABCI Handshake height=7675` → `Reactor waitSync=true` → `Already upgraded to sequencer mode, consensus reactor will not start height=3 upgradeHeight=2` → 最后一行是 `derivation skipped: sequencer mode`,**之后没有任何输出**,没有启动出块例程。 -- **根因(已在代码里确认,不是猜测):** - 1. 出块例程只在 `blocksync/reactor.go` 里 `if bcR.pool.IsCaughtUp()` 之后才 `StartSequencerRoutines()`(没有任何配置能绕开); - 2. `blocksync/pool.go` 的 `IsCaughtUp()` 第一条是 `if len(pool.peers) == 0 { return false }`("Need at least 1 peer to be considered caught up"); - 3. 我们的拓扑里 node-0 是**唯一**运行 tendermint 的节点(node-1 是 layer1 校验模式,不启动 tendermint),`persistent_peers` 为空,pool 没有对端。 - 4. 首次启动能出块,是因为从高度 0 开始,靠单验证者先跑 PBFT 阶段、升级进入出块模式,不走这条路径;**重启后高度已超过升级高度,必须走 block pool,于是卡死。** -- **这是这个拓扑的固有限制,不是原生运行引入的:** Morph 的 `ops/README.md` 第 3 条前置条件写着"至少需要两个运行 tendermint 的节点,layer1 校验模式的节点不算",上游 docker 版的单序列器拓扑(node-0 + layer1 的 node-1)应有同样的限制。**我没有在 docker 版上验证过,这一句是按代码推断的。** -- **处理:** 新增 `scripts/add-node2.py`,在现有运行目录上追加一个标准全节点 **node-2(带 morph-el-2,没有出块密钥)**,它运行 tendermint,是 node-0 的 block pool 里永远存在的对端;node-0 的 `persistent_peers` 加入 node-2。**保留 node-1 不变**,因为它的"独立从 L1 blob 还原"验证我不想丢。端口:node-2 的 tendermint 26666/26667/26670,morph-el-2 的 8745/8746/8751/30305/6162。 -- **此前的结论需要修正:** 我之前汇报"主线验证完成"时没有包含重启恢复,这正是当时列在"未验证"里的那一项,现在证明它确实有问题。 - -#### I-028 结论(加入 node-2 后重跑完整重启测试) - -- `scripts/restart-test.sh`(T1~T6、T8)**19 项全部通过、0 失败**: - - T1 `kill -9` node-1:5 秒内被守护外壳拉起,继续还原,tip 哈希一致; - - T2 / T3 重启 morph-el-1 / node-1:继续还原,哈希一致; - - T4 停 L1 代理 20 秒:L1 同步恢复、node-0 没停、所有进程都没退出; - - **T5 重启出块节点 node-0:24 秒内恢复出块(原先永远停转),重启前的区块哈希不变,无分叉;** - - T6 重启 morph-el-0:node-0 恢复出块; - - T8 全部 down 再 up:高度从 8196 继续(不是从 0),历史区块哈希不变,所有进程在运行,node-1 tip 哈希一致。 -- 恢复期间三个节点已有的 7563 个区块哈希逐个比对,0 个不一致:那次停转没有造成分叉。 -- 测试脚本里一处文字("all 7 processes")在加入 node-2 后过时,检查本身用的是完整进程清单,已改文字。 -- T7(重启 tx-submitter 并等下一批)单独跑,见下一条。 - -### 验证记录:L2→L1 提款(P7-5)通过 - -- `scripts/withdraw-test.sh`:L2 区块 8341 发起 0.005 ETH 提款(叶子下标 0,`from` 为 L2 的 ETH 网关,`to` 为 L1 的 ETH 网关);343 秒后 L1 Rollup 列出包含它的 withdrawal root;本地从 L2 的全部 `AppendMessage` 事件重建深度 32 的稀疏默克尔树,**重建的根与链上一致**;L1 `proveAndRelayMessage`(区块 4044651,状态 1,gas 167527)发出 `RelayedMessage`;新的 L1 接收地址余额 0.0 → 0.005 ETH。 -- 证明算法的离线自测(`scripts/withdraw-proof.selftest.js`):逐行复刻合约的 `_appendMessageHash` / `getTreeRoot` / `verifyMerkleProof`,210 组(叶子数 1~20 × 每个下标)全部一致。 -- 只验证了**一笔**提款(树里只有一个叶子)。多笔提款时证明的兄弟节点会包含真实叶子,算法已被离线自测覆盖,但链上还没有用多笔提款实测。 +| gas-oracle | `GAS_ORACLE_METRIC_ADDRESS` defaults to `0.0.0.0:6060` | metrics 6060 of morph-el-0 | set to `127.0.0.1:6070` | +| morphnode (node-1, layer1 verify mode) | `MORPH_NODE_METRICS_PORT` defaults to 26660 | the Tendermint prometheus 26660 of node-0 | set `MORPH_NODE_METRICS_SERVER_ENABLE=true`, `MORPH_NODE_METRICS_PORT=27660` | +| tx-submitter | metrics off by default (also off in compose) | - | enabled with `TX_SUBMITTER_METRICS_PORT=8060` for easier observation | + +### I-016 `scripts/morph-native.sh` is written and tested without side effects + +- **Tested:** syntax, usage without arguments, `status` (with no processes), `up` refusing before a deployment, an unknown process name, reading the contract addresses from the deployment file of the dry run. +- **Not tested:** really starting the processes. Reason: another devnet on this machine still holds 8545 and 8551 (the `el-0 :8545` in `status` read the height of another chain, which confirms the collision). It has to wait until that one is stopped and the L1 deployment is done before it can be verified end to end. + +### I-017 the deployer becomes the user's own account + +- **Background:** the user supplied their own deployer private key (not recorded here), which holds 36 ETH on Hoodi. +- **Warned:** it is better that a private key does not pass through the conversation. The user still gave it in the conversation, so that key is in the conversation record. It is a testnet account; **from now on treat it as "exposed"**, do not use it to hold real assets and do not reuse it on mainnet. +- **Handling:** written to `env/secrets.env` with mode 600; checked that the derived address equals the given address; replaced the old deployer address everywhere (4 places in `hoodidev.ts` and 8 in `hoodidev-deploy-config.json`) with the new one, staged again and exported the patch. 0 private keys in the patch. +- **Effect:** the owner of every contract is this account of the user. The previously generated account `0x0129…1A2c` never received any coins and is retired. +- **1 ETH is sent from the deployer to the submitter** as running funds for batch submission (`SUBMITTER_FUND_ETH=1`). + +### I-018 first real deployment fails: "not readable right after it was mined" on the public RPC - hardened, rerun + +- **Symptom:** the first contract (ProxyAdmin) of the deployment on real Hoodi was mined (transaction `0xbbcab7c1…`), but the following `owner()` call returned empty data (`CALL_EXCEPTION, data="0x"`) and the deployment script exited. The same scripts work perfectly on the anvil fork. +- **Check:** querying again right after the failure, the contract has code (2059 bytes) and `owner()` is the deployer - the contract is fine, the read request was just too early. +- **Cause (partly verified):** for each contract the deployment code does `await contract.deployed()` and immediately `assertContractVariable(...)` to read state. Several nodes sit behind a public RPC, and the node that confirmed the block may differ from the one that handles the next read. I observed that the block height of `0xrpc.io` jumps between two adjacent values (consistent with this model); ethpandaops was very stable in my 30 quick probes, so **this mechanism is an inference, not a direct proof of that one failure**. +- **Handling:** in `contracts/src/deploy-utils.ts` the two assertion functions (51 call sites) get a retry that is **off by default**: `MORPH_READ_RETRIES` (default 0 = as before), `MORPH_READ_RETRY_DELAY_MS` (default 2000). `deploy-l1.sh` sets 15 retries, 2 seconds apart, by default. A failed read or a value mismatch is retried, the result of the last attempt is thrown unchanged, so the assertion still reports the real problem. +- **Side effect:** the failed run left an orphan contract `0x2637…EEF45` (ProxyAdmin) and the deployer nonce is 1. The rerun deploys a whole new set; the orphan can be ignored and cost only a few cents of testnet coins. +- **Limit:** only the reads inside the assertion functions are covered. The `register` step has a few other reads (such as `registered()`); if the same problem shows up there, it needs the same treatment. + +### I-019 second real deployment fails + switch to a consistency proxy at the request layer - rerun + +- **Symptom:** after adding the assertion retries the run failed at another place, `console.log(await IProxyContract.admin())` at `deploy/013-DeployProxys.ts:27/227` (a debug print). 9 transactions had been sent by then (up to `Proxy__L1GatewayRouter`). It is a second read point of the same root cause; later steps such as `register` have more read points, and patching them one by one is not a way. +- **Handling:** I wrote `scripts/rpc-consistency-proxy.js` (about 100 lines, no dependencies) and put it between hardhat / the genesis tool / cast and the public RPC: + 1. it remembers "the highest block seen so far" (from receipts and `eth_blockNumber`), called the floor; + 2. it rewrites every state read on `latest` / `pending` to that concrete floor block number; + 3. when the upstream has not caught up yet, it waits and retries (every 500 ms, at most 30 seconds); + 4. write transactions, requests with an explicit block number and all other methods pass through unchanged. +- **A detail that only verification revealed:** this upstream does **not return an error for a block it has not caught up with, it returns `result: null`** (`eth_call`, `getBalance`, `getCode`, `getTransactionCount`, `getStorageAt` and `getBlockByNumber` all do; only `eth_estimateGas` reports `header not found`). My first version only recognised error text, which means it fixed nothing. Now a `null` result of a rewritten read is also treated as "not caught up yet". +- **Verification:** (1) pass-through, rewriting, a monotonically increasing `eth_blockNumber` and batch requests all work; (2) with a test hook making the proxy believe it had seen head+2: `owner()` was held for 17 seconds (21 retries) and then returned the correct deployer address, later reads took 276 ms; (3) requests with an explicit block number return at once and are not affected. +- **Wiring:** `deploy-l1.sh` enables it by default for an `https://` RPC (`USE_CONSISTENCY_PROXY=auto`), not for a local anvil; the proxy is stopped automatically on exit. +- **Limit:** it was written for the behaviour we measured (`null` / `header not found`). With another upstream the "not caught up" behaviour may differ; the proxy only guarantees monotonic reads and not correctness across a reorg, which is enough for a devnet deployment. +- **Leftover:** the first two failures left about 10 orphan transactions (a few orphan contracts); the deployer balance is 35.99 ETH, the effect is negligible. + +### I-020 third real deployment fails: the upstream returns `rate-limit exceeded` - the proxy gets backoff and fallback endpoints + +- **Symptom:** after about 100 seconds of progress through the consistency proxy, an `eth_call` (`admin()`) got `ProviderError: rate-limit exceeded`, which ethers throws as `CALL_EXCEPTION`, and the deployment exited. The proxy log shows not a single read retry, so this was not read inconsistency but rate limiting. +- **Investigation:** with plain `curl`, 150 requests each of `eth_blockNumber`, `eth_call`, `eth_estimateGas`, `eth_getTransactionCount`, `eth_getTransactionReceipt` and `eth_getBlockByNumber`, plus 150 `eth_blockNumber` on each of the other two endpoints, in a row: **none was rate limited**. So the limit is not triggered steadily by "the number of sustained requests" or "one method"; it looks more like a **momentary limit** of the public service (a shared quota). This is an inference, with no direct proof for that one occurrence. +- **Handling:** the proxy now has: + 1. on rate limiting (HTTP 429/503, or an error message containing rate limit / too many requests / quota / exceeded) and on network errors it **switches to the next upstream at once**; when every upstream refuses it backs off exponentially 0.5 -> 1 -> 2 -> 4 -> 8 seconds, at most 8 rounds; + 2. support for fallback upstreams (comma separated); `deploy-l1.sh` uses `0xrpc.io` and `publicnode` as fallbacks by default; + 3. `/stats` counts requests per method, rate-limit hits and failovers, so the traffic makes up can be seen later. +- **Verification (with a local fake upstream):** (A) the primary is rate limited all the time and the fallback is real Hoodi: the failover completes in 332 ms and returns the correct chain id and balance; (B) a single upstream that is limited for the first 3 requests and then recovers: backoff 0.5+1+2 seconds, success after 3568 ms in total. +- **Risk:** the block headers of several upstreams may be slightly ahead of or behind each other. Reads are pinned to a concrete block number by the floor, a lagging node returns null and is retried, so this risk is covered; a sent transaction may go to any upstream, and the receipt is polled by the client, so it is eventually consistent. +- **Leftover:** the three failures left about 20 orphan transactions in total; the deployer balance is 35.98 ETH, about 0.017 ETH was spent. + +### I-021 fourth real deployment hangs in `initialize`: the floor of the consistency proxy is frozen - a bug of the proxy, fixed + +- **Symptom:** `s10_deploy` (deployment) passed at once, `s11`, `s20` (genesis) and `s21` also passed, then `s30_initialize` hung for more than 18 minutes at "Upgrading the L1CrossDomainMessenger proxy...". The process used almost no CPU; in the proxy statistics `rateLimited=0`, `retries=0`, `eth_sendRawTransaction` stood at 38 while `eth_call` and `eth_chainId` slowly increased. +- **Root cause (reproduced by a self-test):** `deploy/015-MessengerInit.ts` sends an `upgradeToAndCall` transaction **without waiting for the receipt** and then polls `implementation()` every 3 seconds until it becomes the new address. My proxy pins reads on `latest` to the floor, and the floor is only updated when the client calls `eth_blockNumber` or gets a receipt - neither happens here, so the floor froze at the block **before** the upgrade transaction and the polling read the old state forever. **This is a bug of the proxy I wrote, not a problem of the RPC or the chain.** +- **Fix:** + 1. before handling a rewritten read, ask the upstream for its latest height at most once per second and update the floor (`PROXY_HEAD_REFRESH_MS`, default 1000); + 2. the `pending` nonce is handled separately: take the maximum of "the upstream pending", "the count at the floor block" and "the next nonce of the transactions the proxy itself has seen being sent", so that a transaction that was sent but not mined is not missed and a nonce is not reused; + 3. a new optional throttle `PROXY_MIN_INTERVAL_MS` (default 0 = off), for the need of "sleep between requests when rate limited". +- **Verification:** `scripts/rpc-consistency-proxy.selftest.js` reproduces the bug with a fake chain that produces a block per second: with refreshing off the polling still read the old value after 12 seconds (FAIL); with it on the new value was read 3 seconds after the chain passed the changing block. All four checks pass (the floor follows the chain, the pending nonce, the latest nonce is not polluted, explicit block numbers pass through). +- **About adding sleeps:** the proxy statistics of the fourth run show `rateLimited=0` and `failovers=0`, so **rate limiting was not triggered** and no sleep between contract deployments was needed this time. If rate limiting is triggered later, turn on `PROXY_MIN_INTERVAL_MS` (for example 300); the deployment code does not need to change. +- **Cleanup:** the directory of the hung run stays in `run/l1-attempt4-stuck/`. The contracts it had deployed and the upgrade transaction stay on the chain as orphans; since `initialize` deploys the implementation contracts again and the genesis file embeds the contract addresses, it cannot be continued in place, so the whole set is redone. +- **Another observation:** the deployer balance went from 35.98 ETH to 68.93 ETH in the meantime (not sent by me); it looks as if someone sent more coins. + +### I-022 `cast send` does not read `ETH_PRIVATE_KEY`, and the step runner swallows errors - `setFirstSequencer` was once not sent, fixed and checked + +- **Symptom:** `s33_fund_submitter` reports `Error accessing local wallet`; tracing it showed that `s32_first_sequencer` had **failed the same way** but was marked "ok" within 0 seconds. On the chain `getSequencer()` was still `no sequencer configured`. +- **Root cause 1:** the `cast send` of this cast version (Foundry 1.9.0) does not read the environment variable `ETH_PRIVATE_KEY` (earlier I had only tested it with `cast wallet address` and wrongly generalised the result to `cast send`). +- **Root cause 2:** `step()` calls the step function as `if ! "${fn}" ...`. In the context of an `if` condition bash **turns `set -e` off**, so a command failing in the middle of the function does not abort it and only the status of the last command decides; the last command of `s32` is an `echo`, so it "succeeded". +- **Fix:** (1) a new `scripts/send-tx.js` sends transactions with ethers, and the private key only comes in through the environment variable `KEY`, never on the command line; (2) `step()` becomes `set +e; ( set -e; fn ) ...; rc=$?; set -e`, so errexit really works inside a step; (3) `s32` and `s33` **read the result back from the chain** inside the step before they count as successful. +- **Lesson:** exit codes alone cannot be trusted. When a hardhat task goes wrong it often prints one line and then `return`s with exit code 0. So a new `scripts/verify-l1.sh` ignores the step exit codes completely and compares the on-chain state with the expectation. +- **Result:** after the fix the continued run succeeded for `s32`, `s33` and `s40`; `verify-l1.sh` has **53 passed, 0 failed** (owners and mutual references of Rollup/Messenger/MessageQueue/Submitter/L1Sequencer, the L2 chain id and genesis batch of the Rollup, the submitter's registration and stake, implementation and admin of all 21 proxies, the first sequencer). +- **Cleanup:** the wrong `s32` marker is kept as `run/l1/state/s32_first_sequencer.done.WRONG-nothing-was-sent`. + +### I-023 the deployer balance rose by about 32 ETH again + +- During the deployment the deployer balance went from 68.93 ETH to 100.87 ETH (the "spent" in the summary of `deploy-l1.sh` shows a negative number because it uses the balance recorded before the first attempt). It was not sent by me; presumably you sent more coins. Recorded only. + +### I-024 port 6060 is taken by the Coder workspace agent - the morph-geth metrics move to 6160/6161 + +- **Symptom:** while checking the ports Morph needs, 6060 was held by the workspace's own agent, which must not be touched. So the geth metrics ports start at 6160. +- **Handling:** in `morph-native.sh` the metrics ports of morph-geth changed from 6060/6061 to 6160/6161; the port table in section 6 of the PLAN was changed to match. +- **Reminder:** 6060 is also geth's default metrics port, so every geth-like process started on this machine has to avoid 6060. + +### I-025 the oracle key is not allowed to update the GasPriceOracle - in the upstream devnet owner and oracle are the same account, we split them + +- **Symptom (found before starting the oracle):** in the L2 genesis `gasPriceOracleOwner` is the user's deployer, while the oracle process uses the separately generated `L2_GAS_ORACLE_PRIVATE_KEY`. On the chain `GasPriceOracle.owner()` is the deployer, the oracle key has `isAllowed=false` and an L2 balance of 0. All update functions (`setL1BaseFee...`) are `onlyAllowed` (owner or allow list). +- **Cause:** in the upstream devnet `gasPriceOracleOwner` and `L2_GAS_ORACLE_PRIVATE_KEY` are the same Anvil #0 account, so nobody noticed this coupling. +- **Handling:** `scripts/l2-bootstrap.sh`: with the development account that the L2 genesis pre-funds (the public Anvil #0 account, used only on this local private L2 that listens on 127.0.0.1) it sends 100 ETH to the deployer and 10 ETH to the oracle, and then the deployer calls `setAllowList([oracle],[true])` and reads back `isAllowed=true`. +- **Result:** the oracle's first update then succeeded (L2 transaction `0x7fa3…`). + +### I-026 node-1 scans L1 at only 1 to 2 blocks every 15 seconds + +- **Symptom:** in the log of node-1 (layer1 verify mode), 1 to 2 L1 blocks are fetched every 15 seconds (`derivation start pull rollupData form l1 startBlock=… end=…`). Hoodi has a block every 12 seconds, about 1.25 blocks per 15 seconds, and it handles 1 to 2 blocks per round, so the margin to catch up is small. +- **Effect:** the batch was at L1 block 4043361 and node-1 at 4043352; it took about 2 minutes to catch up and rebuild the blocks. Correctness is not affected, but **the rebuild delay depends on the L1 block time and on this polling rhythm**; it is not real time. +- **Not done:** the polling interval or range parameters were not tuned (the corresponding flag is not confirmed). If a lower rebuild delay is needed, this is the place to tune. + +### I-027 the first L1 to L2 deposit fails: the L1 message was included but failed to execute on the L2 (status 0) + +- **Symptom:** first run of `scripts/deposit-test.sh`: the L1 deposit transaction succeeded in Hoodi block 4043381 (status 1, gas 241464), the message was queued (`L1MessageQueue.nextCrossDomainMessageIndex = 1`). But the balance of the fresh receiving address `0x50d3…831b` on the L2 stayed 0 for 10 minutes and the script timed out. +- **Investigation:** + 1. the node-0 log only has 2 lines `failed to fetch L1 messages … block range extends beyond current head block` (see the item that hardened the proxy after I-026), which looked like a read problem; + 2. but the node-0 metrics `morphnode_syncer_message_count = 1` and `morphnode_executor_next_l1_message_queue_index = 1` show that the message **was read and included in a block**; + 3. scanning all L2 blocks found the only transaction of type `0x7e` (L1 message), in **L2 block 342**: `to` is the L2CrossDomainMessenger (`0x5300…0007`), `gas` 110000, **receipt status 0**, `gasUsed` 108798, 0 logs, calling `relayMessage`. +- **Conclusion (an inference, to be verified by the second deposit):** I reused `_gasLimit = 110000` from the repository's example task `deposit-l1-eth`; on this set of contracts the whole call chain of `relayMessage` fails after using 98.9% of the gas, so it is mostly **not enough gas**. **It is not that the L1 message was not delivered, and not that the L2 did not include it.** +- **The 0.01 ETH of the first deposit:** it is locked in the L1 gateway and did not arrive on the L2. It is testnet coin. The L1 Messenger of Morph has `replayMessage` (replay with more gas); no replay was done this time. +- **Another lesson (mine):** I had piped the deposit script into `| cut`, so the output was buffered until the script ended and I could see no progress during the 10 minutes of waiting; it now writes to a file directly. +- **Effect on the plan:** the default gas limit of `deposit-test.sh` is now 400000 and can be overridden with `GAS_LIMIT`. The result of the second deposit is in the next item. + +#### I-027 conclusion (second deposit, gas limit 400000) - confirmed + +- 0.01 ETH was deposited to the new address `0xA2ac…6357` in Hoodi block 4043433 (L1 gas 224386). **It arrived on node-0 after about 25 seconds**; **on node-1 after 391 seconds** (it has to wait until the batch 4 containing that L2 block is committed to L1 and then rebuild it from the blob). +- So the first failure really was an **insufficient `_gasLimit = 110000`**, not a problem of the path or the configuration. The 110000 of the repository's example task cannot be used on this deployment; give deposits at least a few hundred thousand. +- Afterwards all blocks that node-1 had (0 to 796) were compared with node-0 hash by hash: **0 differences**. The range contains both block 342 (with the failed L1 message transaction) and the block of the successful deposit, which shows that on both paths what node-1 rebuilds agrees with node-0. +- **Not done:** the `replayMessage` replay of the 0.01 ETH of the first failed deposit (testnet coin, small amount). + +### I-028 after a restart the block producer node-0 never produces blocks again - a topology with a single Tendermint node cannot be restarted (restart test T5 fails) + +- **Symptom:** T5 of `scripts/restart-test.sh` (stop node-0 for 15 seconds, start it again): the process is running, the RPC answers, the log has no error, but the L2 height is frozen (7675) and **the chain has stopped**. The block hashes from before the restart are unchanged (T5b passes, no fork). +- **Log signature (the same as the "silent stall" described in Morph's `ops/README.md`):** `ABCI Handshake height=7675` -> `Reactor waitSync=true` -> `Already upgraded to sequencer mode, consensus reactor will not start height=3 upgradeHeight=2` -> the last line is `derivation skipped: sequencer mode`, **and then no output at all**; the block production routine was not started. +- **Root cause (confirmed in the code, not guessed):** + 1. the block production routine is only started with `StartSequencerRoutines()` in `blocksync/reactor.go` after `if bcR.pool.IsCaughtUp()` (no configuration can get around it); + 2. the first line of `IsCaughtUp()` in `blocksync/pool.go` is `if len(pool.peers) == 0 { return false }` ("Need at least 1 peer to be considered caught up"); + 3. in our topology node-0 is the **only** node running Tendermint (node-1 is in layer1 verify mode and does not start Tendermint), `persistent_peers` is empty, and the pool has no peer. + 4. The first start can produce blocks because it starts from height 0 and the single validator first runs the PBFT phase and upgrades into block production mode, which does not take this path; **after a restart the height is already beyond the upgrade height, the block pool has to be used, and so it hangs.** +- **This is an inherent limit of this topology, not introduced by running natively:** item 3 of the prerequisites in Morph's `ops/README.md` says "at least two nodes running Tendermint are needed, a node in layer1 verify mode does not count", and the single-sequencer topology of the upstream docker setup (node-0 + layer1 node-1) should have the same limit. **I have not verified this on the docker version; this sentence is inferred from the code.** +- **Handling:** a new `scripts/add-node2.py` adds a standard full node **node-2 (with morph-el-2, without a block production key)** to the existing run directory; it runs Tendermint and is the peer that always exists in the block pool of node-0; the `persistent_peers` of node-0 gets node-2. **node-1 stays unchanged**, because I do not want to lose its verification of "rebuilding independently from the L1 blob". Ports: Tendermint of node-2 26666/26667/26670, morph-el-2 8745/8746/8751/30305/6162. +- **A previous conclusion needs correcting:** when I reported "main line verification done" before, restart recovery was not included, which was exactly the item then listed under "not verified"; it is now proven that it really has a problem. + +#### I-028 conclusion (full restart test rerun after adding node-2) + +- `scripts/restart-test.sh` (T1 to T6, T8): **19 checks all pass, 0 fail**: + - T1 `kill -9` node-1: it is started again by the supervisor shell within 5 seconds, continues rebuilding, the tip hash agrees; + - T2 / T3 restart morph-el-1 / node-1: it continues rebuilding, the hashes agree; + - T4 stop the L1 proxy for 20 seconds: L1 sync recovers, node-0 did not stop, no process exited; + - **T5 restart the block producer node-0: block production resumes within 24 seconds (it used to stall forever), the block hashes from before the restart are unchanged, no fork;** + - T6 restart morph-el-0: node-0 resumes block production; + - T8 down and up everything: the height continues from 8196 (not from 0), the history block hashes are unchanged, every process is running, the tip hash of node-1 agrees. +- The 7563 block hashes that the three nodes already had were compared one by one during the recovery, 0 differences: that stall caused no fork. +- A text in the test script ("all 7 processes") became outdated after node-2 was added; the check itself uses the complete process list, and the text was changed. +- T7 (restart tx-submitter and wait for the next batch) was run separately, see the next item. + +### Verification record: L2 to L1 withdrawal (P7-5) passes + +- `scripts/withdraw-test.sh`: a 0.005 ETH withdrawal was initiated in L2 block 8341 (leaf index 0, `from` is the ETH gateway on the L2, `to` is the ETH gateway on L1); 343 seconds later the L1 Rollup lists the withdrawal root containing it; a sparse Merkle tree of depth 32 was rebuilt locally from all `AppendMessage` events of the L2, and **the rebuilt root agrees with the one on the chain**; L1 `proveAndRelayMessage` (block 4044651, status 1, gas 167527) emitted `RelayedMessage`; the balance of the new L1 receiving address went from 0.0 to 0.005 ETH. +- Offline self-test of the proof algorithm (`scripts/withdraw-proof.selftest.js`): it copies the contract's `_appendMessageHash` / `getTreeRoot` / `verifyMerkleProof` line by line, and all 210 cases (1 to 20 leaves x every index) agree. +- Only **one** withdrawal was verified (the tree holds a single leaf). With several withdrawals the siblings of a proof contain real leaves; the algorithm is covered by the offline self-test, but several withdrawals were not tried on the chain yet. + +--- + +## 2026-11-27 (added with the challenger and the address changes of the pull request) + +### I-029 node-2 is built from the genesis of `run/l1` whatever `L1_RUN` says - the whole L2 stops producing blocks + +- **Symptom:** with a second deployment in another directory (`run/l1-v2` next to the old `run/l1`), the new L2 stopped after about 220 blocks and the committed batch index stayed at 1. All processes were `running`; the node-0 log showed `Error reconnecting to peer ... connection refused` (dialling node-2), the node-2 log `NewL2Block failed ... wrong parent hash`, and the height of el-2 stayed at 0. +- **Cause:** `add-node2.py` read the L2 genesis from `/../l1/genesis/genesis-l2.json`. node-0 and node-1 were initialised from `L1_RUN` (correct), node-2 from `run/l1` (the old deployment). The block 0 hashes differ (`0x6d00d673…` on el-0, `0x4e07ce7e…` on el-2), so node-2 rejects every block; node-0 then has no Tendermint peer, which is I-028. +- **Fix:** `add-node2.py` takes an optional `--genesis`; `morph-native.sh setup` passes `"${L1_RUN}/genesis/genesis-l2.json"`. Without the flag the old default is kept. +- **How to recognise it:** `cast block 0 --field hash` on 8545 and 8745 must be equal; the node-2 log must not contain `wrong parent hash`. +- **Handling of the live environment:** `down`, move the wrong `nodes/node2` and `el2` to `run/archive/node2-wrong-genesis-