{"eip":4399,"title":"Supplant DIFFICULTY opcode with PREVRANDAO","description":"Expose beacon chain randomness in the EVM by supplanting DIFFICULTY opcode semantics","authors":["Mikhail Kalinin (@mkalinin)","Danny Ryan (@djrtwo)"],"status":"Final","type":"Standards Track","category":"Core","created":"2021-10-30","requires":[3675],"discussionsTo":"https://ethereum-magicians.org/t/eip-4399-supplant-difficulty-opcode-with-random/7368","repo":"EIPs","label":"EIP-4399","officialUrl":"https://eips.ethereum.org/EIPS/eip-4399","sourceUrl":"https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4399.md","url":"https://eips.huatuo.xyz/eip-4399/","tldr":{"en":"Renamed the DIFFICULTY opcode to PREVRANDAO at the Merge so it returns the beacon chain's RANDAO mix, giving contracts an on-chain (but biasable) randomness value.","ja":"The Merge で DIFFICULTY opcode を PREVRANDAO に改名し、ビーコンチェーンの RANDAO mix を返すようにした。コントラクトはオンチェーンの（ただし偏りを加えられる）乱数値を得られる。","ko":"The Merge에서 DIFFICULTY opcode를 PREVRANDAO로 이름을 바꿔 비콘 체인의 RANDAO mix를 반환하게 했다. 컨트랙트는 온체인에서 얻는(하지만 편향될 수 있는) 난수 값을 사용할 수 있다.","zh":"在 The Merge 时把 DIFFICULTY 操作码改名为 PREVRANDAO，使其返回信标链的 RANDAO mix，为合约提供一个链上（但可被影响的）随机数值。"},"tags":["evm","opcode","randomness","core","merge"],"explainers":{"en":{"lang":"en","tldr":"Renamed the DIFFICULTY opcode to PREVRANDAO at the Merge so it returns the beacon chain's RANDAO mix, giving contracts an on-chain (but biasable) randomness value.","tags":["evm","opcode","randomness","core","merge"],"related":[3675,2982],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-4399/","markdown":"## What problem does it solve?\n\nUnder Proof-of-Work, opcode `0x44` (`DIFFICULTY`) returned the block's mining difficulty. Many contracts mixed that value into hashes as a cheap source of \"randomness\".\n\nAt the Merge ([EIP-3675](/eip-3675/)) the header's `difficulty` field became `0`, so `DIFFICULTY` would have lost all meaning. Meanwhile the beacon chain produces its own randomness (the RANDAO mix) that the EVM could not see. EIP-4399 connects the two: the old opcode now returns beacon chain randomness, so existing contracts keep getting an unpredictable-looking value and new contracts gain access to RANDAO.\n\n## How it works\n\n- From the first PoS block, the header field `mixHash` (field 13) is set to the latest RANDAO mix from the beacon state of the previous block. The field is renamed `prevRandao`.\n- Opcode `0x44` returns that `prevRandao` value and is renamed `PREVRANDAO`. Gas cost is unchanged.\n- `difficulty` stays `0`. The authors reused `mixHash` instead of `difficulty` to avoid hidden bugs in client code that still sums total difficulty, and to avoid adding a new header field.\n- A contract can tell whether it runs on PoS: RANDAO outputs are 256-bit values, almost always larger than `2**64`, while PoW difficulty values were far below that.\n\nThe change was scheduled together with EIP-3675 and activated with the Merge (Paris, September 2022).\n\n## Sample code\n\nSolidity 0.8.18+ exposes the value as `block.prevrandao` (`block.difficulty` is a deprecated alias):\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\ncontract RandaoReader {\n    function isPoS() external view returns (bool) {\n        return block.prevrandao \u003e 2**64;\n    }\n\n    // Illustration only: NOT safe for anything with real value at stake.\n    function weakRandom(uint256 salt) external view returns (uint256) {\n        return uint256(keccak256(abi.encode(block.prevrandao, salt)));\n    }\n}\n```\n\nReading it off-chain with ethers v6:\n\n```ts\nconst block = await provider.getBlock(\"latest\");\nconsole.log(block!.prevRandao); // 32-byte hex string\n```\n\n## Things to know\n\n- **Biasable.** Each block proposer has roughly 1 bit of influence: they can skip their slot so the mix is not updated. A proposer can also delay a \"dice roll\" transaction into a block whose `prevRandao` they already know. Do not use it alone for lotteries or high-value games.\n- **Partly predictable.** Past values are fully known, and values a few slots ahead can be influenced or anticipated. The spec advises closing bets and then using a RANDAO mix from at least about four epochs later. For high-value use, commit-reveal schemes or VRF oracles are safer.\n- Contracts that assumed `DIFFICULTY` returns a small number may overflow; the spec considered this risk negligible.\n- Tooling and libraries may still show the field as `mixHash` or the opcode as `DIFFICULTY`.\n"},"ja":{"lang":"ja","tldr":"The Merge で DIFFICULTY opcode を PREVRANDAO に改名し、ビーコンチェーンの RANDAO mix を返すようにした。コントラクトはオンチェーンの（ただし偏りを加えられる）乱数値を得られる。","tags":["evm","opcode","randomness","core","merge"],"related":[3675,2982],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-4399/","markdown":"## 何を解決するのか\n\nProof-of-Work では、opcode `0x44`（`DIFFICULTY`）はブロックのマイニング難易度を返していました。多くのコントラクトは、この値をハッシュに混ぜて手軽な「乱数」源として使っていました。\n\nThe Merge（[EIP-3675](/eip-3675/)）でヘッダーの `difficulty` フィールドが `0` になったため、`DIFFICULTY` は意味を失うはずでした。一方、ビーコンチェーンは独自の乱数（RANDAO mix）を生み出していますが、EVM からは見えませんでした。EIP-4399 はこの両者をつなぎます。古い opcode がビーコンチェーンの乱数を返すようになり、既存のコントラクトは予測しにくく見える値を引き続き得られ、新しいコントラクトは RANDAO を利用できるようになります。\n\n## 仕組み\n\n- 最初の PoS ブロックから、ヘッダーフィールド `mixHash`（13 番目のフィールド）には、直前のブロックのビーコンステートにある最新の RANDAO mix が設定されます。このフィールドは `prevRandao` に改名されます。\n- opcode `0x44` はその `prevRandao` の値を返し、`PREVRANDAO` に改名されます。ガスコストは変わりません。\n- `difficulty` は `0` のままです。作者は `difficulty` ではなく `mixHash` を再利用しました。総難易度を合計し続けているクライアントコードに潜在的なバグが生じるのを避け、新しいヘッダーフィールドを追加しないためです。\n- コントラクトは PoS 上で動いているかどうかを判別できます。RANDAO の出力は 256 ビットの値で、ほぼ常に `2**64` より大きくなりますが、PoW の難易度の値はそれよりはるかに小さかったためです。\n\nこの変更は EIP-3675 と同時にスケジュールされ、The Merge（Paris、2022 年 9 月）で有効化されました。\n\n## サンプルコード\n\nSolidity 0.8.18 以降では、この値を `block.prevrandao` として参照できます（`block.difficulty` は非推奨のエイリアスです）:\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\ncontract RandaoReader {\n    function isPoS() external view returns (bool) {\n        return block.prevrandao \u003e 2**64;\n    }\n\n    // Illustration only: NOT safe for anything with real value at stake.\n    function weakRandom(uint256 salt) external view returns (uint256) {\n        return uint256(keccak256(abi.encode(block.prevrandao, salt)));\n    }\n}\n```\n\nethers v6 でオフチェーンから読む:\n\n```ts\nconst block = await provider.getBlock(\"latest\");\nconsole.log(block!.prevRandao); // 32-byte hex string\n```\n\n## 知っておくべきこと\n\n- **偏りを加えられる。** 各ブロックプロポーザーはおよそ 1 ビット分の影響力を持ちます。自分のスロットをスキップして mix が更新されないようにできます。また、プロポーザーは「サイコロを振る」トランザクションを、自分がすでに `prevRandao` を知っているブロックまで遅らせることもできます。抽選や高額なゲームにこれ単体で使わないでください。\n- **一部は予測可能。** 過去の値はすべて既知で、数スロット先の値も影響を与えたり予想したりできます。仕様では、賭けを締め切ってから、少なくとも約 4 エポック後の RANDAO mix を使うことを勧めています。高額な用途では、commit-reveal 方式や VRF オラクルのほうが安全です。\n- `DIFFICULTY` が小さな数を返すと仮定していたコントラクトはオーバーフローする可能性があります。仕様ではこのリスクは無視できる程度と判断されました。\n- ツールやライブラリでは、フィールドが `mixHash` のまま、opcode が `DIFFICULTY` のまま表示されることがあります。\n"},"ko":{"lang":"ko","tldr":"The Merge에서 DIFFICULTY opcode를 PREVRANDAO로 이름을 바꿔 비콘 체인의 RANDAO mix를 반환하게 했다. 컨트랙트는 온체인에서 얻는(하지만 편향될 수 있는) 난수 값을 사용할 수 있다.","tags":["evm","opcode","randomness","core","merge"],"related":[3675,2982],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-4399/","markdown":"## 어떤 문제를 해결하나요?\n\nProof-of-Work에서 opcode `0x44`(`DIFFICULTY`)는 블록의 채굴 난이도를 반환했습니다. 많은 컨트랙트가 이 값을 해시에 섞어 값싼 \"난수\" 소스로 사용했습니다.\n\nThe Merge([EIP-3675](/eip-3675/))에서 헤더의 `difficulty` 필드가 `0`이 되면서 `DIFFICULTY`는 의미를 잃게 되었습니다. 한편 비콘 체인은 자체 난수(RANDAO mix)를 만들어 내지만 EVM에서는 이를 볼 수 없었습니다. EIP-4399는 이 둘을 연결합니다. 기존 opcode가 이제 비콘 체인의 난수를 반환하므로, 기존 컨트랙트는 예측하기 어려워 보이는 값을 계속 얻고 새 컨트랙트는 RANDAO를 사용할 수 있게 됩니다.\n\n## 어떻게 동작하나요?\n\n- 첫 PoS 블록부터 헤더 필드 `mixHash`(13번째 필드)는 이전 블록의 비콘 상태에 있는 최신 RANDAO mix로 설정됩니다. 이 필드의 이름은 `prevRandao`로 바뀝니다.\n- opcode `0x44`는 그 `prevRandao` 값을 반환하며 이름이 `PREVRANDAO`로 바뀝니다. 가스 비용은 그대로입니다.\n- `difficulty`는 `0`으로 유지됩니다. 작성자들은 `difficulty` 대신 `mixHash`를 재사용했는데, 총 난이도를 계속 합산하는 클라이언트 코드에 숨은 버그가 생기는 것을 피하고 새 헤더 필드를 추가하지 않기 위해서입니다.\n- 컨트랙트는 PoS에서 실행 중인지 알 수 있습니다. RANDAO 출력은 256비트 값으로 거의 항상 `2**64`보다 큰 반면, PoW 난이도 값은 그보다 훨씬 작았습니다.\n\n이 변경은 EIP-3675와 함께 일정이 잡혔고 The Merge(Paris, 2022년 9월)와 함께 활성화되었습니다.\n\n## 샘플 코드\n\nSolidity 0.8.18 이상에서는 이 값을 `block.prevrandao`로 노출합니다(`block.difficulty`는 더 이상 권장되지 않는 별칭입니다):\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\ncontract RandaoReader {\n    function isPoS() external view returns (bool) {\n        return block.prevrandao \u003e 2**64;\n    }\n\n    // Illustration only: NOT safe for anything with real value at stake.\n    function weakRandom(uint256 salt) external view returns (uint256) {\n        return uint256(keccak256(abi.encode(block.prevrandao, salt)));\n    }\n}\n```\n\nethers v6로 오프체인에서 읽기:\n\n```ts\nconst block = await provider.getBlock(\"latest\");\nconsole.log(block!.prevRandao); // 32-byte hex string\n```\n\n## 알아둘 점\n\n- **편향될 수 있습니다.** 각 블록 제안자는 약 1비트 정도의 영향력을 가집니다. 자신의 슬롯을 건너뛰어 mix가 갱신되지 않게 할 수 있습니다. 또한 제안자는 \"주사위 굴리기\" 트랜잭션을 자신이 이미 `prevRandao`를 알고 있는 블록으로 미룰 수도 있습니다. 복권이나 고액 게임에 이 값만 단독으로 사용하지 마세요.\n- **부분적으로 예측 가능합니다.** 과거 값은 모두 알려져 있고, 몇 슬롯 앞의 값은 영향을 주거나 예상할 수 있습니다. 스펙은 베팅을 마감한 뒤 적어도 약 4 에포크 이후의 RANDAO mix를 사용하라고 권고합니다. 고액 용도에는 commit-reveal 방식이나 VRF 오라클이 더 안전합니다.\n- `DIFFICULTY`가 작은 수를 반환한다고 가정한 컨트랙트는 오버플로가 발생할 수 있습니다. 스펙은 이 위험을 무시할 만한 수준으로 판단했습니다.\n- 도구와 라이브러리에서는 여전히 이 필드를 `mixHash`로, opcode를 `DIFFICULTY`로 표시할 수 있습니다.\n"},"zh":{"lang":"zh","tldr":"在 The Merge 时把 DIFFICULTY 操作码改名为 PREVRANDAO，使其返回信标链的 RANDAO mix，为合约提供一个链上（但可被影响的）随机数值。","tags":["evm","opcode","randomness","core","merge"],"related":[3675,2982],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-4399/","markdown":"## 它解决什么问题？\n\n在工作量证明（PoW）下，操作码 `0x44`（`DIFFICULTY`）返回区块的挖矿难度。许多合约把这个值混入哈希，作为一种廉价的\"随机性\"来源。\n\n在 The Merge（[EIP-3675](/eip-3675/)）时，区块头的 `difficulty` 字段变为 `0`，`DIFFICULTY` 会因此失去全部意义。与此同时，信标链会产生自己的随机数（RANDAO mix），而 EVM 看不到它。EIP-4399 把两者连接起来：旧操作码现在返回信标链的随机数，现有合约依然能得到一个看起来不可预测的值，新合约也可以使用 RANDAO。\n\n## 它如何运作\n\n- 从第一个 PoS 区块开始，区块头字段 `mixHash`（第 13 个字段）被设置为上一个区块的信标状态中最新的 RANDAO mix。该字段改名为 `prevRandao`。\n- 操作码 `0x44` 返回该 `prevRandao` 值，并改名为 `PREVRANDAO`。gas 成本不变。\n- `difficulty` 保持为 `0`。作者复用了 `mixHash` 而不是 `difficulty`，以避免仍在累加总难度的客户端代码出现隐蔽的 bug，也避免新增区块头字段。\n- 合约可以判断自己是否运行在 PoS 上：RANDAO 的输出是 256 位的值，几乎总是大于 `2**64`，而 PoW 的难度值远低于这个数。\n\n这一变更与 EIP-3675 一同排期，并随 The Merge（Paris，2022 年 9 月）激活。\n\n## 示例代码\n\nSolidity 0.8.18+ 将该值暴露为 `block.prevrandao`（`block.difficulty` 是已弃用的别名）：\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\ncontract RandaoReader {\n    function isPoS() external view returns (bool) {\n        return block.prevrandao \u003e 2**64;\n    }\n\n    // Illustration only: NOT safe for anything with real value at stake.\n    function weakRandom(uint256 salt) external view returns (uint256) {\n        return uint256(keccak256(abi.encode(block.prevrandao, salt)));\n    }\n}\n```\n\n用 ethers v6 在链下读取：\n\n```ts\nconst block = await provider.getBlock(\"latest\");\nconsole.log(block!.prevRandao); // 32-byte hex string\n```\n\n## 需要注意\n\n- **可被影响。** 每个区块提议者大约有 1 比特的影响力：他们可以跳过自己的出块时隙，使 mix 不被更新。提议者还可以把一笔\"掷骰子\"交易推迟到某个他们已经知道 `prevRandao` 的区块中。不要单独把它用于彩票或高价值游戏。\n- **部分可预测。** 过去的值是完全已知的，未来几个时隙的值可以被影响或预判。规范建议先截止下注，然后使用至少约四个 epoch 之后的 RANDAO mix。对于高价值场景，commit-reveal 方案或 VRF 预言机更安全。\n- 假定 `DIFFICULTY` 返回较小数值的合约可能会溢出；规范认为这一风险可以忽略。\n- 工具和库中可能仍然把该字段显示为 `mixHash`，或把该操作码显示为 `DIFFICULTY`。\n"}}}
