diff --git a/packages/block/examples/4844.ts b/packages/block/examples/4844.ts index 5331a68e20..a88f701620 100644 --- a/packages/block/examples/4844.ts +++ b/packages/block/examples/4844.ts @@ -1,7 +1,7 @@ import { createBlockFromBlockData } from '@ethereumjs/block' import { Chain, Common, Hardfork } from '@ethereumjs/common' import { create4844BlobTx } from '@ethereumjs/tx' -import { Address } from '@ethereumjs/util' +import { createAddressFromPrivateKey } from '@ethereumjs/util' import { randomBytes } from 'crypto' import { loadKZG } from 'kzg-wasm' @@ -16,7 +16,7 @@ const main = async () => { }, }) const blobTx = create4844BlobTx( - { blobsData: ['myFirstBlob'], to: Address.fromPrivateKey(randomBytes(32)) }, + { blobsData: ['myFirstBlob'], to: createAddressFromPrivateKey(randomBytes(32)) }, { common }, ) diff --git a/packages/block/src/header.ts b/packages/block/src/header.ts index f8f417362d..0c220f07d4 100644 --- a/packages/block/src/header.ts +++ b/packages/block/src/header.ts @@ -17,6 +17,8 @@ import { bytesToHex, bytesToUtf8, concatBytes, + createAddressFromPublicKey, + createZeroAddress, ecrecover, ecsign, equalsBytes, @@ -177,7 +179,7 @@ export class BlockHeader { const defaults = { parentHash: zeros(32), uncleHash: KECCAK256_RLP_ARRAY, - coinbase: Address.zero(), + coinbase: createZeroAddress(), stateRoot: zeros(32), transactionsTrie: KECCAK256_RLP, receiptTrie: KECCAK256_RLP, @@ -932,13 +934,13 @@ export class BlockHeader { const extraSeal = this.cliqueExtraSeal() // Reasonable default for default blocks if (extraSeal.length === 0 || equalsBytes(extraSeal, new Uint8Array(65))) { - return Address.zero() + return createZeroAddress() } const r = extraSeal.subarray(0, 32) const s = extraSeal.subarray(32, 64) const v = bytesToBigInt(extraSeal.subarray(64, 65)) + BIGINT_27 const pubKey = ecrecover(this.cliqueSigHash(), v, r, s) - return Address.fromPublicKey(pubKey) + return createAddressFromPublicKey(pubKey) } /** diff --git a/packages/block/test/clique.spec.ts b/packages/block/test/clique.spec.ts index 2c000d2bb3..a9ee44e710 100644 --- a/packages/block/test/clique.spec.ts +++ b/packages/block/test/clique.spec.ts @@ -1,5 +1,5 @@ import { Chain, Common, Hardfork } from '@ethereumjs/common' -import { Address, hexToBytes } from '@ethereumjs/util' +import { Address, createZeroAddress, hexToBytes } from '@ethereumjs/util' import { assert, describe, it } from 'vitest' import { BlockHeader } from '../src/header.js' @@ -68,7 +68,11 @@ describe('[Header]: Clique PoA Functionality', () => { ) const msg = 'cliqueEpochTransitionSigners() -> should return the correct epoch transition signer list on epoch block' - assert.deepEqual(header.cliqueEpochTransitionSigners(), [Address.zero(), Address.zero()], msg) + assert.deepEqual( + header.cliqueEpochTransitionSigners(), + [createZeroAddress(), createZeroAddress()], + msg, + ) }) type Signer = { @@ -99,7 +103,7 @@ describe('[Header]: Clique PoA Functionality', () => { header = BlockHeader.fromHeaderData({ extraData: new Uint8Array(97) }, { common }) assert.ok( - header.cliqueSigner().equals(Address.zero()), + header.cliqueSigner().equals(createZeroAddress()), 'should return zero address on default block', ) }) diff --git a/packages/block/test/header.spec.ts b/packages/block/test/header.spec.ts index 92d4d11c75..29f1beeddb 100644 --- a/packages/block/test/header.spec.ts +++ b/packages/block/test/header.spec.ts @@ -1,11 +1,11 @@ import { Chain, Common, Hardfork } from '@ethereumjs/common' import { RLP } from '@ethereumjs/rlp' import { - Address, KECCAK256_RLP, KECCAK256_RLP_ARRAY, bytesToHex, concatBytes, + createZeroAddress, equalsBytes, hexToBytes, zeros, @@ -28,7 +28,7 @@ describe('[Block]: Header functions', () => { function compareDefaultHeader(header: BlockHeader) { assert.ok(equalsBytes(header.parentHash, zeros(32))) assert.ok(equalsBytes(header.uncleHash, KECCAK256_RLP_ARRAY)) - assert.ok(header.coinbase.equals(Address.zero())) + assert.ok(header.coinbase.equals(createZeroAddress())) assert.ok(equalsBytes(header.stateRoot, zeros(32))) assert.ok(equalsBytes(header.transactionsTrie, KECCAK256_RLP)) assert.ok(equalsBytes(header.receiptTrie, KECCAK256_RLP)) @@ -380,7 +380,7 @@ describe('[Block]: Header functions', () => { testCase = 'should throw on non-zero beneficiary (coinbase) for epoch transition block' headerData.number = common.consensusConfig().epoch - headerData.coinbase = Address.fromString('0x091dcd914fCEB1d47423e532955d1E62d1b2dAEf') + headerData.coinbase = createAddressFromString('0x091dcd914fCEB1d47423e532955d1E62d1b2dAEf') header = BlockHeader.fromHeaderData(headerData, { common }) try { await header.validate(blockchain) @@ -393,7 +393,7 @@ describe('[Block]: Header functions', () => { } } headerData.number = 1 - headerData.coinbase = Address.zero() + headerData.coinbase = createZeroAddress() testCase = 'should throw on non-zero mixHash' headerData.mixHash = new Uint8Array(32).fill(1) @@ -455,7 +455,7 @@ describe('[Block]: Header functions', () => { */ it('should test validateGasLimit()', () => { const common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.London }) - const bcBlockGasLimitTestData = testData.tests.BlockGasLimit2p63m1 + const bcBlockGasLimitTestData = testData.default.tests.BlockGasLimit2p63m1 for (const key of Object.keys(bcBlockGasLimitTestData)) { const genesisRlp = hexToBytes( diff --git a/packages/block/test/mergeBlock.spec.ts b/packages/block/test/mergeBlock.spec.ts index 3a0ac43597..803dc9fc61 100644 --- a/packages/block/test/mergeBlock.spec.ts +++ b/packages/block/test/mergeBlock.spec.ts @@ -1,8 +1,8 @@ import { Chain, Common, Hardfork } from '@ethereumjs/common' import { - Address, KECCAK256_RLP, KECCAK256_RLP_ARRAY, + createZeroAddress, equalsBytes, hexToBytes, zeros, @@ -21,7 +21,7 @@ const common = new Common({ function validateMergeHeader(header: BlockHeader) { assert.ok(equalsBytes(header.parentHash, zeros(32)), 'parentHash') assert.ok(equalsBytes(header.uncleHash, KECCAK256_RLP_ARRAY), 'uncleHash') - assert.ok(header.coinbase.equals(Address.zero()), 'coinbase') + assert.ok(header.coinbase.equals(createZeroAddress()), 'coinbase') assert.ok(equalsBytes(header.stateRoot, zeros(32)), 'stateRoot') assert.ok(equalsBytes(header.transactionsTrie, KECCAK256_RLP), 'transactionsTrie') assert.ok(equalsBytes(header.receiptTrie, KECCAK256_RLP), 'receiptTrie') diff --git a/packages/blockchain/test/clique.spec.ts b/packages/blockchain/test/clique.spec.ts index 544f6bf093..1159b17889 100644 --- a/packages/blockchain/test/clique.spec.ts +++ b/packages/blockchain/test/clique.spec.ts @@ -7,7 +7,13 @@ import { Hardfork, createCustomCommon, } from '@ethereumjs/common' -import { Address, concatBytes, hexToBytes } from '@ethereumjs/util' +import { + Address, + concatBytes, + createAddressFromString, + createZeroAddress, + hexToBytes, +} from '@ethereumjs/util' import { assert, describe, it } from 'vitest' import { CLIQUE_NONCE_AUTH, CLIQUE_NONCE_DROP, CliqueConsensus } from '../src/consensus/clique.js' @@ -114,7 +120,7 @@ function getBlock( common = common ?? COMMON const number = lastBlock.header.number + BigInt(1) - let coinbase = Address.zero() + let coinbase = createZeroAddress() let nonce = CLIQUE_NONCE_DROP let extraData = EXTRA_DATA if (beneficiary) { @@ -214,7 +220,7 @@ describe('Clique: Initialization', () => { // _validateConsensus needs to be true to trigger this test condition ;(blockchain as any)._validateConsensus = true const number = (COMMON.consensusConfig() as CliqueConfig).epoch - const unauthorizedSigner = Address.fromString('0x00a839de7922491683f547a67795204763ff8237') + const unauthorizedSigner = createAddressFromString('0x00a839de7922491683f547a67795204763ff8237') const extraData = concatBytes( new Uint8Array(32), A.address.toBytes(), diff --git a/packages/client/bin/cli.ts b/packages/client/bin/cli.ts index 7488a7d1d6..29b70eecc3 100755 --- a/packages/client/bin/cli.ts +++ b/packages/client/bin/cli.ts @@ -12,11 +12,12 @@ import { } from '@ethereumjs/common' import { RLP } from '@ethereumjs/rlp' import { - Address, BIGINT_2, bytesToHex, calculateSigRecovery, concatBytes, + createAddressFromPrivateKey, + createAddressFromString, ecrecover, ecsign, hexToBytes, @@ -65,7 +66,7 @@ import type { RPCArgs } from './startRpc.js' import type { Block, BlockBytes } from '@ethereumjs/block' import type { ConsensusDict } from '@ethereumjs/blockchain' import type { CustomCrypto } from '@ethereumjs/common' -import type { GenesisState, PrefixedHexString } from '@ethereumjs/util' +import type { Address, GenesisState, PrefixedHexString } from '@ethereumjs/util' import type { AbstractLevel } from 'abstract-level' import type { Server as RPCServer } from 'jayson/promise/index.js' @@ -371,7 +372,7 @@ const args: ClientOpts = yargs describe: 'Address for mining rewards (etherbase). If not provided, defaults to the primary account', string: true, - coerce: (coinbase) => Address.fromString(coinbase), + coerce: (coinbase) => createAddressFromString(coinbase), }) .option('saveReceipts', { describe: @@ -835,13 +836,13 @@ async function inputAccounts() { const isFile = existsSync(path.resolve(addresses[0])) if (!isFile) { for (const addressString of addresses) { - const address = Address.fromString(addressString) + const address = createAddressFromString(addressString) const inputKey = (await question( `Please enter the 0x-prefixed private key to unlock ${address}:\n`, )) as PrefixedHexString ;(rl as any).history = (rl as any).history.slice(1) const privKey = hexToBytes(inputKey) - const derivedAddress = Address.fromPrivateKey(privKey) + const derivedAddress = createAddressFromPrivateKey(privKey) if (address.equals(derivedAddress)) { accounts.push([address, privKey]) } else { @@ -854,7 +855,7 @@ async function inputAccounts() { } else { const acc = readFileSync(path.resolve(args.unlock!), 'utf-8').replace(/(\r\n|\n|\r)/gm, '') const privKey = hexToBytes(`0x${acc}`) // See docs: acc has to be non-zero prefixed in the file - const derivedAddress = Address.fromPrivateKey(privKey) + const derivedAddress = createAddressFromPrivateKey(privKey) accounts.push([derivedAddress, privKey]) } } catch (e: any) { @@ -870,7 +871,7 @@ async function inputAccounts() { */ function generateAccount(): Account { const privKey = randomBytes(32) - const address = Address.fromPrivateKey(privKey) + const address = createAddressFromPrivateKey(privKey) console.log('='.repeat(50)) console.log('Account generated for mining blocks:') console.log(`Address: ${address}`) diff --git a/packages/client/devnets/4844-interop/tools/txGenerator.ts b/packages/client/devnets/4844-interop/tools/txGenerator.ts index f6d6aea8a1..4d799e65c5 100644 --- a/packages/client/devnets/4844-interop/tools/txGenerator.ts +++ b/packages/client/devnets/4844-interop/tools/txGenerator.ts @@ -1,13 +1,13 @@ // Adapted from - https://github.com/Inphi/eip4844-interop/blob/master/blob_tx_generator/blob.js -import { Common, Hardfork } from '@ethereumjs/common' -import { BlobEIP4844Transaction, TransactionType, TxData } from '@ethereumjs/tx' +import { createCommonFromGethGenesis, Hardfork } from '@ethereumjs/common' +import { createTxFromTxData, TransactionType, TxData } from '@ethereumjs/tx' import { - Address, blobsToCommitments, commitmentsToVersionedHashes, getBlobs, bytesToHex, hexToBytes, + createAddressFromPrivateKey, } from '@ethereumjs/util' import { randomBytes } from '@ethereumjs/util' @@ -18,8 +18,8 @@ import { loadKZG } from 'kzg-wasm' const clientPort = parseInt(process.argv[2]) // EL client port number const input = process.argv[3] // text to generate blob from const genesisJson = require(process.argv[4]) // Genesis parameters -const pkey = hexToBytes('0x' + process.argv[5]) // private key of tx sender as unprefixed hex string (unprefixed in args) -const sender = Address.fromPrivateKey(pkey) +const pkey = hexToBytes(`0x${process.argv[5]}`) // private key of tx sender as unprefixed hex string (unprefixed in args) +const sender = createAddressFromPrivateKey(pkey) async function getNonce(client: Client, account: string) { const nonce = await client.request('eth_getTransactionCount', [account, 'latest'], 2.0) @@ -41,7 +41,7 @@ async function run(data: any) { const commitments = blobsToCommitments(kzg, blobs) const hashes = commitmentsToVersionedHashes(commitments) - const account = Address.fromPrivateKey(randomBytes(32)) + const account = createAddressFromPrivateKey(randomBytes(32)) const txData: TxData[TransactionType.BlobEIP4844] = { to: account.toString(), data: '0x', @@ -62,7 +62,7 @@ async function run(data: any) { txData.gasLimit = BigInt(28000000) const nonce = await getNonce(client, sender.toString()) txData.nonce = BigInt(nonce) - const blobTx = BlobEIP4844Transaction.fromTxData(txData, { common }).sign(pkey) + const blobTx = createTxFromTxData(txData, { common }).sign(pkey) const serializedWrapper = blobTx.serializeNetworkWrapper() diff --git a/packages/client/src/miner/pendingBlock.ts b/packages/client/src/miner/pendingBlock.ts index 0d08db6e76..dfb58fad31 100644 --- a/packages/client/src/miner/pendingBlock.ts +++ b/packages/client/src/miner/pendingBlock.ts @@ -1,13 +1,13 @@ import { Hardfork } from '@ethereumjs/common' import { BlobEIP4844Transaction } from '@ethereumjs/tx' import { - Address, BIGINT_1, BIGINT_2, TypeOutput, bigIntToUnpaddedBytes, bytesToHex, concatBytes, + createZeroAddress, equalsBytes, toBytes, toType, @@ -140,7 +140,7 @@ export class PendingBlock { const validatorIndex = bigIntToUnpaddedBytes( toType(withdrawal.validatorIndex ?? 0, TypeOutput.BigInt), ) - const address = toType(withdrawal.address ?? Address.zero(), TypeOutput.Uint8Array) + const address = toType(withdrawal.address ?? createZeroAddress(), TypeOutput.Uint8Array) const amount = bigIntToUnpaddedBytes(toType(withdrawal.amount ?? 0, TypeOutput.BigInt)) withdrawalsBufTemp.push(concatBytes(indexBuf, validatorIndex, address, amount)) } diff --git a/packages/client/src/rpc/modules/debug.ts b/packages/client/src/rpc/modules/debug.ts index 758525c1cb..f118b561a9 100644 --- a/packages/client/src/rpc/modules/debug.ts +++ b/packages/client/src/rpc/modules/debug.ts @@ -1,4 +1,11 @@ -import { Address, TypeOutput, bigIntToHex, bytesToHex, hexToBytes, toType } from '@ethereumjs/util' +import { + TypeOutput, + bigIntToHex, + bytesToHex, + createAddressFromString, + hexToBytes, + toType, +} from '@ethereumjs/util' import { type VM, encodeReceipt, runTx } from '@ethereumjs/vm' import { INTERNAL_ERROR, INVALID_PARAMS } from '../error-code.js' @@ -304,8 +311,8 @@ export class Debug { next?.() }) const runCallOpts = { - caller: from !== undefined ? Address.fromString(from) : undefined, - to: to !== undefined ? Address.fromString(to) : undefined, + caller: from !== undefined ? createAddressFromString(from) : undefined, + to: to !== undefined ? createAddressFromString(to) : undefined, gasLimit: toType(gasLimit, TypeOutput.BigInt), gasPrice: toType(gasPrice, TypeOutput.BigInt), value: toType(value, TypeOutput.BigInt), @@ -373,7 +380,7 @@ export class Debug { // await here so that any error can be handled in the catch below for proper response return vmCopy.stateManager.dumpStorageRange!( // Validator already verified that `account` and `startKey` are properly formatted. - Address.fromString(account), + createAddressFromString(account), BigInt(startKey), limit, ) diff --git a/packages/client/src/rpc/modules/eth.ts b/packages/client/src/rpc/modules/eth.ts index 2d1f5b725c..e874293daf 100644 --- a/packages/client/src/rpc/modules/eth.ts +++ b/packages/client/src/rpc/modules/eth.ts @@ -7,7 +7,6 @@ import { createTxFromTxData, } from '@ethereumjs/tx' import { - Address, BIGINT_0, BIGINT_1, BIGINT_100, @@ -16,6 +15,8 @@ import { bigIntMax, bigIntToHex, bytesToHex, + createAddressFromString, + createZeroAddress, equalsBytes, hexToBytes, intToHex, @@ -51,7 +52,7 @@ import type { LegacyTransaction, TypedTransaction, } from '@ethereumjs/tx' -import type { PrefixedHexString } from '@ethereumjs/util' +import type { Address, PrefixedHexString } from '@ethereumjs/util' const EMPTY_SLOT = `0x${'00'.repeat(32)}` @@ -517,8 +518,8 @@ export class Eth { const data = transaction.data ?? transaction.input const runCallOpts = { - caller: from !== undefined ? Address.fromString(from) : undefined, - to: to !== undefined ? Address.fromString(to) : undefined, + caller: from !== undefined ? createAddressFromString(from) : undefined, + to: to !== undefined ? createAddressFromString(to) : undefined, gasLimit: toType(gasLimit, TypeOutput.BigInt), gasPrice: toType(gasPrice, TypeOutput.BigInt), value: toType(value, TypeOutput.BigInt), @@ -608,7 +609,9 @@ export class Eth { // set from address const from = - transaction.from !== undefined ? Address.fromString(transaction.from) : Address.zero() + transaction.from !== undefined + ? createAddressFromString(transaction.from) + : createZeroAddress() tx.getSenderAddress = () => { return from } @@ -631,7 +634,7 @@ export class Eth { */ async getBalance(params: [string, string]) { const [addressHex, blockOpt] = params - const address = Address.fromString(addressHex) + const address = createAddressFromString(addressHex) const block = await getBlockByOption(blockOpt, this._chain) if (this._vm === undefined) { @@ -737,7 +740,7 @@ export class Eth { const vm = await this._vm.shallowCopy() await vm.stateManager.setStateRoot(block.header.stateRoot) - const address = Address.fromString(addressHex) + const address = createAddressFromString(addressHex) const code = await vm.stateManager.getCode(address) return bytesToHex(code) } @@ -778,7 +781,7 @@ export class Eth { const block = await getBlockByOption(blockOpt, this._chain) await vm.stateManager.setStateRoot(block.header.stateRoot) - const address = Address.fromString(addressHex) + const address = createAddressFromString(addressHex) const account = await vm.stateManager.getAccount(address) if (account === undefined) { return EMPTY_SLOT @@ -875,7 +878,7 @@ export class Eth { const vm = await this._vm.shallowCopy() await vm.stateManager.setStateRoot(block.header.stateRoot) - const address = Address.fromString(addressHex) + const address = createAddressFromString(addressHex) const account = await vm.stateManager.getAccount(address) if (account === undefined) { return '0x0' @@ -1245,7 +1248,7 @@ export class Eth { } await vm.stateManager.setStateRoot(block.header.stateRoot) - const address = Address.fromString(addressHex) + const address = createAddressFromString(addressHex) const slots = slotsHex.map((slotHex) => setLengthLeft(hexToBytes(slotHex), 32)) const proof = await vm.stateManager.getProof!(address, slots) for (const p of proof.storageProof) { diff --git a/packages/client/test/integration/pow.spec.ts b/packages/client/test/integration/pow.spec.ts index 51f0b3d4ba..c2af982121 100644 --- a/packages/client/test/integration/pow.spec.ts +++ b/packages/client/test/integration/pow.spec.ts @@ -1,13 +1,15 @@ import { Hardfork, createCommonFromGethGenesis } from '@ethereumjs/common' -import { Address, hexToBytes, parseGethGenesisState } from '@ethereumjs/util' +import { createAddressFromPrivateKey, hexToBytes, parseGethGenesisState } from '@ethereumjs/util' import { rmSync } from 'fs' import { assert, describe, it } from 'vitest' import { Config } from '../../src/index.js' import { createInlineClient } from '../sim/simutils.js' +import type { Address } from '@ethereumjs/util' + const pk = hexToBytes('0x95a602ff1ae30a2243f400dcf002561b9743b2ae9827b1008e3714a5cc1c0cfe') -const minerAddress = Address.fromPrivateKey(pk) +const minerAddress = createAddressFromPrivateKey(pk) async function setupPowDevnet(prefundAddress: Address, cleanStart: boolean) { if (cleanStart) { diff --git a/packages/client/test/miner/miner.spec.ts b/packages/client/test/miner/miner.spec.ts index 0fa1c2e97b..ec82090d15 100644 --- a/packages/client/test/miner/miner.spec.ts +++ b/packages/client/test/miner/miner.spec.ts @@ -570,7 +570,7 @@ describe.skip('assembleBlocks() -> should stop assembling when a new block is re for (let i = 0; i < 1000; i++) { // In order not to pollute TxPool with too many txs from the same address // (or txs which are already known), keep generating a new address for each tx - const address = Address.fromPrivateKey(privateKey) + const address = createAddressFromPrivateKey(privateKey) await setBalance(vm, address, BigInt('200000000000001')) const tx = createTx({ address, privateKey }) await txPool.add(tx) diff --git a/packages/client/test/net/protocol/ethprotocol.spec.ts b/packages/client/test/net/protocol/ethprotocol.spec.ts index fb6ef7ce84..20fdc24c23 100644 --- a/packages/client/test/net/protocol/ethprotocol.spec.ts +++ b/packages/client/test/net/protocol/ethprotocol.spec.ts @@ -1,7 +1,13 @@ import { createBlockFromBlockData } from '@ethereumjs/block' import { Common, Chain as CommonChain, Hardfork } from '@ethereumjs/common' import { TransactionType, create1559FeeMarketTx, createTxFromTxData } from '@ethereumjs/tx' -import { Address, bigIntToBytes, bytesToBigInt, hexToBytes, randomBytes } from '@ethereumjs/util' +import { + bigIntToBytes, + bytesToBigInt, + createZeroAddress, + hexToBytes, + randomBytes, +} from '@ethereumjs/util' import { loadKZG } from 'kzg-wasm' import { assert, describe, it } from 'vitest' @@ -224,7 +230,11 @@ describe('[EthProtocol]', () => { const eip2929Tx = createTxFromTxData({ type: 1 }, { common: config.chainCommon }) const eip1559Tx = createTxFromTxData({ type: 2 }, { common: config.chainCommon }) const blobTx = createTxFromTxData( - { type: 3, to: Address.zero(), blobVersionedHashes: [hexToBytes(`0x01${'00'.repeat(31)}`)] }, + { + type: 3, + to: createZeroAddress(), + blobVersionedHashes: [hexToBytes(`0x01${'00'.repeat(31)}`)], + }, { common: config.chainCommon }, ) const res = p.encode(p.messages.filter((message) => message.name === 'Transactions')[0], [ diff --git a/packages/client/test/rpc/debug/getRawBlock.spec.ts b/packages/client/test/rpc/debug/getRawBlock.spec.ts index 4e560c185b..8c32a58cc1 100644 --- a/packages/client/test/rpc/debug/getRawBlock.spec.ts +++ b/packages/client/test/rpc/debug/getRawBlock.spec.ts @@ -1,7 +1,7 @@ import { BlockHeader, createBlockFromBlockData } from '@ethereumjs/block' import { createCustomCommon } from '@ethereumjs/common' import { create4844BlobTx, createLegacyTx } from '@ethereumjs/tx' -import { Address, bytesToHex, hexToBytes } from '@ethereumjs/util' +import { bytesToHex, createZeroAddress, hexToBytes } from '@ethereumjs/util' import { loadKZG } from 'kzg-wasm' import { assert, describe, it } from 'vitest' @@ -16,7 +16,7 @@ common.setHardfork('cancun') const mockedTx1 = createLegacyTx({}).sign(dummy.privKey) const mockedTx2 = createLegacyTx({ nonce: 1 }).sign(dummy.privKey) const mockedBlobTx3 = create4844BlobTx( - { nonce: 2, blobsData: ['0x1234'], to: Address.zero() }, + { nonce: 2, blobsData: ['0x1234'], to: createZeroAddress() }, { common }, ).sign(dummy.privKey) const blockHash = hexToBytes('0xdcf93da321b27bca12087d6526d2c10540a4c8dc29db1b36610c3004e0e5d2d5') diff --git a/packages/client/test/rpc/debug/getRawHeader.spec.ts b/packages/client/test/rpc/debug/getRawHeader.spec.ts index bd86b30f3c..19752304ac 100644 --- a/packages/client/test/rpc/debug/getRawHeader.spec.ts +++ b/packages/client/test/rpc/debug/getRawHeader.spec.ts @@ -1,7 +1,7 @@ import { BlockHeader, createBlockFromBlockData } from '@ethereumjs/block' import { createCustomCommon } from '@ethereumjs/common' import { create4844BlobTx, createLegacyTx } from '@ethereumjs/tx' -import { Address, bytesToHex, hexToBytes } from '@ethereumjs/util' +import { bytesToHex, createZeroAddress, hexToBytes } from '@ethereumjs/util' import { loadKZG } from 'kzg-wasm' import { assert, describe, it } from 'vitest' @@ -16,7 +16,7 @@ common.setHardfork('cancun') const mockedTx1 = createLegacyTx({}).sign(dummy.privKey) const mockedTx2 = createLegacyTx({ nonce: 1 }).sign(dummy.privKey) const mockedBlobTx3 = create4844BlobTx( - { nonce: 2, blobsData: ['0x1234'], to: Address.zero() }, + { nonce: 2, blobsData: ['0x1234'], to: createZeroAddress() }, { common }, ).sign(dummy.privKey) const blockHash = hexToBytes('0xdcf93da321b27bca12087d6526d2c10540a4c8dc29db1b36610c3004e0e5d2d5') diff --git a/packages/client/test/rpc/engine/getPayloadBodiesByHashV1.spec.ts b/packages/client/test/rpc/engine/getPayloadBodiesByHashV1.spec.ts index c43e167931..eb32e274ac 100644 --- a/packages/client/test/rpc/engine/getPayloadBodiesByHashV1.spec.ts +++ b/packages/client/test/rpc/engine/getPayloadBodiesByHashV1.spec.ts @@ -2,7 +2,13 @@ import { BlockHeader, createBlockFromBlockData } from '@ethereumjs/block' import { Hardfork } from '@ethereumjs/common' import { DefaultStateManager } from '@ethereumjs/statemanager' import { createTxFromTxData } from '@ethereumjs/tx' -import { Account, Address, bytesToHex, hexToBytes, randomBytes } from '@ethereumjs/util' +import { + Account, + bytesToHex, + createAddressFromPrivateKey, + hexToBytes, + randomBytes, +} from '@ethereumjs/util' import { assert, describe, it } from 'vitest' import { TOO_LARGE_REQUEST } from '../../../src/rpc/error-code.js' @@ -39,7 +45,7 @@ describe(method, () => { const rpc = getRpcClient(server) common.setHardfork(Hardfork.Cancun) const pkey = hexToBytes('0x9c9996335451aab4fc4eac58e31a8c300e095cdbcee532d53d09280e83360355') - const address = Address.fromPrivateKey(pkey) + const address = createAddressFromPrivateKey(pkey) await service.execution.vm.stateManager.putAccount(address, new Account()) const account = await service.execution.vm.stateManager.getAccount(address) @@ -125,7 +131,7 @@ describe(method, () => { const rpc = getRpcClient(server) common.setHardfork(Hardfork.London) const pkey = hexToBytes('0x9c9996335451aab4fc4eac58e31a8c300e095cdbcee532d53d09280e83360355') - const address = Address.fromPrivateKey(pkey) + const address = createAddressFromPrivateKey(pkey) await service.execution.vm.stateManager.putAccount(address, new Account()) const account = await service.execution.vm.stateManager.getAccount(address) diff --git a/packages/client/test/rpc/engine/getPayloadBodiesByRangeV1.spec.ts b/packages/client/test/rpc/engine/getPayloadBodiesByRangeV1.spec.ts index 45c4226068..1d5890fefb 100644 --- a/packages/client/test/rpc/engine/getPayloadBodiesByRangeV1.spec.ts +++ b/packages/client/test/rpc/engine/getPayloadBodiesByRangeV1.spec.ts @@ -2,7 +2,7 @@ import { BlockHeader, createBlockFromBlockData } from '@ethereumjs/block' import { Hardfork } from '@ethereumjs/common' import { DefaultStateManager } from '@ethereumjs/statemanager' import { createTxFromTxData } from '@ethereumjs/tx' -import { Account, Address, bytesToHex, hexToBytes } from '@ethereumjs/util' +import { Account, bytesToHex, createAddressFromPrivateKey, hexToBytes } from '@ethereumjs/util' import { assert, describe, it, vi } from 'vitest' import { INVALID_PARAMS, TOO_LARGE_REQUEST } from '../../../src/rpc/error-code.js' @@ -41,7 +41,7 @@ describe(method, () => { const rpc = getRpcClient(server) common.setHardfork(Hardfork.Cancun) const pkey = hexToBytes('0x9c9996335451aab4fc4eac58e31a8c300e095cdbcee532d53d09280e83360355') - const address = Address.fromPrivateKey(pkey) + const address = createAddressFromPrivateKey(pkey) await service.execution.vm.stateManager.putAccount(address, new Account()) const account = await service.execution.vm.stateManager.getAccount(address) @@ -123,7 +123,7 @@ describe(method, () => { const rpc = getRpcClient(server) common.setHardfork(Hardfork.London) const pkey = hexToBytes('0x9c9996335451aab4fc4eac58e31a8c300e095cdbcee532d53d09280e83360355') - const address = Address.fromPrivateKey(pkey) + const address = createAddressFromPrivateKey(pkey) await service.execution.vm.stateManager.putAccount(address, new Account()) const account = await service.execution.vm.stateManager.getAccount(address) diff --git a/packages/client/test/rpc/engine/getPayloadV3.spec.ts b/packages/client/test/rpc/engine/getPayloadV3.spec.ts index def3e58408..35aa080b5e 100644 --- a/packages/client/test/rpc/engine/getPayloadV3.spec.ts +++ b/packages/client/test/rpc/engine/getPayloadV3.spec.ts @@ -3,11 +3,12 @@ import { DefaultStateManager } from '@ethereumjs/statemanager' import { createTxFromTxData } from '@ethereumjs/tx' import { Account, - Address, blobsToCommitments, blobsToProofs, bytesToHex, commitmentsToVersionedHashes, + createAddressFromPrivateKey, + createZeroAddress, getBlobs, hexToBytes, } from '@ethereumjs/util' @@ -78,7 +79,7 @@ describe(method, () => { const rpc = getRpcClient(server) common.setHardfork(Hardfork.Cancun) const pkey = hexToBytes('0x9c9996335451aab4fc4eac58e31a8c300e095cdbcee532d53d09280e83360355') - const address = Address.fromPrivateKey(pkey) + const address = createAddressFromPrivateKey(pkey) await service.execution.vm.stateManager.putAccount(address, new Account()) const account = await service.execution.vm.stateManager.getAccount(address) @@ -104,7 +105,7 @@ describe(method, () => { maxFeePerGas: 10000000000n, maxPriorityFeePerGas: 100000000n, gasLimit: 30000000n, - to: Address.zero(), + to: createZeroAddress(), }, { common }, ).sign(pkey) diff --git a/packages/client/test/rpc/engine/newPayloadV1.spec.ts b/packages/client/test/rpc/engine/newPayloadV1.spec.ts index df1155e379..6a9402859e 100644 --- a/packages/client/test/rpc/engine/newPayloadV1.spec.ts +++ b/packages/client/test/rpc/engine/newPayloadV1.spec.ts @@ -1,6 +1,12 @@ import { BlockHeader } from '@ethereumjs/block' import { create1559FeeMarketTx } from '@ethereumjs/tx' -import { Address, bytesToHex, hexToBytes, zeros } from '@ethereumjs/util' +import { + bytesToHex, + createAddressFromPrivateKey, + createAddressFromString, + hexToBytes, + zeros, +} from '@ethereumjs/util' import { assert, describe, it, vi } from 'vitest' import { INVALID_PARAMS } from '../../../src/rpc/error-code.js' @@ -160,7 +166,7 @@ describe(method, () => { gasLimit: 21_000, maxFeePerGas: 10, value: 1, - to: Address.fromString('0x61FfE691821291D02E9Ba5D33098ADcee71a3a17'), + to: createAddressFromString('0x61FfE691821291D02E9Ba5D33098ADcee71a3a17'), }, { common }, ) @@ -182,7 +188,7 @@ describe(method, () => { const accountPk = hexToBytes( '0xe331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109', ) - const accountAddress = Address.fromPrivateKey(accountPk) + const accountAddress = createAddressFromPrivateKey(accountPk) const newGenesisJSON = { ...genesisJSON, alloc: { @@ -222,7 +228,7 @@ describe(method, () => { const accountPk = hexToBytes( '0xe331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109', ) - const accountAddress = Address.fromPrivateKey(accountPk) + const accountAddress = createAddressFromPrivateKey(accountPk) const newGenesisJSON = { ...genesisJSON, alloc: { diff --git a/packages/client/test/rpc/engine/newPayloadV2.spec.ts b/packages/client/test/rpc/engine/newPayloadV2.spec.ts index f11aaad90f..98ea103f73 100644 --- a/packages/client/test/rpc/engine/newPayloadV2.spec.ts +++ b/packages/client/test/rpc/engine/newPayloadV2.spec.ts @@ -1,6 +1,12 @@ import { BlockHeader } from '@ethereumjs/block' import { create1559FeeMarketTx } from '@ethereumjs/tx' -import { Address, bytesToHex, hexToBytes, zeros } from '@ethereumjs/util' +import { + bytesToHex, + createAddressFromPrivateKey, + createAddressFromString, + hexToBytes, + zeros, +} from '@ethereumjs/util' import { assert, describe, it, vi } from 'vitest' import { INVALID_PARAMS } from '../../../src/rpc/error-code.js' @@ -158,7 +164,7 @@ describe(`${method}: call with executionPayloadV1`, () => { gasLimit: 21_000, maxFeePerGas: 10, value: 1, - to: Address.fromString('0x61FfE691821291D02E9Ba5D33098ADcee71a3a17'), + to: createAddressFromString('0x61FfE691821291D02E9Ba5D33098ADcee71a3a17'), }, { common }, ) @@ -179,7 +185,7 @@ describe(`${method}: call with executionPayloadV1`, () => { const accountPk = hexToBytes( '0xe331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109', ) - const accountAddress = Address.fromPrivateKey(accountPk) + const accountAddress = createAddressFromPrivateKey(accountPk) const newGenesisJSON = { ...genesisJSON, alloc: { diff --git a/packages/client/test/rpc/eth/blobBaseFee.spec.ts b/packages/client/test/rpc/eth/blobBaseFee.spec.ts index 5a2dc594fc..5ca11d3b1f 100644 --- a/packages/client/test/rpc/eth/blobBaseFee.spec.ts +++ b/packages/client/test/rpc/eth/blobBaseFee.spec.ts @@ -1,11 +1,12 @@ import { Hardfork } from '@ethereumjs/common' import { createTxFromTxData } from '@ethereumjs/tx' import { - Address, BIGINT_0, BIGINT_256, blobsToCommitments, commitmentsToVersionedHashes, + createAddressFromPrivateKey, + createZeroAddress, getBlobs, hexToBytes, } from '@ethereumjs/util' @@ -21,7 +22,7 @@ import type { VMExecution } from '../../../src/execution/vmexecution.js' const method = 'eth_blobBaseFee' const privateKey = hexToBytes('0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8') -const accountAddress = Address.fromPrivateKey(privateKey) +const accountAddress = createAddressFromPrivateKey(privateKey) const produceBlockWith4844Tx = async ( execution: VMExecution, chain: Chain, @@ -53,7 +54,7 @@ const produceBlockWith4844Tx = async ( const blobVersionedHashes = [] const blobs = [] const kzgCommitments = [] - const to = Address.zero() + const to = createZeroAddress() if (blobsCount[i] > 0) { for (let blob = 0; blob < blobsCount[i]; blob++) { blobVersionedHashes.push(...blobVersionedHash) diff --git a/packages/client/test/rpc/eth/call.spec.ts b/packages/client/test/rpc/eth/call.spec.ts index a2d7613d0e..53cdad15a1 100644 --- a/packages/client/test/rpc/eth/call.spec.ts +++ b/packages/client/test/rpc/eth/call.spec.ts @@ -2,7 +2,7 @@ import { createBlockFromBlockData } from '@ethereumjs/block' import { createBlockchain } from '@ethereumjs/blockchain' import { Chain, Common, Hardfork } from '@ethereumjs/common' import { createLegacyTx } from '@ethereumjs/tx' -import { Address, bigIntToHex, bytesToHex } from '@ethereumjs/util' +import { bigIntToHex, bytesToHex, createAddressFromString } from '@ethereumjs/util' import { runBlock, runTx } from '@ethereumjs/vm' import { assert, describe, it } from 'vitest' @@ -33,7 +33,7 @@ describe(method, () => { const { vm } = execution // genesis address with balance - const address = Address.fromString('0xccfd725760a68823ff1e062f4cc97e1360e8d997') + const address = createAddressFromString('0xccfd725760a68823ff1e062f4cc97e1360e8d997') // contract: /* @@ -130,7 +130,7 @@ describe(method, () => { const rpc = getRpcClient(startRPC(manager.getMethods())) // genesis address with balance - const address = Address.fromString('0xccfd725760a68823ff1e062f4cc97e1360e8d997') + const address = createAddressFromString('0xccfd725760a68823ff1e062f4cc97e1360e8d997') const funcHash = '26b85ee1' // borrowed from valid test above const estimateTxData = { @@ -156,7 +156,7 @@ describe(method, () => { const rpc = getRpcClient(startRPC(manager.getMethods())) // genesis address with balance - const address = Address.fromString('0xccfd725760a68823ff1e062f4cc97e1360e8d997') + const address = createAddressFromString('0xccfd725760a68823ff1e062f4cc97e1360e8d997') const estimateTxData = { to: address.toString(), from: address.toString(), diff --git a/packages/client/test/rpc/eth/estimateGas.spec.ts b/packages/client/test/rpc/eth/estimateGas.spec.ts index 4210479c1a..c3c7da94c8 100644 --- a/packages/client/test/rpc/eth/estimateGas.spec.ts +++ b/packages/client/test/rpc/eth/estimateGas.spec.ts @@ -3,7 +3,7 @@ import { createBlockchain } from '@ethereumjs/blockchain' import { createCommonFromGethGenesis } from '@ethereumjs/common' import { getGenesis } from '@ethereumjs/genesis' import { createLegacyTx } from '@ethereumjs/tx' -import { Address, bigIntToHex } from '@ethereumjs/util' +import { bigIntToHex, createAddressFromString } from '@ethereumjs/util' import { runBlock, runTx } from '@ethereumjs/vm' import { assert, describe, it } from 'vitest' @@ -42,7 +42,7 @@ describe( await vm.stateManager.generateCanonicalGenesis!(getGenesis(1)) // genesis address with balance - const address = Address.fromString('0xccfd725760a68823ff1e062f4cc97e1360e8d997') + const address = createAddressFromString('0xccfd725760a68823ff1e062f4cc97e1360e8d997') // contract: /* @@ -196,7 +196,7 @@ describe( const rpc = getRpcClient(startRPC(manager.getMethods())) // genesis address with balance - const address = Address.fromString('0xccfd725760a68823ff1e062f4cc97e1360e8d997') + const address = createAddressFromString('0xccfd725760a68823ff1e062f4cc97e1360e8d997') const funcHash = '26b85ee1' // borrowed from valid test above const estimateTxData = { diff --git a/packages/client/test/rpc/eth/getBalance.spec.ts b/packages/client/test/rpc/eth/getBalance.spec.ts index 63c5b34e30..8b03a6e546 100644 --- a/packages/client/test/rpc/eth/getBalance.spec.ts +++ b/packages/client/test/rpc/eth/getBalance.spec.ts @@ -3,7 +3,7 @@ import { createBlockchain } from '@ethereumjs/blockchain' import { Chain, Common, Hardfork } from '@ethereumjs/common' import { getGenesis } from '@ethereumjs/genesis' import { createLegacyTx } from '@ethereumjs/tx' -import { Address, bigIntToHex } from '@ethereumjs/util' +import { bigIntToHex, createAddressFromString } from '@ethereumjs/util' import { runBlock } from '@ethereumjs/vm' import { assert, describe, it } from 'vitest' @@ -35,7 +35,7 @@ describe( await vm.stateManager.generateCanonicalGenesis!(getGenesis(1)) // genesis address with balance - const address = Address.fromString('0xccfd725760a68823ff1e062f4cc97e1360e8d997') + const address = createAddressFromString('0xccfd725760a68823ff1e062f4cc97e1360e8d997') // verify balance is genesis amount const genesisBalance = BigInt(0x15ac56edc4d12c0000) diff --git a/packages/client/test/rpc/eth/getBlockByNumber.spec.ts b/packages/client/test/rpc/eth/getBlockByNumber.spec.ts index 2e21890b93..4bec9dd941 100644 --- a/packages/client/test/rpc/eth/getBlockByNumber.spec.ts +++ b/packages/client/test/rpc/eth/getBlockByNumber.spec.ts @@ -1,7 +1,7 @@ import { createBlockFromBlockData } from '@ethereumjs/block' import { createCustomCommon } from '@ethereumjs/common' import { create4844BlobTx, createLegacyTx } from '@ethereumjs/tx' -import { Address, hexToBytes } from '@ethereumjs/util' +import { createZeroAddress, hexToBytes } from '@ethereumjs/util' import { loadKZG } from 'kzg-wasm' import { assert, describe, it } from 'vitest' @@ -16,7 +16,7 @@ common.setHardfork('cancun') const mockedTx1 = createLegacyTx({}).sign(dummy.privKey) const mockedTx2 = createLegacyTx({ nonce: 1 }).sign(dummy.privKey) const mockedBlobTx3 = create4844BlobTx( - { nonce: 2, blobsData: ['0x1234'], to: Address.zero() }, + { nonce: 2, blobsData: ['0x1234'], to: createZeroAddress() }, { common }, ).sign(dummy.privKey) const blockHash = hexToBytes('0xdcf93da321b27bca12087d6526d2c10540a4c8dc29db1b36610c3004e0e5d2d5') diff --git a/packages/client/test/rpc/eth/getBlockTransactionCountByNumber.spec.ts b/packages/client/test/rpc/eth/getBlockTransactionCountByNumber.spec.ts index 63418f5b06..df9b14ceac 100644 --- a/packages/client/test/rpc/eth/getBlockTransactionCountByNumber.spec.ts +++ b/packages/client/test/rpc/eth/getBlockTransactionCountByNumber.spec.ts @@ -3,7 +3,7 @@ import { createBlockchain } from '@ethereumjs/blockchain' import { Chain, Common, Hardfork } from '@ethereumjs/common' import { getGenesis } from '@ethereumjs/genesis' import { createLegacyTx } from '@ethereumjs/tx' -import { Address } from '@ethereumjs/util' +import { createAddressFromString } from '@ethereumjs/util' import { runBlock } from '@ethereumjs/vm' import { assert, describe, it } from 'vitest' @@ -35,7 +35,7 @@ describe(method, () => { await vm.stateManager.generateCanonicalGenesis!(getGenesis(1)) - const address = Address.fromString('0xccfd725760a68823ff1e062f4cc97e1360e8d997') + const address = createAddressFromString('0xccfd725760a68823ff1e062f4cc97e1360e8d997') // construct block with tx const tx = createLegacyTx({ gasLimit: 53000 }, { common, freeze: false }) @@ -82,7 +82,7 @@ describe(method, () => { await vm.stateManager.generateCanonicalGenesis!(getGenesis(1)) - const address = Address.fromString('0xccfd725760a68823ff1e062f4cc97e1360e8d997') + const address = createAddressFromString('0xccfd725760a68823ff1e062f4cc97e1360e8d997') // construct block with tx const tx = createLegacyTx({ gasLimit: 53000 }, { common, freeze: false }) diff --git a/packages/client/test/rpc/eth/getCode.spec.ts b/packages/client/test/rpc/eth/getCode.spec.ts index 720fd4496c..a580abc3c1 100644 --- a/packages/client/test/rpc/eth/getCode.spec.ts +++ b/packages/client/test/rpc/eth/getCode.spec.ts @@ -3,7 +3,7 @@ import { createBlockchain } from '@ethereumjs/blockchain' import { Chain, Common, Hardfork } from '@ethereumjs/common' import { getGenesis } from '@ethereumjs/genesis' import { createLegacyTx } from '@ethereumjs/tx' -import { Address } from '@ethereumjs/util' +import { createAddressFromString, createContractAddress } from '@ethereumjs/util' import { runBlock } from '@ethereumjs/vm' import { assert, describe, it } from 'vitest' @@ -31,7 +31,7 @@ describe(method, () => { await vm.stateManager.generateCanonicalGenesis!(getGenesis(1)) // genesis address - const address = Address.fromString('0xccfd725760a68823ff1e062f4cc97e1360e8d997') + const address = createAddressFromString('0xccfd725760a68823ff1e062f4cc97e1360e8d997') // verify code is null const res = await rpc.request(method, [address.toString(), 'latest']) @@ -54,7 +54,7 @@ describe(method, () => { const { vm } = execution // genesis address with balance - const address = Address.fromString('0xccfd725760a68823ff1e062f4cc97e1360e8d997') + const address = createAddressFromString('0xccfd725760a68823ff1e062f4cc97e1360e8d997') // sample contract from https://ethereum.stackexchange.com/a/70791 const data = @@ -88,7 +88,7 @@ describe(method, () => { const { createdAddress } = result.results[0] await vm.blockchain.putBlock(ranBlock!) - const expectedContractAddress = Address.generate(address, BigInt(0)) + const expectedContractAddress = createContractAddress(address, BigInt(0)) assert.ok( createdAddress!.equals(expectedContractAddress), 'should match the expected contract address', diff --git a/packages/client/test/rpc/eth/getFeeHistory.spec.ts b/packages/client/test/rpc/eth/getFeeHistory.spec.ts index e49108903f..4a21400160 100644 --- a/packages/client/test/rpc/eth/getFeeHistory.spec.ts +++ b/packages/client/test/rpc/eth/getFeeHistory.spec.ts @@ -2,13 +2,14 @@ import { paramsBlock } from '@ethereumjs/block' import { Common, Chain as CommonChain, Hardfork } from '@ethereumjs/common' import { createTxFromTxData } from '@ethereumjs/tx' import { - Address, BIGINT_0, BIGINT_256, bigIntToHex, blobsToCommitments, bytesToBigInt, commitmentsToVersionedHashes, + createAddressFromPrivateKey, + createZeroAddress, getBlobs, } from '@ethereumjs/util' import { buildBlock } from '@ethereumjs/vm' @@ -26,12 +27,12 @@ import type { VMExecution } from '../../../src/execution/index.js' const method = 'eth_feeHistory' const privateKey = hexToBytes('0xe331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109') -const pKeyAddress = Address.fromPrivateKey(privateKey) +const pKeyAddress = createAddressFromPrivateKey(privateKey) const privateKey4844 = hexToBytes( '0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8', ) -const p4844Address = Address.fromPrivateKey(privateKey4844) +const p4844Address = createAddressFromPrivateKey(privateKey4844) const produceFakeGasUsedBlock = async (execution: VMExecution, chain: Chain, gasUsed: bigint) => { const { vm } = execution @@ -148,7 +149,7 @@ const produceBlockWith4844Tx = async ( const blobVersionedHashes = [] const blobs = [] const kzgCommitments = [] - const to = Address.zero() + const to = createZeroAddress() if (blobsCount[i] > 0) { for (let blob = 0; blob < blobsCount[i]; blob++) { blobVersionedHashes.push(...blobVersionedHash) diff --git a/packages/client/test/rpc/eth/getLogs.spec.ts b/packages/client/test/rpc/eth/getLogs.spec.ts index c433cddea8..db1f6e6d91 100644 --- a/packages/client/test/rpc/eth/getLogs.spec.ts +++ b/packages/client/test/rpc/eth/getLogs.spec.ts @@ -1,5 +1,5 @@ import { createLegacyTx } from '@ethereumjs/tx' -import { Address, bytesToHex, hexToBytes } from '@ethereumjs/util' +import { bytesToHex, createContractAddress, hexToBytes } from '@ethereumjs/util' import { assert, describe, it } from 'vitest' import { INVALID_PARAMS } from '../../../src/rpc/error-code.js' @@ -49,8 +49,8 @@ describe(method, async () => { { common }, ).sign(dummy.privKey) - const contractAddr1 = Address.generate(dummy.addr, BigInt(0)) - const contractAddr2 = Address.generate(dummy.addr, BigInt(1)) + const contractAddr1 = createContractAddress(dummy.addr, BigInt(0)) + const contractAddr2 = createContractAddress(dummy.addr, BigInt(1)) // construct txs to emit the logs // data calls log(logCount: 10, num1: 1, num2: 2, num3: 3, num4: 4) const data = hexToBytes( diff --git a/packages/client/test/rpc/eth/getProof.spec.ts b/packages/client/test/rpc/eth/getProof.spec.ts index 84f52a7db8..dd3befdfcb 100644 --- a/packages/client/test/rpc/eth/getProof.spec.ts +++ b/packages/client/test/rpc/eth/getProof.spec.ts @@ -2,7 +2,7 @@ import { createBlockFromBlockData } from '@ethereumjs/block' import { createBlockchain } from '@ethereumjs/blockchain' import { Common } from '@ethereumjs/common' import { createLegacyTx } from '@ethereumjs/tx' -import { Address, bigIntToHex } from '@ethereumjs/util' +import { bigIntToHex, createAddressFromString } from '@ethereumjs/util' import { runBlock } from '@ethereumjs/vm' import { assert, describe, it } from 'vitest' @@ -106,7 +106,7 @@ describe(method, async () => { const { vm } = execution // genesis address with balance - const address = Address.fromString('0xccfd725760a68823ff1e062f4cc97e1360e8d997') + const address = createAddressFromString('0xccfd725760a68823ff1e062f4cc97e1360e8d997') // contract inspired from https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getstorageat/ /* diff --git a/packages/client/test/rpc/eth/getStorageAt.spec.ts b/packages/client/test/rpc/eth/getStorageAt.spec.ts index e5d3784ead..b51f409155 100644 --- a/packages/client/test/rpc/eth/getStorageAt.spec.ts +++ b/packages/client/test/rpc/eth/getStorageAt.spec.ts @@ -1,6 +1,6 @@ import { createBlockFromBlockData } from '@ethereumjs/block' import { createLegacyTx } from '@ethereumjs/tx' -import { Address } from '@ethereumjs/util' +import { createAddressFromString } from '@ethereumjs/util' import { runBlock } from '@ethereumjs/vm' import { assert, describe, it } from 'vitest' @@ -14,7 +14,7 @@ const method = 'eth_getStorageAt' describe(method, async () => { it('call with valid arguments', async () => { - const address = Address.fromString(`0x${'11'.repeat(20)}`) + const address = createAddressFromString(`0x${'11'.repeat(20)}`) const emptySlotStr = `0x${'00'.repeat(32)}` const { execution, common, server, chain } = await setupChain(pow, 'pow') diff --git a/packages/client/test/rpc/eth/getTransactionCount.spec.ts b/packages/client/test/rpc/eth/getTransactionCount.spec.ts index 03d8e6e068..334725ecca 100644 --- a/packages/client/test/rpc/eth/getTransactionCount.spec.ts +++ b/packages/client/test/rpc/eth/getTransactionCount.spec.ts @@ -3,7 +3,13 @@ import { createBlockchain } from '@ethereumjs/blockchain' import { Chain, Common, Hardfork } from '@ethereumjs/common' import { getGenesis } from '@ethereumjs/genesis' import { createLegacyTx, createTxFromTxData } from '@ethereumjs/tx' -import { Account, Address, hexToBytes, randomBytes } from '@ethereumjs/util' +import { + Account, + createAddressFromPrivateKey, + createAddressFromString, + hexToBytes, + randomBytes, +} from '@ethereumjs/util' import { runBlock } from '@ethereumjs/vm' import { assert, describe, it } from 'vitest' @@ -37,7 +43,7 @@ describe(method, () => { await vm.stateManager.generateCanonicalGenesis!(getGenesis(1)) // a genesis address - const address = Address.fromString('0xccfd725760a68823ff1e062f4cc97e1360e8d997') + const address = createAddressFromString('0xccfd725760a68823ff1e062f4cc97e1360e8d997') // verify nonce is 0 let res = await rpc.request(method, [address.toString(), 'latest']) @@ -84,7 +90,7 @@ describe(method, () => { const rpc = getRpcClient(startRPC(manager.getMethods())) const pk = hexToBytes('0x266682876da8fd86410d001ec33c7c281515aeeb640d175693534062e2599238') - const address = Address.fromPrivateKey(pk) + const address = createAddressFromPrivateKey(pk) await service.execution.vm.stateManager.putAccount(address, new Account()) const account = await service.execution.vm.stateManager.getAccount(address) account!.balance = 0xffffffffffffffn diff --git a/packages/client/test/rpc/helpers.ts b/packages/client/test/rpc/helpers.ts index 551daab306..e25fccdc05 100644 --- a/packages/client/test/rpc/helpers.ts +++ b/packages/client/test/rpc/helpers.ts @@ -6,6 +6,7 @@ import { Address, BIGINT_1, KECCAK256_RLP, + createAddressFromString, hexToBytes, parseGethGenesisState, } from '@ethereumjs/util' @@ -93,7 +94,7 @@ export async function createClient(clientOpts: Partial = {}) { const config = new Config({ minerCoinbase: clientOpts.minerCoinbase !== undefined - ? Address.fromString(clientOpts.minerCoinbase) + ? createAddressFromString(clientOpts.minerCoinbase) : undefined, common, saveReceipts: clientOpts.enableMetaDB, diff --git a/packages/client/test/sim/simutils.ts b/packages/client/test/sim/simutils.ts index 2ddba64f10..cdd3479dc7 100644 --- a/packages/client/test/sim/simutils.ts +++ b/packages/client/test/sim/simutils.ts @@ -2,13 +2,13 @@ import { executionPayloadFromBeaconPayload } from '@ethereumjs/block' import { createBlockchain } from '@ethereumjs/blockchain' import { create1559FeeMarketTx, create4844BlobTx } from '@ethereumjs/tx' import { - Address, BIGINT_1, blobsToCommitments, blobsToProofs, bytesToHex, bytesToUtf8, commitmentsToVersionedHashes, + createAddressFromPrivateKey, getBlobs, randomBytes, } from '@ethereumjs/util' @@ -323,7 +323,7 @@ export const runBlobTx = async ( const proofs = blobsToProofs(kzg, blobs, commitments) const hashes = commitmentsToVersionedHashes(commitments) - const sender = Address.fromPrivateKey(pkey) + const sender = createAddressFromPrivateKey(pkey) const txData: TxData[TransactionType.BlobEIP4844] = { to, data: '0x', @@ -395,7 +395,7 @@ export const createBlobTxs = async ( const txns = [] for (let x = startNonce; x <= startNonce + numTxs; x++) { - const sender = Address.fromPrivateKey(pkey) + const sender = createAddressFromPrivateKey(pkey) const txData = { from: sender.toString(), ...txMeta, diff --git a/packages/client/test/sim/snapsync.spec.ts b/packages/client/test/sim/snapsync.spec.ts index 89ae5e2422..dfd5719af1 100644 --- a/packages/client/test/sim/snapsync.spec.ts +++ b/packages/client/test/sim/snapsync.spec.ts @@ -1,7 +1,7 @@ import { createCommonFromGethGenesis } from '@ethereumjs/common' import { - Address, bytesToHex, + createAddressFromString, hexToBytes, parseGethGenesisState, privateToAddress, @@ -217,7 +217,7 @@ describe('simple mainnet test run', async () => { } for (const addressString of Object.keys(customGenesisState)) { - const address = Address.fromString(addressString) + const address = createAddressFromString(addressString) const account = await stateManager?.getAccount(address) assert.equal( account?.balance, diff --git a/packages/client/test/sim/txGenerator.ts b/packages/client/test/sim/txGenerator.ts index bb1225d710..9fd4d2dde3 100644 --- a/packages/client/test/sim/txGenerator.ts +++ b/packages/client/test/sim/txGenerator.ts @@ -1,10 +1,10 @@ // Adapted from - https://github.com/Inphi/eip4844-interop/blob/master/blob_tx_generator/blob.js import { create4844BlobTx } from '@ethereumjs/tx' import { - Address, blobsToCommitments, bytesToHex, commitmentsToVersionedHashes, + createAddressFromPrivateKey, hexToBytes, randomBytes, } from '@ethereumjs/util' @@ -24,7 +24,7 @@ const MAX_USEFUL_BYTES_PER_TX = USEFUL_BYTES_PER_BLOB * MAX_BLOBS_PER_TX - 1 const BLOB_SIZE = BYTES_PER_FIELD_ELEMENT * FIELD_ELEMENTS_PER_BLOB const pkey = hexToBytes('0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8') -const sender = Address.fromPrivateKey(pkey) +const sender = createAddressFromPrivateKey(pkey) const kzg = await loadKZG() @@ -100,7 +100,7 @@ async function run(data: any) { const commitments = blobsToCommitments(kzg, blobs) const hashes = commitmentsToVersionedHashes(commitments) - const account = Address.fromPrivateKey(randomBytes(32)) + const account = createAddressFromPrivateKey(randomBytes(32)) const txData: TxData[TransactionType.BlobEIP4844] = { to: account.toString(), data: '0x', diff --git a/packages/evm/src/evm.ts b/packages/evm/src/evm.ts index cf954832e2..093339bd10 100644 --- a/packages/evm/src/evm.ts +++ b/packages/evm/src/evm.ts @@ -10,6 +10,7 @@ import { MAX_INTEGER, bigIntToBytes, bytesToUnprefixedHex, + createZeroAddress, equalsBytes, generateAddress, generateAddress2, @@ -716,14 +717,14 @@ export class EVM implements EVMInterface { message: Message, opts: InterpreterOpts = {}, ): Promise { - let contract = await this.stateManager.getAccount(message.to ?? Address.zero()) + let contract = await this.stateManager.getAccount(message.to ?? createZeroAddress()) if (!contract) { contract = new Account() } const env = { - address: message.to ?? Address.zero(), - caller: message.caller ?? Address.zero(), + address: message.to ?? createZeroAddress(), + caller: message.caller ?? createZeroAddress(), callData: message.data ?? Uint8Array.from([0]), callValue: message.value ?? BIGINT_0, code: message.code as Uint8Array, @@ -731,7 +732,7 @@ export class EVM implements EVMInterface { isCreate: message.isCreate ?? false, depth: message.depth ?? 0, gasPrice: this._tx!.gasPrice, - origin: this._tx!.origin ?? message.caller ?? Address.zero(), + origin: this._tx!.origin ?? message.caller ?? createZeroAddress(), block: this._block ?? defaultBlock(), contract, codeAddress: message.codeAddress, @@ -814,9 +815,9 @@ export class EVM implements EVMInterface { this._block = opts.block ?? defaultBlock() this._tx = { gasPrice: opts.gasPrice ?? BIGINT_0, - origin: opts.origin ?? opts.caller ?? Address.zero(), + origin: opts.origin ?? opts.caller ?? createZeroAddress(), } - const caller = opts.caller ?? Address.zero() + const caller = opts.caller ?? createZeroAddress() const value = opts.value ?? BIGINT_0 if (opts.skipBalance === true) { @@ -952,14 +953,14 @@ export class EVM implements EVMInterface { this._tx = { gasPrice: opts.gasPrice ?? BIGINT_0, - origin: opts.origin ?? opts.caller ?? Address.zero(), + origin: opts.origin ?? opts.caller ?? createZeroAddress(), } const message = new Message({ code: opts.code, data: opts.data, gasLimit: opts.gasLimit ?? BigInt(0xffffff), - to: opts.to ?? Address.zero(), + to: opts.to ?? createZeroAddress(), caller: opts.caller, value: opts.value, depth: opts.depth, @@ -1148,8 +1149,8 @@ export function defaultBlock(): Block { return { header: { number: BIGINT_0, - cliqueSigner: () => Address.zero(), - coinbase: Address.zero(), + cliqueSigner: () => createZeroAddress(), + coinbase: createZeroAddress(), timestamp: BIGINT_0, difficulty: BIGINT_0, prevRandao: zeros(32), diff --git a/packages/evm/src/message.ts b/packages/evm/src/message.ts index 7730fec394..ccc758f2d1 100644 --- a/packages/evm/src/message.ts +++ b/packages/evm/src/message.ts @@ -1,13 +1,13 @@ -import { Address, BIGINT_0 } from '@ethereumjs/util' +import { BIGINT_0, createZeroAddress } from '@ethereumjs/util' import type { PrecompileFunc } from './precompiles/index.js' import type { EOFEnv } from './types.js' import type { AccessWitnessInterface } from '@ethereumjs/common' -import type { PrefixedHexString } from '@ethereumjs/util' +import type { Address, PrefixedHexString } from '@ethereumjs/util' const defaults = { value: BIGINT_0, - caller: Address.zero(), + caller: createZeroAddress(), data: new Uint8Array(0), depth: 0, isStatic: false, diff --git a/packages/evm/src/opcodes/functions.ts b/packages/evm/src/opcodes/functions.ts index 8b8fc1fde0..d20b18faa0 100644 --- a/packages/evm/src/opcodes/functions.ts +++ b/packages/evm/src/opcodes/functions.ts @@ -41,7 +41,7 @@ import { EOFBYTES, EOFHASH, isEOF } from '../eof/util.js' import { ERROR } from '../exceptions.js' import { - addresstoBytes, + createAddressFromStackBigInt, describeLocation, exponentiation, fromTwos, @@ -428,7 +428,7 @@ export const handlers: Map = new Map([ 0x31, async function (runState) { const addressBigInt = runState.stack.pop() - const address = new Address(addresstoBytes(addressBigInt)) + const address = createAddressFromStackBigInt(addressBigInt) const balance = await runState.interpreter.getExternalBalance(address) runState.stack.push(balance) }, @@ -522,7 +522,7 @@ export const handlers: Map = new Map([ 0x3b, async function (runState) { const addressBigInt = runState.stack.pop() - const address = new Address(addresstoBytes(addressBigInt)) + const address = createAddressFromStackBigInt(addressBigInt) // EOF check const code = await runState.stateManager.getCode(address) if (isEOF(code)) { @@ -532,7 +532,7 @@ export const handlers: Map = new Map([ } const size = BigInt( - await runState.stateManager.getCodeSize(new Address(addresstoBytes(addressBigInt))), + await runState.stateManager.getCodeSize(createAddressFromStackBigInt(addressBigInt)), ) runState.stack.push(size) @@ -545,7 +545,7 @@ export const handlers: Map = new Map([ const [addressBigInt, memOffset, codeOffset, dataLength] = runState.stack.popN(4) if (dataLength !== BIGINT_0) { - let code = await runState.stateManager.getCode(new Address(addresstoBytes(addressBigInt))) + let code = await runState.stateManager.getCode(createAddressFromStackBigInt(addressBigInt)) if (isEOF(code)) { // In legacy code, the target code is treated as to be "EOFBYTES" code @@ -564,7 +564,7 @@ export const handlers: Map = new Map([ 0x3f, async function (runState) { const addressBigInt = runState.stack.pop() - const address = new Address(addresstoBytes(addressBigInt)) + const address = createAddressFromStackBigInt(addressBigInt) // EOF check const code = await runState.stateManager.getCode(address) @@ -1419,7 +1419,7 @@ export const handlers: Map = new Map([ async function (runState: RunState, common: Common) { const [_currentGasLimit, toAddr, value, inOffset, inLength, outOffset, outLength] = runState.stack.popN(7) - const toAddress = new Address(addresstoBytes(toAddr)) + const toAddress = createAddressFromStackBigInt(toAddr) let data = new Uint8Array(0) if (inLength !== BIGINT_0) { @@ -1447,7 +1447,7 @@ export const handlers: Map = new Map([ async function (runState: RunState, common: Common) { const [_currentGasLimit, toAddr, value, inOffset, inLength, outOffset, outLength] = runState.stack.popN(7) - const toAddress = new Address(addresstoBytes(toAddr)) + const toAddress = createAddressFromStackBigInt(toAddr) let gasLimit = runState.messageGasLimit! if (value !== BIGINT_0) { @@ -1476,7 +1476,7 @@ export const handlers: Map = new Map([ const value = runState.interpreter.getCallValue() const [_currentGasLimit, toAddr, inOffset, inLength, outOffset, outLength] = runState.stack.popN(6) - const toAddress = new Address(addresstoBytes(toAddr)) + const toAddress = createAddressFromStackBigInt(toAddr) let data = new Uint8Array(0) if (inLength !== BIGINT_0) { @@ -1580,7 +1580,7 @@ export const handlers: Map = new Map([ const [_currentGasLimit, addr, value, argsOffset, argsLength, retOffset, retLength] = runState.stack.popN(7) - const toAddress = new Address(addresstoBytes(addr)) + const toAddress = createAddressFromStackBigInt(addr) const gasLimit = runState.messageGasLimit! runState.messageGasLimit = undefined @@ -1625,7 +1625,7 @@ export const handlers: Map = new Map([ return } - const toAddress = new Address(addresstoBytes(toAddr)) + const toAddress = createAddressFromStackBigInt(toAddr) let data = new Uint8Array(0) if (inLength !== BIGINT_0) { @@ -1660,7 +1660,7 @@ export const handlers: Map = new Map([ return } - const toAddress = new Address(addresstoBytes(toAddr)) + const toAddress = createAddressFromStackBigInt(toAddr) const code = await runState.stateManager.getCode(toAddress) @@ -1687,7 +1687,7 @@ export const handlers: Map = new Map([ const value = BIGINT_0 const [_currentGasLimit, toAddr, inOffset, inLength, outOffset, outLength] = runState.stack.popN(6) - const toAddress = new Address(addresstoBytes(toAddr)) + const toAddress = createAddressFromStackBigInt(toAddr) const gasLimit = runState.messageGasLimit! runState.messageGasLimit = undefined @@ -1724,7 +1724,7 @@ export const handlers: Map = new Map([ return } - const toAddress = new Address(addresstoBytes(toAddr)) + const toAddress = createAddressFromStackBigInt(toAddr) let data = new Uint8Array(0) if (inLength !== BIGINT_0) { @@ -1766,7 +1766,7 @@ export const handlers: Map = new Map([ 0xff, async function (runState) { const selfdestructToAddressBigInt = runState.stack.pop() - const selfdestructToAddress = new Address(addresstoBytes(selfdestructToAddressBigInt)) + const selfdestructToAddress = createAddressFromStackBigInt(selfdestructToAddressBigInt) return runState.interpreter.selfDestruct(selfdestructToAddress) }, ], diff --git a/packages/evm/src/opcodes/gas.ts b/packages/evm/src/opcodes/gas.ts index 81cfae362c..6f8cd64252 100644 --- a/packages/evm/src/opcodes/gas.ts +++ b/packages/evm/src/opcodes/gas.ts @@ -1,7 +1,6 @@ import { Hardfork } from '@ethereumjs/common' import { Account, - Address, BIGINT_0, BIGINT_1, BIGINT_3, @@ -24,7 +23,7 @@ import { updateSstoreGasEIP1283 } from './EIP1283.js' import { updateSstoreGasEIP2200 } from './EIP2200.js' import { accessAddressEIP2929, accessStorageEIP2929 } from './EIP2929.js' import { - addresstoBytes, + createAddressFromStackBigInt, divCeil, maxCallGas, setLengthLeftStorage, @@ -91,12 +90,11 @@ export const dynamicGasHandlers: Map { - const address = addresstoBytes(runState.stack.peek()[0]) + const address = createAddressFromStackBigInt(runState.stack.peek()[0]) let charge2929Gas = true if (common.isActivatedEIP(6800)) { - const balanceAddress = new Address(address) const coldAccessGas = runState.env.accessWitness!.touchAddressOnReadAndComputeGas( - balanceAddress, + address, 0, VERKLE_BALANCE_LEAF_KEY, ) @@ -106,7 +104,7 @@ export const dynamicGasHandlers: Map { - const addressBytes = addresstoBytes(runState.stack.peek()[0]) - const address = new Address(addressBytes) + const address = createAddressFromStackBigInt(runState.stack.peek()[0]) let charge2929Gas = true if ( @@ -183,7 +180,7 @@ export const dynamicGasHandlers: Map { const [addressBigInt, memOffset, _codeOffset, dataLength] = runState.stack.peek(4) - const addressBytes = addresstoBytes(addressBigInt) - const address = new Address(addressBytes) + const address = createAddressFromStackBigInt(addressBigInt) gas += subMemUsage(runState, memOffset, dataLength, common) @@ -222,7 +218,7 @@ export const dynamicGasHandlers: Map { - const address = addresstoBytes(runState.stack.peek()[0]) + const address = createAddressFromStackBigInt(runState.stack.peek()[0]) let charge2929Gas = true if (common.isActivatedEIP(6800)) { - const codeAddress = new Address(address) - let coldAccessGas = BIGINT_0 coldAccessGas += runState.env.accessWitness!.touchAddressOnReadAndComputeGas( - codeAddress, + address, 0, VERKLE_CODE_HASH_LEAF_KEY, ) @@ -289,7 +283,7 @@ export const dynamicGasHandlers: Map { const [currentGasLimit, toAddr, value, inOffset, inLength, outOffset, outLength] = runState.stack.peek(7) - const toAddress = new Address(addresstoBytes(toAddr)) + const toAddress = createAddressFromStackBigInt(toAddr) if (runState.interpreter.isStatic() && value !== BIGINT_0) { trap(ERROR.STATIC_STATE_CHANGE) @@ -641,7 +635,7 @@ export const dynamicGasHandlers: Map { const [currentGasLimit, toAddr, value, inOffset, inLength, outOffset, outLength] = runState.stack.peek(7) - const toAddress = new Address(addresstoBytes(toAddr)) + const toAddress = createAddressFromStackBigInt(toAddr) gas += subMemUsage(runState, inOffset, inLength, common) gas += subMemUsage(runState, outOffset, outLength, common) @@ -658,7 +652,12 @@ export const dynamicGasHandlers: Map { const [currentGasLimit, toAddr, inOffset, inLength, outOffset, outLength] = runState.stack.peek(6) - const toAddress = new Address(addresstoBytes(toAddr)) + const toAddress = createAddressFromStackBigInt(toAddr) gas += subMemUsage(runState, inOffset, inLength, common) gas += subMemUsage(runState, outOffset, outLength, common) @@ -714,7 +713,12 @@ export const dynamicGasHandlers: Map } const res = await evm.runCall(runCallArgs) - const address = Address.fromString(bytesToHex(res.execResult.returnValue.slice(12))) + const address = createAddressFromString(bytesToHex(res.execResult.returnValue.slice(12))) const code = await evm.stateManager.getCode(address) assert.equal( diff --git a/packages/evm/test/customPrecompiles.spec.ts b/packages/evm/test/customPrecompiles.spec.ts index ef73bb7efa..7829d6e670 100644 --- a/packages/evm/test/customPrecompiles.spec.ts +++ b/packages/evm/test/customPrecompiles.spec.ts @@ -1,4 +1,4 @@ -import { Address, hexToBytes, utf8ToBytes } from '@ethereumjs/util' +import { Address, createZeroAddress, hexToBytes, utf8ToBytes } from '@ethereumjs/util' import { assert, describe, it } from 'vitest' import { type PrecompileInput, createEVM } from '../src/index.js' @@ -30,13 +30,13 @@ describe('EVM -> custom precompiles', () => { const EVMOverride = await createEVM({ customPrecompiles: [ { - address: Address.zero(), + address: createZeroAddress(), function: customPrecompileNoInput, }, ], }) const result = await EVMOverride.runCall({ - to: Address.zero(), + to: createZeroAddress(), gasLimit: BigInt(30000), data: utf8ToBytes(''), caller: sender, diff --git a/packages/evm/test/eips/eip-3860.spec.ts b/packages/evm/test/eips/eip-3860.spec.ts index 09992f364a..2d4ff7c17f 100644 --- a/packages/evm/test/eips/eip-3860.spec.ts +++ b/packages/evm/test/eips/eip-3860.spec.ts @@ -1,5 +1,12 @@ import { Chain, Common, Hardfork } from '@ethereumjs/common' -import { Address, concatBytes, equalsBytes, hexToBytes, privateToAddress } from '@ethereumjs/util' +import { + Address, + concatBytes, + createAddressFromString, + equalsBytes, + hexToBytes, + privateToAddress, +} from '@ethereumjs/util' import { assert, describe, it } from 'vitest' import { createEVM } from '../../src/index.js' @@ -53,14 +60,14 @@ describe('EIP 3860 tests', () => { hardfork: Hardfork.London, eips: [], }) - const caller = Address.fromString('0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b') + const caller = createAddressFromString('0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b') const evm = await createEVM({ common: commonWith3860, }) const evmWithout3860 = await createEVM({ common: commonWithout3860, }) - const contractFactory = Address.fromString('0xb94f5374fce5edbc8e2a8697c15331677e6ebf0b') + const contractFactory = createAddressFromString('0xb94f5374fce5edbc8e2a8697c15331677e6ebf0b') const contractAccount = await evm.stateManager.getAccount(contractFactory) await evm.stateManager.putAccount(contractFactory, contractAccount!) await evmWithout3860.stateManager.putAccount(contractFactory, contractAccount!) @@ -97,14 +104,14 @@ describe('EIP 3860 tests', () => { hardfork: Hardfork.London, eips: [], }) - const caller = Address.fromString('0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b') + const caller = createAddressFromString('0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b') const evm = await createEVM({ common: commonWith3860, }) const evmWithout3860 = await createEVM({ common: commonWithout3860, }) - const contractFactory = Address.fromString('0xb94f5374fce5edbc8e2a8697c15331677e6ebf0b') + const contractFactory = createAddressFromString('0xb94f5374fce5edbc8e2a8697c15331677e6ebf0b') const contractAccount = await evm.stateManager.getAccount(contractFactory) await evm.stateManager.putAccount(contractFactory, contractAccount!) await evmWithout3860.stateManager.putAccount(contractFactory, contractAccount!) @@ -167,7 +174,7 @@ describe('EIP 3860 tests', () => { hardfork: Hardfork.London, eips: [3860], }) - const caller = Address.fromString('0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b') + const caller = createAddressFromString('0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b') for (const code of ['F0', 'F5']) { const evm = await createEVM({ common: commonWith3860, @@ -178,7 +185,7 @@ describe('EIP 3860 tests', () => { common: commonWith3860, allowUnlimitedInitCodeSize: false, }) - const contractFactory = Address.fromString('0xb94f5374fce5edbc8e2a8697c15331677e6ebf0b') + const contractFactory = createAddressFromString('0xb94f5374fce5edbc8e2a8697c15331677e6ebf0b') const contractAccount = await evm.stateManager.getAccount(contractFactory) await evm.stateManager.putAccount(contractFactory, contractAccount!) await evmDisabled.stateManager.putAccount(contractFactory, contractAccount!) diff --git a/packages/evm/test/precompiles/09-blake2f.spec.ts b/packages/evm/test/precompiles/09-blake2f.spec.ts index 21a1390896..516e00c200 100644 --- a/packages/evm/test/precompiles/09-blake2f.spec.ts +++ b/packages/evm/test/precompiles/09-blake2f.spec.ts @@ -1,5 +1,5 @@ import { Chain, Common, Hardfork } from '@ethereumjs/common' -import { Address, bytesToHex, hexToBytes } from '@ethereumjs/util' +import { bytesToHex, createZeroAddress, hexToBytes } from '@ethereumjs/util' import { assert, beforeAll, describe, it } from 'vitest' import { createEVM, getActivePrecompiles } from '../../src/index.js' @@ -125,7 +125,7 @@ describe('Precompiles: BLAKE2F', () => { } it('should also work on non-zero aligned inputs', async () => { - const addr = Address.zero() + const addr = createZeroAddress() // Blake2f calldata from https://etherscan.io/tx/0x4f2e13a0a3f14033630ab2b8cdad09d316826375f761ded5b31253bb42e0a476 // (This tx calls into Blake2f multiple times, but one of them is taken) const calldata = diff --git a/packages/evm/test/precompiles/eip-2537-bls.spec.ts b/packages/evm/test/precompiles/eip-2537-bls.spec.ts index 138eeeacfe..87344f39b2 100644 --- a/packages/evm/test/precompiles/eip-2537-bls.spec.ts +++ b/packages/evm/test/precompiles/eip-2537-bls.spec.ts @@ -1,5 +1,5 @@ import { Chain, Common, Hardfork } from '@ethereumjs/common' -import { Address, bytesToHex, hexToBytes } from '@ethereumjs/util' +import { Address, bytesToHex, createZeroAddress, hexToBytes } from '@ethereumjs/util' import { readFileSync, readdirSync } from 'fs' import * as mcl from 'mcl-wasm' import { assert, describe, it } from 'vitest' @@ -111,7 +111,7 @@ describe('EIP-2537 BLS precompile availability tests', () => { for (const address of precompiles) { const to = new Address(hexToBytes(address)) const result = await evm.runCall({ - caller: Address.zero(), + caller: createZeroAddress(), gasLimit: BigInt(0xffffffffff), to, value: BigInt(0), diff --git a/packages/evm/test/precompiles/hardfork.spec.ts b/packages/evm/test/precompiles/hardfork.spec.ts index 1b46c97f94..91f91853b1 100644 --- a/packages/evm/test/precompiles/hardfork.spec.ts +++ b/packages/evm/test/precompiles/hardfork.spec.ts @@ -1,5 +1,5 @@ import { Chain, Common, Hardfork } from '@ethereumjs/common' -import { Address, hexToBytes } from '@ethereumjs/util' +import { Address, createZeroAddress, hexToBytes } from '@ethereumjs/util' import { assert, describe, it } from 'vitest' import { createEVM, getActivePrecompiles } from '../../src/index.js' @@ -24,7 +24,7 @@ describe('Precompiles: hardfork availability', () => { common: commonByzantium, }) let result = await evm.runCall({ - caller: Address.zero(), + caller: createZeroAddress(), gasLimit: BigInt(0xffffffffff), to: ECPAIR_Address, value: BigInt(0), @@ -45,7 +45,7 @@ describe('Precompiles: hardfork availability', () => { common: commonPetersburg, }) result = await evm.runCall({ - caller: Address.zero(), + caller: createZeroAddress(), gasLimit: BigInt(0xffffffffff), to: ECPAIR_Address, value: BigInt(0), @@ -68,7 +68,7 @@ describe('Precompiles: hardfork availability', () => { }) result = await evm.runCall({ - caller: Address.zero(), + caller: createZeroAddress(), gasLimit: BigInt(0xffffffffff), to: ECPAIR_Address, value: BigInt(0), diff --git a/packages/evm/test/runCall.spec.ts b/packages/evm/test/runCall.spec.ts index 0e59c6633c..e9d310f944 100644 --- a/packages/evm/test/runCall.spec.ts +++ b/packages/evm/test/runCall.spec.ts @@ -6,6 +6,9 @@ import { bytesToBigInt, bytesToHex, concatBytes, + createAddressFromPrivateKey, + createAddressFromString, + createZeroAddress, hexToBytes, padToEven, unpadBytes, @@ -459,7 +462,7 @@ describe('RunCall tests', () => { // setup the call arguments const runCallArgs = { - to: Address.zero(), + to: createZeroAddress(), value: BigInt(-10), } @@ -480,12 +483,12 @@ describe('RunCall tests', () => { // runCall against a contract to reach `_reduceSenderBalance` const contractCode = hexToBytes('0x00') // 00: STOP - const contractAddress = Address.fromString('0x000000000000000000000000636F6E7472616374') + const contractAddress = createAddressFromString('0x000000000000000000000000636F6E7472616374') await evm.stateManager.putCode(contractAddress, contractCode) const senderKey = hexToBytes( '0xe331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109', ) - const sender = Address.fromPrivateKey(senderKey) + const sender = createAddressFromPrivateKey(senderKey) const runCallArgs = { gasLimit: BigInt(21000), @@ -615,7 +618,7 @@ describe('RunCall tests', () => { const evm = await createEVM({ common }) const contractCode = hexToBytes('0x600060405200') // PUSH 0 PUSH 40 MSTORE STOP - const contractAddress = Address.fromString('0x000000000000000000000000636F6E7472616374') + const contractAddress = createAddressFromString('0x000000000000000000000000636F6E7472616374') await evm.stateManager.putCode(contractAddress, contractCode) const runCallArgs = { @@ -708,7 +711,7 @@ describe('RunCall tests', () => { * PUSH2 0x1a90 // Note: this is the gas available in the new call(code) frame, this value does not matter * CALLCODE/CALL */ - const callCodeAddress = Address.fromString('0x000000000000000000000000000000000000aaaa') + const callCodeAddress = createAddressFromString('0x000000000000000000000000000000000000aaaa') const callCode = hexToBytes(`0x6000600060006000600161AACC611a90${opcode}`) const gasLimit = gas.toString(16).padStart(4, '0') @@ -726,7 +729,7 @@ describe('RunCall tests', () => { * PUSH1 0x00 * SSTORE */ - const callerAddress = Address.fromString('0x000000000000000000000000000000000000aaab') + const callerAddress = createAddressFromString('0x000000000000000000000000000000000000aaab') const callerCode = hexToBytes(`0x60008080808061AAAA61${gasLimit}f1600055`) await evm.stateManager.putAccount(callCodeAddress, new Account()) diff --git a/packages/evm/test/runCode.spec.ts b/packages/evm/test/runCode.spec.ts index 00eafbb573..821626a339 100644 --- a/packages/evm/test/runCode.spec.ts +++ b/packages/evm/test/runCode.spec.ts @@ -1,4 +1,4 @@ -import { Account, Address, hexToBytes } from '@ethereumjs/util' +import { Account, createAddressFromString, hexToBytes } from '@ethereumjs/util' import { assert, describe, it } from 'vitest' import { createEVM } from '../src/index.js' @@ -82,7 +82,7 @@ describe('VM.runCode: interpreter', () => { // does not exist, then if SSTORE/SLOAD is used, the runCode will immediately fail because StateManager now throws // TODO: is this behavior which we should fix? (Either in StateManager OR in runCode where we load the account first, // then re-put the account after (if account === undefined put empty account, such that the account exists)) - const address = Address.fromString(`0x${'00'.repeat(20)}`) + const address = createAddressFromString(`0x${'00'.repeat(20)}`) await evm.stateManager.putAccount(address, new Account()) evm.stateManager.putStorage = (..._args) => { throw new Error('Test') diff --git a/packages/evm/test/transientStorage.spec.ts b/packages/evm/test/transientStorage.spec.ts index 94a29cd8fa..acf90275c1 100644 --- a/packages/evm/test/transientStorage.spec.ts +++ b/packages/evm/test/transientStorage.spec.ts @@ -1,4 +1,4 @@ -import { Address } from '@ethereumjs/util' +import { createAddressFromString } from '@ethereumjs/util' import { assert, describe, it } from 'vitest' import { TransientStorage } from '../src/transientStorage.js' @@ -7,7 +7,7 @@ describe('Transient Storage', () => { it('should set and get storage', () => { const transientStorage = new TransientStorage() - const address = Address.fromString('0xff00000000000000000000000000000000000002') + const address = createAddressFromString('0xff00000000000000000000000000000000000002') const key = new Uint8Array(32).fill(0xff) const value = new Uint8Array(32).fill(0x99) @@ -19,7 +19,7 @@ describe('Transient Storage', () => { it('should return bytes32(0) if there is no key set', () => { const transientStorage = new TransientStorage() - const address = Address.fromString('0xff00000000000000000000000000000000000002') + const address = createAddressFromString('0xff00000000000000000000000000000000000002') const key = new Uint8Array(32).fill(0xff) const value = new Uint8Array(32).fill(0x11) @@ -36,7 +36,7 @@ describe('Transient Storage', () => { it('should revert', () => { const transientStorage = new TransientStorage() - const address = Address.fromString('0xff00000000000000000000000000000000000002') + const address = createAddressFromString('0xff00000000000000000000000000000000000002') const key = new Uint8Array(32).fill(0xff) const value = new Uint8Array(32).fill(0x99) @@ -58,7 +58,7 @@ describe('Transient Storage', () => { it('should commit', () => { const transientStorage = new TransientStorage() - const address = Address.fromString('0xff00000000000000000000000000000000000002') + const address = createAddressFromString('0xff00000000000000000000000000000000000002') const key = new Uint8Array(32).fill(0xff) const value = new Uint8Array(32).fill(0x99) @@ -74,7 +74,7 @@ describe('Transient Storage', () => { it('should fail with wrong size key/value', () => { const transientStorage = new TransientStorage() - const address = Address.fromString('0xff00000000000000000000000000000000000002') + const address = createAddressFromString('0xff00000000000000000000000000000000000002') assert.throws(() => { transientStorage.put(address, new Uint8Array(10), new Uint8Array(1)) @@ -88,14 +88,14 @@ describe('Transient Storage', () => { it('keys are stringified', () => { const transientStorage = new TransientStorage() - const address = Address.fromString('0xff00000000000000000000000000000000000002') + const address = createAddressFromString('0xff00000000000000000000000000000000000002') const key = new Uint8Array(32).fill(0xff) const value = new Uint8Array(32).fill(0x99) transientStorage.put(address, key, value) assert.deepEqual( transientStorage.get( - Address.fromString('0xff00000000000000000000000000000000000002'), + createAddressFromString('0xff00000000000000000000000000000000000002'), new Uint8Array(32).fill(0xff), ), value, @@ -105,7 +105,7 @@ describe('Transient Storage', () => { it('revert applies changes in correct order', () => { const transientStorage = new TransientStorage() - const address = Address.fromString('0xff00000000000000000000000000000000000002') + const address = createAddressFromString('0xff00000000000000000000000000000000000002') const key = new Uint8Array(32).fill(0xff) const value1 = new Uint8Array(32).fill(0x01) const value2 = new Uint8Array(32).fill(0x02) @@ -123,7 +123,7 @@ describe('Transient Storage', () => { it('nested reverts', () => { const transientStorage = new TransientStorage() - const address = Address.fromString('0xff00000000000000000000000000000000000002') + const address = createAddressFromString('0xff00000000000000000000000000000000000002') const key = new Uint8Array(32).fill(0xff) const value0 = new Uint8Array(32).fill(0x00) const value1 = new Uint8Array(32).fill(0x01) @@ -153,7 +153,7 @@ describe('Transient Storage', () => { it('commit batches changes into next revert', () => { const transientStorage = new TransientStorage() - const address = Address.fromString('0xff00000000000000000000000000000000000002') + const address = createAddressFromString('0xff00000000000000000000000000000000000002') const key = new Uint8Array(32).fill(0xff) const value1 = new Uint8Array(32).fill(0x01) const value2 = new Uint8Array(32).fill(0x02) diff --git a/packages/statemanager/examples/rpcStateManager.ts b/packages/statemanager/examples/rpcStateManager.ts index f711f2804b..24a2a2217c 100644 --- a/packages/statemanager/examples/rpcStateManager.ts +++ b/packages/statemanager/examples/rpcStateManager.ts @@ -1,11 +1,11 @@ import { RPCStateManager } from '@ethereumjs/statemanager' -import { Address } from '@ethereumjs/util' +import { createAddressFromString } from '@ethereumjs/util' const main = async () => { try { const provider = 'https://path.to.my.provider.com' const stateManager = new RPCStateManager({ provider, blockTag: 500000n }) - const vitalikDotEth = Address.fromString('0xd8da6bf26964af9d7eed9e03e53415d37aa96045') + const vitalikDotEth = createAddressFromString('0xd8da6bf26964af9d7eed9e03e53415d37aa96045') const account = await stateManager.getAccount(vitalikDotEth) console.log('Vitalik has a current ETH balance of ', account?.balance) } catch (e) { diff --git a/packages/statemanager/examples/simple.ts b/packages/statemanager/examples/simple.ts index 308897ce95..5686606ba8 100644 --- a/packages/statemanager/examples/simple.ts +++ b/packages/statemanager/examples/simple.ts @@ -1,10 +1,10 @@ -import { Account, Address, randomBytes } from '@ethereumjs/util' +import { Account, createAddressFromPrivateKey, randomBytes } from '@ethereumjs/util' import { SimpleStateManager } from '../src/index.js' const main = async () => { const sm = new SimpleStateManager() - const address = Address.fromPrivateKey(randomBytes(32)) + const address = createAddressFromPrivateKey(randomBytes(32)) const account = new Account(0n, 0xfffffn) await sm.putAccount(address, account) console.log(await sm.getAccount(address)) diff --git a/packages/statemanager/src/stateManager.ts b/packages/statemanager/src/stateManager.ts index 50aad47542..79c75a34f7 100644 --- a/packages/statemanager/src/stateManager.ts +++ b/packages/statemanager/src/stateManager.ts @@ -3,7 +3,6 @@ import { RLP } from '@ethereumjs/rlp' import { Trie, createTrieFromProof, verifyTrieProof } from '@ethereumjs/trie' import { Account, - Address, KECCAK256_NULL, KECCAK256_NULL_S, KECCAK256_RLP, @@ -14,6 +13,7 @@ import { concatBytes, createAccount, createAccountFromRLP, + createAddressFromString, equalsBytes, hexToBytes, setLengthLeft, @@ -43,7 +43,7 @@ import type { StorageDump, StorageRange, } from '@ethereumjs/common' -import type { DB, PrefixedHexString } from '@ethereumjs/util' +import type { Address, DB, PrefixedHexString } from '@ethereumjs/util' import type { Debugger } from 'debug' /** @@ -562,7 +562,7 @@ export class DefaultStateManager implements StateManagerInterface { if (!this._codeCacheSettings.deactivate) { const items = this._codeCache!.flush() for (const item of items) { - const addr = Address.fromString(`0x${item[0]}`) + const addr = createAddressFromString(`0x${item[0]}`) const code = item[1].code if (code === undefined) { @@ -584,7 +584,7 @@ export class DefaultStateManager implements StateManagerInterface { if (!this._storageCacheSettings.deactivate) { const items = this._storageCache!.flush() for (const item of items) { - const address = Address.fromString(`0x${item[0]}`) + const address = createAddressFromString(`0x${item[0]}`) const keyHex = item[1] const keyBytes = unprefixedHexToBytes(keyHex) const value = item[2] @@ -687,7 +687,7 @@ export class DefaultStateManager implements StateManagerInterface { { useKeyHashing: true }, )) const sm = new DefaultStateManager({ ...opts, trie }) - const address = Address.fromString(proof[0].address) + const address = createAddressFromString(proof[0].address) await sm.addStorageProof(proof[0].storageProof, proof[0].storageHash, address, safe) for (let i = 1; i < proof.length; i++) { const proofItem = proof[i] @@ -740,7 +740,7 @@ export class DefaultStateManager implements StateManagerInterface { await this.addStorageProof( proof[i].storageProof, proof[i].storageHash, - Address.fromString(proof[i].address), + createAddressFromString(proof[i].address), safe, ) } @@ -940,7 +940,7 @@ export class DefaultStateManager implements StateManagerInterface { } const addresses = Object.keys(initState) for (const address of addresses) { - const addr = Address.fromString(address) + const addr = createAddressFromString(address) const state = initState[address] if (!Array.isArray(state)) { // Prior format: address -> balance diff --git a/packages/statemanager/test/proofStateManager.spec.ts b/packages/statemanager/test/proofStateManager.spec.ts index 41c02a7333..3a1e2bef2e 100644 --- a/packages/statemanager/test/proofStateManager.spec.ts +++ b/packages/statemanager/test/proofStateManager.spec.ts @@ -4,6 +4,9 @@ import { Address, bytesToHex, bytesToUnprefixedHex, + createAddressFromPrivateKey, + createAddressFromString, + createZeroAddress, equalsBytes, hexToBytes, randomBytes, @@ -23,7 +26,7 @@ import type { PrefixedHexString } from '@ethereumjs/util' describe('ProofStateManager', () => { it(`should return quantity-encoded RPC representation`, async () => { - const address = Address.zero() + const address = createZeroAddress() const key = zeros(32) const stateManager = new DefaultStateManager() @@ -33,7 +36,7 @@ describe('ProofStateManager', () => { }) it(`should correctly return the right storage root / account root`, async () => { - const address = Address.zero() + const address = createZeroAddress() const key = zeros(32) const stateManager = new DefaultStateManager() @@ -47,7 +50,7 @@ describe('ProofStateManager', () => { }) it(`should return quantity-encoded RPC representation for existing accounts`, async () => { - const address = Address.zero() + const address = createZeroAddress() const key = zeros(32) const stateManager = new DefaultStateManager() @@ -75,7 +78,7 @@ describe('ProofStateManager', () => { }) it(`should get and verify EIP 1178 proofs`, async () => { - const address = Address.zero() + const address = createZeroAddress() const key = zeros(32) const value = hexToBytes('0x0000aabb00') const code = hexToBytes('0x6000') @@ -97,7 +100,9 @@ describe('ProofStateManager', () => { const proof = await stateManager.getProof(address, [key]) assert.ok(await stateManager.verifyProof(proof)) - const nonExistenceProof = await stateManager.getProof(Address.fromPrivateKey(randomBytes(32))) + const nonExistenceProof = await stateManager.getProof( + createAddressFromPrivateKey(randomBytes(32)), + ) assert.equal( await stateManager.verifyProof(nonExistenceProof), true, @@ -110,7 +115,7 @@ describe('ProofStateManager', () => { // Block: 11098094 (hash 0x1d9ea6981b8093a2b63f22f74426ceb6ba1acae3fddd7831442bbeba3fa4f146) // Account: 0xc626553e7c821d0f8308c28d56c60e3c15f8d55a // Storage slots: empty list - const address = Address.fromString('0xc626553e7c821d0f8308c28d56c60e3c15f8d55a') + const address = createAddressFromString('0xc626553e7c821d0f8308c28d56c60e3c15f8d55a') const trie = await createTrie({ useKeyHashing: true }) const stateManager = new DefaultStateManager({ trie }) // Dump all the account proof data in the DB @@ -134,7 +139,7 @@ describe('ProofStateManager', () => { // Block: 11098094 (hash 0x1d9ea6981b8093a2b63f22f74426ceb6ba1acae3fddd7831442bbeba3fa4f146) // Account: 0x68268f12253f69f66b188c95b8106b2f847859fc (this account does not exist) // Storage slots: empty list - const address = Address.fromString('0x68268f12253f69f66b188c95b8106b2f847859fc') + const address = createAddressFromString('0x68268f12253f69f66b188c95b8106b2f847859fc') const trie = new Trie({ useKeyHashing: true }) const stateManager = new DefaultStateManager({ trie }) // Dump all the account proof data in the DB @@ -158,7 +163,7 @@ describe('ProofStateManager', () => { // eth.getProof("0x2D80502854FC7304c3E3457084DE549f5016B73f", ["0x1e8bf26b05059b66f11b6e0c5b9fe941f81181d6cc9f2af65ccee86e95cea1ca", "0x1e8bf26b05059b66f11b6e0c5b9fe941f81181d6cc9f2af65ccee86e95cea1cb"], 11098094) // Note: the first slot has a value, but the second slot is empty // Note: block hash 0x1d9ea6981b8093a2b63f22f74426ceb6ba1acae3fddd7831442bbeba3fa4f146 - const address = Address.fromString('0x2D80502854FC7304c3E3457084DE549f5016B73f') + const address = createAddressFromString('0x2D80502854FC7304c3E3457084DE549f5016B73f') const trie = new Trie({ useKeyHashing: true }) const stateManager = new DefaultStateManager({ trie }) // Dump all the account proof data in the DB @@ -196,7 +201,7 @@ describe('ProofStateManager', () => { // eth.getProof("0x2D80502854FC7304c3E3457084DE549f5016B73f", ["0x1e8bf26b05059b66f11b6e0c5b9fe941f81181d6cc9f2af65ccee86e95cea1ca", "0x1e8bf26b05059b66f11b6e0c5b9fe941f81181d6cc9f2af65ccee86e95cea1cb"], 11098094) // Note: the first slot has a value, but the second slot is empty // Note: block hash 0x1d9ea6981b8093a2b63f22f74426ceb6ba1acae3fddd7831442bbeba3fa4f146 - const address = Address.fromString('0x2D80502854FC7304c3E3457084DE549f5016B73f') + const address = createAddressFromString('0x2D80502854FC7304c3E3457084DE549f5016B73f') const trie = new Trie({ useKeyHashing: true }) const stateManager = new DefaultStateManager({ trie }) // Dump all the account proof data in the DB @@ -262,7 +267,7 @@ describe('ProofStateManager', () => { // eth.getProof("0x2D80502854FC7304c3E3457084DE549f5016B73f", ["0x1e8bf26b05059b66f11b6e0c5b9fe941f81181d6cc9f2af65ccee86e95cea1ca", "0x1e8bf26b05059b66f11b6e0c5b9fe941f81181d6cc9f2af65ccee86e95cea1cb"], 11098094) // Note: the first slot has a value, but the second slot is empty // Note: block hash 0x1d9ea6981b8093a2b63f22f74426ceb6ba1acae3fddd7831442bbeba3fa4f146 - const address = Address.fromString('0x68268f12253f69f66b188c95b8106b2f847859fc') + const address = createAddressFromString('0x68268f12253f69f66b188c95b8106b2f847859fc') const trie = new Trie({ useKeyHashing: true }) const stateManager = new DefaultStateManager({ trie }) // Dump all the account proof data in the DB diff --git a/packages/statemanager/test/rpcStateManager.spec.ts b/packages/statemanager/test/rpcStateManager.spec.ts index d4a4f1f03f..354356bf6c 100644 --- a/packages/statemanager/test/rpcStateManager.spec.ts +++ b/packages/statemanager/test/rpcStateManager.spec.ts @@ -8,6 +8,7 @@ import { bytesToHex, bytesToUnprefixedHex, createAccountFromRLP, + createAddressFromString, equalsBytes, hexToBytes, setLengthLeft, @@ -78,7 +79,7 @@ describe('RPC State Manager initialization tests', async () => { describe('RPC State Manager API tests', () => { it('should work', async () => { const state = new RPCStateManager({ provider, blockTag: 1n }) - const vitalikDotEth = Address.fromString('0xd8da6bf26964af9d7eed9e03e53415d37aa96045') + const vitalikDotEth = createAddressFromString('0xd8da6bf26964af9d7eed9e03e53415d37aa96045') const account = await state.getAccount(vitalikDotEth) assert.ok(account!.nonce > 0n, 'Vitalik.eth returned a valid nonce') @@ -91,13 +92,15 @@ describe('RPC State Manager API tests', () => { assert.ok(retrievedVitalikAccount.nonce > 0n, 'Vitalik.eth is stored in cache') const doesThisAccountExist = await state.accountExists( - Address.fromString('0xccAfdD642118E5536024675e776d32413728DD07'), + createAddressFromString('0xccAfdD642118E5536024675e776d32413728DD07'), ) assert.ok(!doesThisAccountExist, 'getAccount returns undefined for non-existent account') assert.ok(state.getAccount(vitalikDotEth) !== undefined, 'vitalik.eth does exist') - const UNIerc20ContractAddress = Address.fromString('0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984') + const UNIerc20ContractAddress = createAddressFromString( + '0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984', + ) const UNIContractCode = await state.getCode(UNIerc20ContractAddress) assert.ok(UNIContractCode.length > 0, 'was able to retrieve UNI contract code') @@ -160,7 +163,7 @@ describe('RPC State Manager API tests', () => { ) try { - await state.getAccount(Address.fromString('0x9Cef824A8f4b3Dc6B7389933E52e47F010488Fc8')) + await state.getAccount(createAddressFromString('0x9Cef824A8f4b3Dc6B7389933E52e47F010488Fc8')) } catch (err) { assert.ok(true, 'calls getAccountFromProvider for non-cached account') } @@ -238,7 +241,7 @@ describe('runTx custom transaction test', () => { const state = new RPCStateManager({ provider, blockTag: 1n }) const vm = await VM.create({ common, stateManager: state }) // TODO fix the type DefaultStateManager back to StateManagerInterface in VM - const vitalikDotEth = Address.fromString('0xd8da6bf26964af9d7eed9e03e53415d37aa96045') + const vitalikDotEth = createAddressFromString('0xd8da6bf26964af9d7eed9e03e53415d37aa96045') const privateKey = hexToBytes( '0xe331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109', ) @@ -323,7 +326,7 @@ describe('blockchain', () => const code = '0x600143034060005260206000F3' const contractAddress = new Address(hexToBytes('0x00000000000000000000000000000000000000ff')) - const caller = Address.fromString('0xd8da6bf26964af9d7eed9e03e53415d37aa96045') + const caller = createAddressFromString('0xd8da6bf26964af9d7eed9e03e53415d37aa96045') await evm.stateManager.setStateRoot( hexToBytes('0xf8506f559699a58a4724df4fcf2ad4fd242d20324db541823f128f5974feb6c7'), ) diff --git a/packages/statemanager/test/stateManager.code.spec.ts b/packages/statemanager/test/stateManager.code.spec.ts index db47c19a03..ee7dc802ac 100644 --- a/packages/statemanager/test/stateManager.code.spec.ts +++ b/packages/statemanager/test/stateManager.code.spec.ts @@ -1,4 +1,10 @@ -import { Address, createAccount, equalsBytes, hexToBytes } from '@ethereumjs/util' +import { + Address, + createAccount, + createZeroAddress, + equalsBytes, + hexToBytes, +} from '@ethereumjs/util' import { assert, describe, it } from 'vitest' import { DefaultStateManager } from '../src/index.js' @@ -18,7 +24,7 @@ describe('StateManager -> Code', () => { This test is mostly an example of why a code prefix is necessary I an address, we put two storage values. The preimage of the (storage trie) root hash is known This preimage is used as codeHash - + NOTE: Currently, the only problem which this code prefix fixes, is putting 0x80 as contract code -> This hashes to the empty trie node hash (0x80 = RLP([])), so keccak256(0x80) = empty trie node hash -> Therefore, each empty state trie now points to 0x80, which is not a valid trie node, which crashes @ethereumjs/trie @@ -151,7 +157,7 @@ describe('StateManager -> Code', () => { it('putCode with empty code on existing address should correctly propagate', async () => { const stateManager = new DefaultStateManager() - const address = Address.zero() + const address = createZeroAddress() await stateManager.putCode(address, new Uint8Array([1])) await stateManager.putCode(address, new Uint8Array()) const account = await stateManager.getAccount(address) diff --git a/packages/statemanager/test/stateManager.spec.ts b/packages/statemanager/test/stateManager.spec.ts index 585fa1654e..1744973e3b 100644 --- a/packages/statemanager/test/stateManager.spec.ts +++ b/packages/statemanager/test/stateManager.spec.ts @@ -1,9 +1,11 @@ import { Trie, createTrie, createTrieFromProof } from '@ethereumjs/trie' import { Account, - Address, KECCAK256_RLP, bigIntToBytes, + createAddressFromPrivateKey, + createAddressFromString, + createZeroAddress, equalsBytes, hexToBytes, intToBytes, @@ -44,7 +46,7 @@ describe('StateManager -> General', () => { it(`should clear contract storage`, async () => { const sm = new DefaultStateManager() - const contractAddress = Address.fromString('0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984') + const contractAddress = createAddressFromString('0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984') const contractCode = Uint8Array.from([0, 1, 2, 3]) const storageKey = setLengthLeft(bigIntToBytes(2n), 32) const storedData = utf8ToBytes('abcd') @@ -142,9 +144,9 @@ describe('StateManager -> General', () => { const address2Str = '0x2'.padEnd(42, '0') const address3Str = '0x3'.padEnd(42, '0') - const address1 = Address.fromString(address1Str) - const address2 = Address.fromString(address2Str) - const address3 = Address.fromString(address3Str) + const address1 = createAddressFromString(address1Str) + const address2 = createAddressFromString(address2Str) + const address3 = createAddressFromString(address3Str) const key1 = setLengthLeft(new Uint8Array([1]), 32) const key2 = setLengthLeft(new Uint8Array([2]), 32) @@ -184,7 +186,7 @@ describe('StateManager -> General', () => { const stateManager = new DefaultStateManager() for (const [addressStr, entry] of Object.entries(stateSetup)) { - const address = Address.fromString(addressStr) + const address = createAddressFromString(addressStr) const account = new Account(entry.nonce, entry.balance) await stateManager.putAccount(address, account) await stateManager.putCode(address, entry.code) @@ -267,8 +269,8 @@ describe('StateManager -> General', () => { await postVerify(newPartialStateManager2) const zeroAddressNonce = BigInt(100) - await stateManager.putAccount(Address.zero(), new Account(zeroAddressNonce)) - const zeroAddressProof = await stateManager.getProof(Address.zero()) + await stateManager.putAccount(createZeroAddress(), new Account(zeroAddressNonce)) + const zeroAddressProof = await stateManager.getProof(createZeroAddress()) try { await DefaultStateManager.fromProof([proof1, zeroAddressProof], true) @@ -279,11 +281,11 @@ describe('StateManager -> General', () => { await newPartialStateManager2.addProofData(zeroAddressProof) - let zeroAccount = await newPartialStateManager2.getAccount(Address.zero()) + let zeroAccount = await newPartialStateManager2.getAccount(createZeroAddress()) assert.ok(zeroAccount === undefined) await newPartialStateManager2.setStateRoot(await stateManager.getStateRoot()) - zeroAccount = await newPartialStateManager2.getAccount(Address.zero()) + zeroAccount = await newPartialStateManager2.getAccount(createZeroAddress()) assert.ok(zeroAccount!.nonce === zeroAddressNonce) }) it.skipIf(isBrowser() === true)( @@ -293,8 +295,8 @@ describe('StateManager -> General', () => { const sm = new DefaultStateManager({ trie }) const pk = hexToBytes('0x9f12aab647a25a81f821a5a0beec3330cd057b2346af4fb09d7a807e896701ea') const pk2 = hexToBytes('0x8724f27e2ce3714af01af3220478849db68a03c0f84edf1721d73d9a6139ad1c') - const address = Address.fromPrivateKey(pk) - const address2 = Address.fromPrivateKey(pk2) + const address = createAddressFromPrivateKey(pk) + const address2 = createAddressFromPrivateKey(pk2) const account = new Account() const account2 = new Account(undefined, 100n) await sm.putAccount(address, account) diff --git a/packages/statemanager/test/stateManager.storage.spec.ts b/packages/statemanager/test/stateManager.storage.spec.ts index 40d8113348..ed65a30f8f 100644 --- a/packages/statemanager/test/stateManager.storage.spec.ts +++ b/packages/statemanager/test/stateManager.storage.spec.ts @@ -2,6 +2,7 @@ import { Address, bytesToHex, concatBytes, + createZeroAddress, equalsBytes, hexToBytes, unpadBytes, @@ -72,7 +73,7 @@ describe('StateManager -> Storage', () => { it(`should throw on storage values larger than 32 bytes`, async () => { const stateManager = new DefaultStateManager({ prefixStorageTrieKeys, storageCacheOpts }) - const address = Address.zero() + const address = createZeroAddress() const account = createAccountWithDefaults() await stateManager.putAccount(address, account) @@ -88,7 +89,7 @@ describe('StateManager -> Storage', () => { it(`should strip zeros of storage values`, async () => { const stateManager = new DefaultStateManager({ prefixStorageTrieKeys, storageCacheOpts }) - const address = Address.zero() + const address = createZeroAddress() const account = createAccountWithDefaults() await stateManager.putAccount(address, account) @@ -109,7 +110,7 @@ describe('StateManager -> Storage', () => { }) it(`should delete storage values which only consist of zero bytes`, async () => { - const address = Address.zero() + const address = createZeroAddress() const key = zeros(32) const startValue = hexToBytes('0x01') @@ -138,7 +139,7 @@ describe('StateManager -> Storage', () => { it(`should not strip trailing zeros`, async () => { const stateManager = new DefaultStateManager({ prefixStorageTrieKeys, storageCacheOpts }) - const address = Address.zero() + const address = createZeroAddress() const account = createAccountWithDefaults() await stateManager.putAccount(address, account) diff --git a/packages/statemanager/test/statelessVerkleStateManager.spec.ts b/packages/statemanager/test/statelessVerkleStateManager.spec.ts index da1588b4e1..8f8f74df82 100644 --- a/packages/statemanager/test/statelessVerkleStateManager.spec.ts +++ b/packages/statemanager/test/statelessVerkleStateManager.spec.ts @@ -7,6 +7,7 @@ import { bytesToBigInt, bytesToHex, createAccount, + createAddressFromString, getVerkleKey, getVerkleStem, hexToBytes, @@ -54,7 +55,7 @@ describe('StatelessVerkleStateManager: Kaustinen Verkle Block', () => { stateManager.initVerkleExecutionWitness(block.header.number, block.executionWitness) const account = await stateManager.getAccount( - Address.fromString('0x6177843db3138ae69679a54b95cf345ed759450d'), + createAddressFromString('0x6177843db3138ae69679a54b95cf345ed759450d'), ) assert.equal(account!.balance, 288610978528114322n, 'should have correct balance') @@ -117,7 +118,7 @@ describe('StatelessVerkleStateManager: Kaustinen Verkle Block', () => { const stateManager = new StatelessVerkleStateManager({ common, verkleCrypto }) stateManager.initVerkleExecutionWitness(block.header.number, block.executionWitness) - const address = Address.fromString('0x6177843db3138ae69679a54b95cf345ed759450d') + const address = createAddressFromString('0x6177843db3138ae69679a54b95cf345ed759450d') const stem = getVerkleStem(stateManager.verkleCrypto, address, 0n) const balanceKey = getVerkleKey(stem, VerkleLeafType.Balance) @@ -175,7 +176,7 @@ describe('StatelessVerkleStateManager: Kaustinen Verkle Block', () => { const stateManager = new StatelessVerkleStateManager({ common, verkleCrypto }) stateManager.initVerkleExecutionWitness(block.header.number, block.executionWitness) - const contractAddress = Address.fromString('0x4242424242424242424242424242424242424242') + const contractAddress = createAddressFromString('0x4242424242424242424242424242424242424242') const storageKey = '0x0000000000000000000000000000000000000000000000000000000000000022' const storageValue = '0xf5a5fd42d16a20302798ef6ed309979b43003d2320d9f0e8ea9831a92759fb4b' await stateManager.putStorage(contractAddress, hexToBytes(storageKey), hexToBytes(storageValue)) diff --git a/packages/tx/examples/custom-chain-tx.ts b/packages/tx/examples/custom-chain-tx.ts index 8d111ff918..e982712b79 100644 --- a/packages/tx/examples/custom-chain-tx.ts +++ b/packages/tx/examples/custom-chain-tx.ts @@ -1,6 +1,6 @@ import { createCustomCommon } from '@ethereumjs/common' import { createLegacyTx } from '@ethereumjs/tx' -import { Address, hexToBytes } from '@ethereumjs/util' +import { createAddressFromPrivateKey, hexToBytes } from '@ethereumjs/util' // In this example we create a transaction for a custom network. @@ -35,7 +35,7 @@ const tx = createLegacyTx( const privateKey = hexToBytes('0xe331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109') const signedTx = tx.sign(privateKey) -const address = Address.fromPrivateKey(privateKey) +const address = createAddressFromPrivateKey(privateKey) if (signedTx.isValid() && signedTx.getSenderAddress().equals(address)) { console.log('Valid signature') diff --git a/packages/tx/examples/l2tx.ts b/packages/tx/examples/l2tx.ts index 15977fb777..05bcbbd0d5 100644 --- a/packages/tx/examples/l2tx.ts +++ b/packages/tx/examples/l2tx.ts @@ -1,9 +1,9 @@ import { CustomChain, createCustomCommon } from '@ethereumjs/common' import { createLegacyTx } from '@ethereumjs/tx' -import { Address, bytesToHex, hexToBytes } from '@ethereumjs/util' +import { bytesToHex, createAddressFromString, hexToBytes } from '@ethereumjs/util' const pk = hexToBytes('0x076247989df60a82f6e86e58104368676096f84e60972282ee00d4673a2bc9b9') -const to = Address.fromString('0x256e8f0ba532ad83a0debde7501669511a41a1f3') +const to = createAddressFromString('0x256e8f0ba532ad83a0debde7501669511a41a1f3') const common = createCustomCommon(CustomChain.xDaiChain) const txData = { diff --git a/packages/tx/test/eip3860.spec.ts b/packages/tx/test/eip3860.spec.ts index dfcc728476..c008d9c3bc 100644 --- a/packages/tx/test/eip3860.spec.ts +++ b/packages/tx/test/eip3860.spec.ts @@ -1,5 +1,5 @@ import { Chain, Common, Hardfork } from '@ethereumjs/common' -import { Address } from '@ethereumjs/util' +import { createZeroAddress } from '@ethereumjs/util' import { assert, describe, it } from 'vitest' import { TransactionType, createTxFromTxData, paramsTx } from '../src/index.js' @@ -18,7 +18,7 @@ const txTypes = [ TransactionType.FeeMarketEIP1559, //TransactionType.BlobEIP4844, // Explicitly commented out: BlobEIP4844 txs cannot create contracts ] -const addressZero = Address.zero() +const addressZero = createZeroAddress() describe('[EIP3860 tests]', () => { it(`Should instantiate create txs with MAX_INITCODE_SIZE`, () => { diff --git a/packages/tx/test/eip4844.spec.ts b/packages/tx/test/eip4844.spec.ts index d7e8c4d363..9db5d7c447 100644 --- a/packages/tx/test/eip4844.spec.ts +++ b/packages/tx/test/eip4844.spec.ts @@ -1,11 +1,11 @@ import { Hardfork, createCommonFromGethGenesis } from '@ethereumjs/common' import { - Address, blobsToCommitments, blobsToProofs, bytesToHex, commitmentsToVersionedHashes, concatBytes, + createZeroAddress, ecsign, equalsBytes, getBlobs, @@ -46,7 +46,7 @@ describe('EIP4844 addSignature tests', () => { const privateKey = pk const tx = create4844BlobTx( { - to: Address.zero(), + to: createZeroAddress(), blobVersionedHashes: [concatBytes(new Uint8Array([1]), randomBytes(31))], }, { common }, @@ -61,7 +61,7 @@ describe('EIP4844 addSignature tests', () => { const privKey = pk const tx = create4844BlobTx( { - to: Address.zero(), + to: createZeroAddress(), blobVersionedHashes: [concatBytes(new Uint8Array([1]), randomBytes(31))], }, { common }, @@ -80,7 +80,7 @@ describe('EIP4844 addSignature tests', () => { const privKey = pk const tx = create4844BlobTx( { - to: Address.zero(), + to: createZeroAddress(), blobVersionedHashes: [concatBytes(new Uint8Array([1]), randomBytes(31))], }, { common }, @@ -111,7 +111,7 @@ describe('EIP4844 constructor tests - valid scenarios', () => { type: 0x03, blobVersionedHashes: [concatBytes(new Uint8Array([1]), randomBytes(31))], maxFeePerBlobGas: 1n, - to: Address.zero(), + to: createZeroAddress(), } const tx = create4844BlobTx(txData, { common }) assert.equal(tx.type, 3, 'successfully instantiated a blob transaction from txData') @@ -220,7 +220,7 @@ describe('EIP4844 constructor tests - invalid scenarios', () => { const baseTxData = { type: 0x03, maxFeePerBlobGas: 1n, - to: Address.zero(), + to: createZeroAddress(), } const shortVersionHash = { blobVersionedHashes: [concatBytes(new Uint8Array([3]), randomBytes(3))], @@ -560,7 +560,7 @@ describe('hash() and signature verification', () => { storageKeys: ['0x0000000000000000000000000000000000000000000000000000000000000000'], }, ], - to: Address.zero(), + to: createZeroAddress(), }, { common }, ) @@ -593,7 +593,7 @@ it('getEffectivePriorityFee()', async () => { { maxFeePerGas: 10, maxPriorityFeePerGas: 8, - to: Address.zero(), + to: createZeroAddress(), blobVersionedHashes: [concatBytes(new Uint8Array([1]), randomBytes(31))], }, { common }, diff --git a/packages/tx/test/eip7702.spec.ts b/packages/tx/test/eip7702.spec.ts index 47222ce5c4..9ef52a6a19 100644 --- a/packages/tx/test/eip7702.spec.ts +++ b/packages/tx/test/eip7702.spec.ts @@ -1,5 +1,5 @@ import { Chain, Common, Hardfork } from '@ethereumjs/common' -import { Address, hexToBytes, privateToAddress } from '@ethereumjs/util' +import { createAddressFromPrivateKey, createZeroAddress, hexToBytes } from '@ethereumjs/util' import { assert, describe, it } from 'vitest' import { create7702EOACodeTx } from '../src/index.js' @@ -8,8 +8,8 @@ import type { PrefixedHexString } from '@ethereumjs/util' const common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.Cancun, eips: [7702] }) -const pkey = hexToBytes('0x' + '20'.repeat(32)) -const addr = new Address(privateToAddress(pkey)) +const pkey = hexToBytes(`0x${'20'.repeat(32)}`) +const addr = createAddressFromPrivateKey(pkey) const ones32 = `0x${'01'.repeat(32)}` as PrefixedHexString @@ -24,7 +24,7 @@ describe('[EOACodeEIP7702Transaction]', () => { authorizationList: [], chainId: 1, gasLimit: 100000, - to: Address.zero(), + to: createZeroAddress(), data: new Uint8Array(1), }, { common }, diff --git a/packages/util/examples/address.ts b/packages/util/examples/address.ts index 86362e4d44..853004f109 100644 --- a/packages/util/examples/address.ts +++ b/packages/util/examples/address.ts @@ -1,4 +1,4 @@ -import { Address } from '@ethereumjs/util' +import { createAddressFromString } from '@ethereumjs/util' -const address = Address.fromString('0x2f015c60e0be116b1f0cd534704db9c92118fb6a') +const address = createAddressFromString('0x2f015c60e0be116b1f0cd534704db9c92118fb6a') console.log(`Ethereum address ${address.toString()} created`) diff --git a/packages/util/examples/browser.html b/packages/util/examples/browser.html index 6d8fa69162..1f7436a9db 100644 --- a/packages/util/examples/browser.html +++ b/packages/util/examples/browser.html @@ -4,12 +4,12 @@ EthereumJS Browser Examples @@ -38,4 +38,4 @@

Interactive CLI

- \ No newline at end of file + diff --git a/packages/util/src/address.ts b/packages/util/src/address.ts index 2cb37d498e..795052e436 100644 --- a/packages/util/src/address.ts +++ b/packages/util/src/address.ts @@ -11,6 +11,7 @@ import { bytesToHex, equalsBytes, hexToBytes, + setLengthLeft, zeros, } from './bytes.js' import { BIGINT_0 } from './constants.js' @@ -30,76 +31,6 @@ export class Address { this.bytes = bytes } - /** - * Returns the zero address. - */ - static zero(): Address { - return new Address(zeros(20)) - } - - /** - * Returns an Address object from a hex-encoded string. - * @param str - Hex-encoded address - */ - static fromString(str: string): Address { - if (!isValidAddress(str)) { - throw new Error(`Invalid address input=${str}`) - } - return new Address(hexToBytes(str)) - } - - /** - * Returns an address for a given public key. - * @param pubKey The two points of an uncompressed key - */ - static fromPublicKey(pubKey: Uint8Array): Address { - if (!(pubKey instanceof Uint8Array)) { - throw new Error('Public key should be Uint8Array') - } - const bytes = pubToAddress(pubKey) - return new Address(bytes) - } - - /** - * Returns an address for a given private key. - * @param privateKey A private key must be 256 bits wide - */ - static fromPrivateKey(privateKey: Uint8Array): Address { - if (!(privateKey instanceof Uint8Array)) { - throw new Error('Private key should be Uint8Array') - } - const bytes = privateToAddress(privateKey) - return new Address(bytes) - } - - /** - * Generates an address for a newly created contract. - * @param from The address which is creating this new address - * @param nonce The nonce of the from account - */ - static generate(from: Address, nonce: bigint): Address { - if (typeof nonce !== 'bigint') { - throw new Error('Expected nonce to be a bigint') - } - return new Address(generateAddress(from.bytes, bigIntToBytes(nonce))) - } - - /** - * Generates an address for a contract created using CREATE2. - * @param from The address which is creating this new address - * @param salt A salt - * @param initCode The init code of the contract being created - */ - static generate2(from: Address, salt: Uint8Array, initCode: Uint8Array): Address { - if (!(salt instanceof Uint8Array)) { - throw new Error('Expected salt to be a Uint8Array') - } - if (!(initCode instanceof Uint8Array)) { - throw new Error('Expected initCode to be a Uint8Array') - } - return new Address(generateAddress2(from.bytes, salt, initCode)) - } - /** * Is address equal to another. */ @@ -111,7 +42,7 @@ export class Address { * Is address zero. */ isZero(): boolean { - return this.equals(Address.zero()) + return this.equals(new Address(zeros(20))) } /** @@ -139,3 +70,89 @@ export class Address { return new Uint8Array(this.bytes) } } + +/** + * Returns the zero address. + */ +export function createZeroAddress(): Address { + return new Address(zeros(20)) +} + +/** + * Returns an Address object from a bigint address (they are stored as bigints on the stack) + * @param value The bigint address + */ +export function createAddressFromBigInt(value: bigint): Address { + const bytes = bigIntToBytes(value) + if (bytes.length > 20) { + throw new Error(`Invalid address, too long: ${bytes.length}`) + } + return new Address(setLengthLeft(bytes, 20)) +} + +/** + * Returns an Address object from a hex-encoded string. + * @param str - Hex-encoded address + */ +export function createAddressFromString(str: string): Address { + if (!isValidAddress(str)) { + throw new Error(`Invalid address input=${str}`) + } + return new Address(hexToBytes(str)) +} + +/** + * Returns an address for a given public key. + * @param pubKey The two points of an uncompressed key + */ +export function createAddressFromPublicKey(pubKey: Uint8Array): Address { + if (!(pubKey instanceof Uint8Array)) { + throw new Error('Public key should be Uint8Array') + } + const bytes = pubToAddress(pubKey) + return new Address(bytes) +} + +/** + * Returns an address for a given private key. + * @param privateKey A private key must be 256 bits wide + */ +export function createAddressFromPrivateKey(privateKey: Uint8Array): Address { + if (!(privateKey instanceof Uint8Array)) { + throw new Error('Private key should be Uint8Array') + } + const bytes = privateToAddress(privateKey) + return new Address(bytes) +} + +/** + * Generates an address for a newly created contract. + * @param from The address which is creating this new address + * @param nonce The nonce of the from account + */ +export function createContractAddress(from: Address, nonce: bigint): Address { + if (typeof nonce !== 'bigint') { + throw new Error('Expected nonce to be a bigint') + } + return new Address(generateAddress(from.bytes, bigIntToBytes(nonce))) +} + +/** + * Generates an address for a contract created using CREATE2. + * @param from The address which is creating this new address + * @param salt A salt + * @param initCode The init code of the contract being created + */ +export function createContractAddress2( + from: Address, + salt: Uint8Array, + initCode: Uint8Array, +): Address { + if (!(salt instanceof Uint8Array)) { + throw new Error('Expected salt to be a Uint8Array') + } + if (!(initCode instanceof Uint8Array)) { + throw new Error('Expected initCode to be a Uint8Array') + } + return new Address(generateAddress2(from.bytes, salt, initCode)) +} diff --git a/packages/util/test/address.spec.ts b/packages/util/test/address.spec.ts index 05e57fa3e2..a0c3238db8 100644 --- a/packages/util/test/address.spec.ts +++ b/packages/util/test/address.spec.ts @@ -1,6 +1,18 @@ import { assert, describe, it } from 'vitest' -import { Address, equalsBytes, hexToBytes, toBytes } from '../src/index.js' +import { + Address, + createAddressFromBigInt, + createAddressFromPrivateKey, + createAddressFromPublicKey, + createAddressFromString, + createContractAddress, + createContractAddress2, + createZeroAddress, + equalsBytes, + hexToBytes, + toBytes, +} from '../src/index.js' import eip1014Testdata from './testdata/eip1014Examples.json' @@ -11,37 +23,48 @@ describe('Address', () => { it('should validate address length', () => { const str = '0x2f015c60e0be116b1f0cd534704db9c92118fb6a11' - assert.throws(() => Address.fromString(str)) + assert.throws(() => createAddressFromString(str)) const shortStr = '0x2f015c60e0be116b1f0cd534704db9c92118fb' - assert.throws(() => Address.fromString(shortStr)) + assert.throws(() => createAddressFromString(shortStr)) const buf = toBytes(str) assert.throws(() => new Address(buf)) }) it('should generate a zero address', () => { - const addr = Address.zero() + const addr = createZeroAddress() assert.deepEqual(addr.bytes, toBytes(ZERO_ADDR_S)) assert.equal(addr.toString(), ZERO_ADDR_S) }) it('should instantiate address from zero address string', () => { - const addr = Address.fromString(ZERO_ADDR_S) + const addr = createAddressFromString(ZERO_ADDR_S) assert.deepEqual(addr.toString(), ZERO_ADDR_S) assert.ok(addr.isZero()) }) it('should detect non-zero address', () => { const str = '0x2f015c60e0be116b1f0cd534704db9c92118fb6a' - const addr = Address.fromString(str) + const addr = createAddressFromString(str) assert.notOk(addr.isZero()) }) + it('should create an address from a bigint', () => { + const addr = createAddressFromBigInt(BigInt(0)) + assert.ok(addr.isZero()) + const addr2 = createAddressFromBigInt(BigInt(1)) + assert.notOk(addr2.isZero()) + }) + + it('should throw if bigint is too long', () => { + assert.throws(() => createAddressFromBigInt(BigInt(2) ** BigInt(160))) + }) + it('should instantiate from public key', () => { const pubKey = hexToBytes( '0x3a443d8381a6798a70c6ff9304bdc8cb0163c23211d11628fae52ef9e0dca11a001cf066d56a8156fc201cd5df8a36ef694eecd258903fca7086c1fae7441e1d', ) const str = '0x2f015c60e0be116b1f0cd534704db9c92118fb6a' - const addr = Address.fromPublicKey(pubKey) + const addr = createAddressFromPublicKey(pubKey) assert.equal(addr.toString(), str) }) @@ -49,30 +72,30 @@ describe('Address', () => { const pubKey = hexToBytes( '0x3a443d8381a6798a70c6ff9304bdc8cb0163c23211d11628fae52ef9e0dca11a001cf066d56a8156fc201cd5df8a36ef694eecd258903fca7086c1fae744', ) - assert.throws(() => Address.fromPublicKey(pubKey)) + assert.throws(() => createAddressFromPublicKey(pubKey)) }) it('should instantiate from private key', () => { // prettier-ignore const privateKey = Uint8Array.from([234, 84, 189, 197, 45, 22, 63, 136, 201, 58, 176, 97, 87, 130, 207, 113, 138, 46, 251, 158, 81, 167, 152, 154, 171, 27, 8, 6, 126, 156, 28, 95]) const str = '0x2f015c60e0be116b1f0cd534704db9c92118fb6a' - const addr = Address.fromPrivateKey(privateKey) + const addr = createAddressFromPrivateKey(privateKey) assert.equal(addr.toString(), str) }) it('should generate address for created contract', () => { - const from = Address.fromString('0x990ccf8a0de58091c028d6ff76bb235ee67c1c39') - const addr = Address.generate(from, BigInt(14)) + const from = createAddressFromString('0x990ccf8a0de58091c028d6ff76bb235ee67c1c39') + const addr = createContractAddress(from, BigInt(14)) assert.equal(addr.toString(), '0xd658a4b8247c14868f3c512fa5cbb6e458e4a989') - const addr2 = Address.generate(from, BigInt(0)) + const addr2 = createContractAddress(from, BigInt(0)) assert.equal(addr2.toString(), '0xbfa69ba91385206bfdd2d8b9c1a5d6c10097a85b') }) it('should provide correct precompile check', () => { - const precompile = Address.fromString('0x0000000000000000000000000000000000000009') + const precompile = createAddressFromString('0x0000000000000000000000000000000000000009') assert.isTrue(precompile.isPrecompileOrSystemAddress(), 'should detect precompile address') - const nonPrecompile = Address.fromString('0x990ccf8a0de58091c028d6ff76bb235ee67c1c39') + const nonPrecompile = createAddressFromString('0x990ccf8a0de58091c028d6ff76bb235ee67c1c39') assert.isFalse( nonPrecompile.isPrecompileOrSystemAddress(), 'should detect non-precompile address', @@ -82,8 +105,8 @@ describe('Address', () => { it('should generate address for CREATE2', () => { for (const testdata of eip1014Testdata) { const { address, salt, initCode, result } = testdata - const from = Address.fromString(address) - const addr = Address.generate2( + const from = createAddressFromString(address) + const addr = createContractAddress2( from, hexToBytes(salt as PrefixedHexString), hexToBytes(initCode as PrefixedHexString), @@ -94,7 +117,7 @@ describe('Address', () => { it('should provide a Uint8Array that does not mutate the original address', () => { const str = '0x2f015c60e0be116b1f0cd534704db9c92118fb6a' - const address = Address.fromString(str) + const address = createAddressFromString(str) const addressBytes = address.toBytes() addressBytes.fill(0) assert.equal(address.toString(), str) @@ -102,19 +125,19 @@ describe('Address', () => { it('should compare equality properly', () => { const str = '0x2f015c60e0be116b1f0cd534704db9c92118fb6a' - const address1 = Address.fromString(str) + const address1 = createAddressFromString(str) const address2 = new Address(hexToBytes(str)) assert.ok(address1.equals(address2)) assert.ok(equalsBytes(address1.bytes, address2.bytes)) const str2 = '0xcd4EC7b66fbc029C116BA9Ffb3e59351c20B5B06' - const address3 = Address.fromString(str2) + const address3 = createAddressFromString(str2) assert.ok(!address1.equals(address3)) - const address3LowerCase = Address.fromString(str2.toLowerCase()) + const address3LowerCase = createAddressFromString(str2.toLowerCase()) assert.ok(address3.equals(address3LowerCase)) - const address4 = Address.zero() + const address4 = createZeroAddress() assert.ok(!address1.equals(address4)) }) }) diff --git a/packages/util/test/bytes.spec.ts b/packages/util/test/bytes.spec.ts index f08ce15ea3..cf031f98af 100644 --- a/packages/util/test/bytes.spec.ts +++ b/packages/util/test/bytes.spec.ts @@ -1,7 +1,6 @@ import { assert, describe, it } from 'vitest' import { - Address, addHexPrefix, bigIntToAddressBytes, bigIntToBytes, @@ -10,6 +9,7 @@ import { bytesToBigInt, bytesToHex, bytesToInt, + createAddressFromString, equalsBytes, fromSigned, hexToBytes, @@ -262,7 +262,7 @@ describe('toBytes', () => { it('should convert a TransformabletoBytes like the Address class (i.e. provides a toBytes method)', () => { const str = '0x2f015c60e0be116b1f0cd534704db9c92118fb6a' - const address = Address.fromString(str) + const address = createAddressFromString(str) const addressBytes = toBytes(address) assert.deepEqual(addressBytes, address.toBytes()) }) @@ -423,10 +423,10 @@ describe('bigIntToAddressBytes', () => { for (const [addressHex, addressBigInt, isSafe] of testCases) { it('should correctly convert', () => { - const addressHexFromBigInt = bytesToHex(bigIntToAddressBytes(addressBigInt, false)) + const addressHexFromBigInt = bytesToHex(bigIntToAddressBytes(addressBigInt as bigint, false)) assert.equal(addressHex, addressHexFromBigInt, `should correctly convert ${addressBigInt}`) if (isSafe === false) { - assert.throw(() => bigIntToAddressBytes(addressBigInt)) + assert.throw(() => bigIntToAddressBytes(addressBigInt as bigint)) } }) } diff --git a/packages/util/test/verkle.spec.ts b/packages/util/test/verkle.spec.ts index 8eed055405..8fef2d35bb 100644 --- a/packages/util/test/verkle.spec.ts +++ b/packages/util/test/verkle.spec.ts @@ -3,12 +3,12 @@ import { assert, beforeAll, describe, it } from 'vitest' import * as verkleBlockJSON from '../../statemanager/test/testdata/verkleKaustinen6Block72.json' import { - Address, type VerkleCrypto, type VerkleExecutionWitness, VerkleLeafType, bytesToHex, concatBytes, + createAddressFromString, getVerkleKey, getVerkleStem, hexToBytes, @@ -27,7 +27,10 @@ describe('Verkle cryptographic helpers', () => { // Empty address assert.equal( bytesToHex( - getVerkleStem(verkle, Address.fromString('0x0000000000000000000000000000000000000000')), + getVerkleStem( + verkle, + createAddressFromString('0x0000000000000000000000000000000000000000'), + ), ), '0x1a100684fd68185060405f3f160e4bb6e034194336b547bdae323f888d5332', ) @@ -35,7 +38,10 @@ describe('Verkle cryptographic helpers', () => { // Non-empty address assert.equal( bytesToHex( - getVerkleStem(verkle, Address.fromString('0x71562b71999873DB5b286dF957af199Ec94617f7')), + getVerkleStem( + verkle, + createAddressFromString('0x71562b71999873DB5b286dF957af199Ec94617f7'), + ), ), '0x1540dfad7755b40be0768c6aa0a5096fbf0215e0e8cf354dd928a178346466', ) diff --git a/packages/vm/examples/browser.html b/packages/vm/examples/browser.html index 0173d56d77..dabeeedc98 100644 --- a/packages/vm/examples/browser.html +++ b/packages/vm/examples/browser.html @@ -4,7 +4,7 @@ EthereumJS Browser Examples