← 返回列表

Don't Eat My Sandwich

单站 零鉴科技 发布 Fri, 28 Jul 2023 16:20:00 +0800 入库 2026-11-18T12:54:32

原创 零鉴科技 2023-07-28 16:20 北京

三明治交易是一种利用闪电贷和 AMM 自动化做市商的策略,通过在交易对中同时进行两笔交易来实现利润。这种策略被广泛应用于去中心化交易所(DEX)和其他区块链金融应用中。

三明治交易是一种利用闪电贷和 AMM 自动化做市商的策略,通过在交易对中同时进行两笔交易来实现利润。这种策略被广泛应用于去中心化交易所(DEX)和其他区块链金融应用中。然而,由于区块链的去中心化和透明性,这种策略也会成为攻击者的目标。本文将从三明治交易的原理出发,深入探讨一次针对以太坊三明治机器人的攻击事件,分析攻击者的手段和攻击原理。同时,我们也将介绍一些区块链上的基本概念和技术,以帮助读者更好地理解本文内容。

三明治攻击原理

交易顺序如何决定

三明治机器人如何运转

当机器人开始争夺三明治

狩猎通用型三明治机器人

FlashBots Auction

We believe that without the adoption of neutral, public, open-source infrastructure for permissionless MEV extraction, MEV risks becoming an insiders’ game. We commit as an organization to releasing reference implementations for participation in fair, ethical, and politically neutral MEV extraction. By doing so, we hope to prevent the properties of Ethereum from being eroded by trust-based dark pools or proprietary channels which are key points of security weakness.

✦

POW 时期的设计

POS 升级之后

Overview | Flashbots Docs --- 概述 | Flashbots 文档

Frontrunning As A Service

Relayer, Validator, and PBS

POS Proposer 选择

The validator selection is fixed two epochs in advance as a way to protect against certain kinds of seed manipulation.

选举是提前两个 epoch决定的

可预测性 & 随机性

def get_beacon_proposer_index(state: BeaconState) -> ValidatorIndex:  """  Return the beacon proposer index at the current slot.  """  epoch = get_current_epoch(state)  seed = hash(get_seed(state, epoch, DOMAIN_BEACON_PROPOSER) + int_to_bytes(state.slot, length=8))  indices = get_active_validator_indices(state, epoch)  return compute_proposer_index(state, indices, seed)

def compute_proposer_index(state: BeaconState, indices: Sequence[ValidatorIndex], seed: Bytes32) -> ValidatorIndex:    """    Return from ``indices`` a random index sampled by effective balance.    """    assert len(indices) > 0    MAX_RANDOM_BYTE = 2**8 - 1    i = uint64(0)    total = uint64(len(indices))    while True:        candidate_index = indices[compute_shuffled_index(i % total, total, seed)]        random_byte = hash(seed + uint_to_bytes(uint64(i // 32)))[i % 32]        effective_balance = state.validators[candidate_index].effective_balance        if effective_balance * MAX_RANDOM_BYTE >= MAX_EFFECTIVE_BALANCE * random_byte:            return candidate_index        i += 1

可以看到 proposer 的选择主要来源于这个 seed,那么这个 seed 是从哪里来呢?

proof of stake - How are block proposers selected in Ethereum 2.0? - Ethereum Stack Exchange

prysm-spike/randao.go at d5ac70f0406b445a276ee61ba10fdf0eb6aafa0f · silesiacoin/prysm-spike

def get_seed(state: BeaconState, epoch: Epoch, domain_type: DomainType) -> Hash:  """  Return the seed at ``epoch``.  """  mix = get_randao_mix(state, Epoch(epoch + EPOCHS_PER_HISTORICAL_VECTOR - MIN_SEED_LOOKAHEAD - 1))  # Avoid underflow  return hash(domain_type + int_to_bytes(epoch, length=8) + mix)

def get_randao_mix(state: BeaconState, epoch: Epoch) -> Hash: """ Return the randao mix at a recent ``epoch``. """ return state.randao_mixes[epoch % EPOCHS_PER_HISTORICAL_VECTOR]

Current and past RANDAO values are stored in the beacon state(https://eth2book.info/bellatrix/part3/containers/state/#beaconstate) in the randao_mixes field. The current value is updated by process_randao(https://eth2book.info/bellatrix/part3/transition/block/#def_process_randao)with every block that the beacon chain processes.

那么这个 randao_mixes 又是如何计算的?

每个区块的所有交易计算结束后会调用 process_block,进而调用 process_randao

def process_block(state: BeaconState, block: BeaconBlock) -> None:    process_block_header(state, block)    process_randao(state, block.body)    process_eth1_data(state, block.body)    process_operations(state, block.body)

def process_randao(state: BeaconState, body: BeaconBlockBody) -> None:    epoch = get_current_epoch(state)    # Verify RANDAO reveal    proposer = state.validators[get_beacon_proposer_index(state)]    signing_root = compute_signing_root(epoch, get_domain(state, DOMAIN_RANDAO))    assert bls.Verify(proposer.pubkey, signing_root, body.randao_reveal)    # Mix in RANDAO reveal    mix = xor(get_randao_mix(state, epoch), hash(body.randao_reveal))    state.randao_mixes[epoch % EPOCHS_PER_HISTORICAL_VECTOR] = mi

class BeaconBlockBody(Container):    randao_reveal: BLSSignature    eth1_data: Eth1Data  # Eth1 data vote    graffiti: Bytes32  # Arbitrary data    # Operations    proposer_slashings: List[ProposerSlashing, MAX_PROPOSER_SLASHINGS]    attester_slashings: List[AttesterSlashing, MAX_ATTESTER_SLASHINGS]    attestations: List[Attestation, MAX_ATTESTATIONS]    deposits: List[Deposit, MAX_DEPOSITS]    voluntary_exits: List[SignedVoluntaryExit, MAX_VOLUNTARY_EXITS]

Dusk for Sandwich Bots

布局

// ExecutionPayload https://github.com/ethereum/consensus-specs/blob/dev/specs/bellatrix/beacon-chain.md#executionpayloadtype ExecutionPayload struct {  ParentHash    Hash            `json:"parent_hash" ssz-size:"32"`  FeeRecipient  Address         `json:"fee_recipient" ssz-size:"20"`  StateRoot     Root            `json:"state_root" ssz-size:"32"`  ReceiptsRoot  Root            `json:"receipts_root" ssz-size:"32"`  LogsBloom     Bloom           `json:"logs_bloom" ssz-size:"256"`  Random        Hash            `json:"prev_randao" ssz-size:"32"`  BlockNumber   uint64          `json:"block_number,string"`  GasLimit      uint64          `json:"gas_limit,string"`  GasUsed       uint64          `json:"gas_used,string"`  Timestamp     uint64          `json:"timestamp,string"`  ExtraData     ExtraData       `json:"extra_data" ssz-max:"32"`  BaseFeePerGas U256Str         `json:"base_fee_per_gas" ssz-max:"32"`  BlockHash     Hash            `json:"block_hash" ssz-size:"32"`  ` Transactions  []hexutil.Bytesjson:"transactions" ssz-max:"1048576,1073741824" ssz-size:"?,?"```}

Attack!

Unfortunately, if the signed block was invalid, then it would never be accepted by the network, so there would be no race at all. By setting both the parent root and the state root to zero, that's exactly what the malicious validator did.

Proposer Slashing

本次攻击的 proposer 被 slash 的证据:

代价

Correlation penalty=min(B,2SB/T)

crements in the list of slashed validators over the last 36 days, B my effective balance, and T the total increments, the calculation looks as follows.

原文链接:https://mp.weixin.qq.com/s?__biz=MzkzODE2NjgyNQ==&mid=2247502907&idx=1&sn=3e243b398d98c5630b7e8bc4c730670f