From 13fd40b3218042f3284231deb22ce5a8b6379f0e Mon Sep 17 00:00:00 2001 From: Marketen Date: Thu, 22 Oct 2026 17:44:50 +0200 Subject: [PATCH 1/9] Bump go-eth2-client to v0.30.2 for Gloas support Glamsterdam's consensus fork (Gloas) moves the execution payload out of the beacon block. v0.30.2 is the first go-eth2-client release that can decode Gloas beacon blocks and fetch execution payload envelopes; with v0.27.1 the oracle stops at the first Gloas slot because the block can't be decoded. v0.30 requires Go 1.25, so the Dockerfile and CI move to it as well. go-bitfield moved from prysmaticlabs to OffchainLabs upstream, which only affects one test import. No behaviour changes. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/tests.yml | 2 +- Dockerfile | 4 ++-- go.mod | 25 ++++++++++----------- go.sum | 44 ++++++++++++++++++------------------- oracle/block_test.go | 2 +- 5 files changed, 37 insertions(+), 40 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index c960974..9fddaec 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -4,7 +4,7 @@ jobs: test: strategy: matrix: - go-version: [1.24.x] + go-version: [1.25.x] #macos-latest, windows-latest os: [ubuntu-latest, macos-latest] runs-on: ${{ matrix.os }} diff --git a/Dockerfile b/Dockerfile index 23ed4e8..b97407a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.24-alpine AS build +FROM golang:1.25-alpine AS build ARG BUILD_VERSION WORKDIR /app @@ -9,7 +9,7 @@ RUN apk add --update gcc g++ RUN go mod download RUN go build -o /mev-sp-oracle -ldflags "-X github.com/dappnode/mev-sp-oracle/config.ReleaseVersion=$BUILD_VERSION" . -FROM golang:1.24-alpine +FROM golang:1.25-alpine WORKDIR / diff --git a/go.mod b/go.mod index aa9d297..59efe68 100644 --- a/go.mod +++ b/go.mod @@ -1,10 +1,9 @@ module github.com/dappnode/mev-sp-oracle -go 1.23.0 - -toolchain go1.24.2 +go 1.25.0 require ( + github.com/OffchainLabs/go-bitfield v0.0.0-20251031151322-f427d04d8506 github.com/attestantio/go-builder-client v0.4.3 github.com/avast/retry-go/v4 v4.5.0 github.com/gorilla/mux v1.8.0 @@ -12,12 +11,11 @@ require ( github.com/miguelmota/go-solidity-sha3 v0.1.1 github.com/pkg/errors v0.9.1 github.com/prometheus/client_golang v1.17.0 - github.com/prysmaticlabs/go-bitfield v0.0.0-20240618144021-706c95b2dd15 github.com/rs/zerolog v1.32.0 github.com/sirupsen/logrus v1.9.3 - github.com/stretchr/testify v1.10.0 + github.com/stretchr/testify v1.11.1 github.com/txaty/go-merkletree v0.1.15 - golang.org/x/crypto v0.35.0 + golang.org/x/crypto v0.42.0 golang.org/x/exp v0.0.0-20231110203233-9a3e6036ecaa ) @@ -44,19 +42,19 @@ require ( github.com/go-ole/go-ole v1.3.0 // indirect github.com/go-playground/validator/v10 v10.11.1 // indirect github.com/goccy/go-yaml v1.11.2 // indirect - github.com/google/go-cmp v0.6.0 // indirect github.com/google/uuid v1.3.1 // indirect github.com/gorilla/websocket v1.5.0 // indirect github.com/holiman/uint256 v1.3.2 // indirect github.com/huandu/go-clone v1.6.0 // indirect - github.com/klauspost/cpuid/v2 v2.2.9 // indirect + github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/mattn/go-colorable v0.1.14 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 // indirect github.com/minio/sha256-simd v1.0.1 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/mmcloughlin/addchain v0.4.0 // indirect - github.com/pk910/dynamic-ssz v0.0.4 // indirect + github.com/pk910/dynamic-ssz v1.4.0 // indirect + github.com/pk910/hashtree-bindings v0.2.6 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/prometheus/client_model v0.5.0 // indirect github.com/prometheus/common v0.45.0 // indirect @@ -71,11 +69,10 @@ require ( go.opentelemetry.io/otel v1.19.0 // indirect go.opentelemetry.io/otel/metric v1.19.0 // indirect go.opentelemetry.io/otel/trace v1.19.0 // indirect - golang.org/x/net v0.36.0 // indirect - golang.org/x/sync v0.11.0 // indirect + golang.org/x/net v0.43.0 // indirect + golang.org/x/sync v0.17.0 // indirect golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028 // indirect google.golang.org/protobuf v1.34.2 // indirect - gopkg.in/Knetic/govaluate.v3 v3.0.0 // indirect gopkg.in/cenkalti/backoff.v1 v1.1.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect @@ -83,7 +80,7 @@ require ( ) require ( - github.com/attestantio/go-eth2-client v0.27.1 + github.com/attestantio/go-eth2-client v0.30.2 github.com/ethereum/go-ethereum v1.15.7 - golang.org/x/sys v0.30.0 // indirect + golang.org/x/sys v0.36.0 // indirect ) diff --git a/go.sum b/go.sum index 2a419bf..de85f74 100644 --- a/go.sum +++ b/go.sum @@ -2,14 +2,16 @@ github.com/DataDog/zstd v1.4.5 h1:EndNeuB0l9syBZhut0wns3gV1hL8zX8LIu6ZiVHWLIQ= github.com/DataDog/zstd v1.4.5/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo= github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= +github.com/OffchainLabs/go-bitfield v0.0.0-20251031151322-f427d04d8506 h1:d/SJkN8/9Ca+1YmuDiUJxAiV4w/a9S8NcsG7GMQSrVI= +github.com/OffchainLabs/go-bitfield v0.0.0-20251031151322-f427d04d8506/go.mod h1:6TZI4FU6zT8x6ZfWa1J8YQ2NgW0wLV/W3fHRca8ISBo= github.com/VictoriaMetrics/fastcache v1.12.2 h1:N0y9ASrJ0F6h0QaC3o6uJb3NIZ9VKLjCM7NQbSmF7WI= github.com/VictoriaMetrics/fastcache v1.12.2/go.mod h1:AmC+Nzz1+3G2eCPapF6UcsnkThDcMsQicp4xDukwJYI= github.com/agiledragon/gomonkey/v2 v2.9.0 h1:PDiKKybR596O6FHW+RVSG0Z7uGCBNbmbUXh3uCNQ7Hc= github.com/agiledragon/gomonkey/v2 v2.9.0/go.mod h1:ap1AmDzcVOAz1YpeJ3TCzIgstoaWLA6jbbgxfB4w2iY= github.com/attestantio/go-builder-client v0.4.3 h1:K1m/PTqY01mfAPc0h+9iR2OivY3LOevbxHxEfvI4M8M= github.com/attestantio/go-builder-client v0.4.3/go.mod h1:yeJANU1O5P3b/4+iwShz9JMcgUnZABCh5RJBtZnLiDo= -github.com/attestantio/go-eth2-client v0.27.1 h1:g7bm+gG/p+gfzYdEuxuAepVWYb8EO+2KojV5/Lo2BxM= -github.com/attestantio/go-eth2-client v0.27.1/go.mod h1:fvULSL9WtNskkOB4i+Yyr6BKpNHXvmpGZj9969fCrfY= +github.com/attestantio/go-eth2-client v0.30.2 h1:8LWN86Dh5PjXTwcrRR+SXcatcocFw7j08KO7NFqEcNo= +github.com/attestantio/go-eth2-client v0.30.2/go.mod h1:IcbypY5iD/c/T5OLWVuZyWS8kM8HXkGc0ZW12uikfys= github.com/avast/retry-go/v4 v4.5.0 h1:QoRAZZ90cj5oni2Lsgl2GW8mNTnUCnmpx/iKpwVisHg= github.com/avast/retry-go/v4 v4.5.0/go.mod h1:7hLEXp0oku2Nir2xBAsg0PTphp9z71bN5Aq1fboC3+I= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= @@ -140,8 +142,8 @@ github.com/jackpal/go-nat-pmp v1.0.2 h1:KzKSgb7qkJvOUTqYl9/Hg/me3pWgBmERKrTGD7Bd github.com/jackpal/go-nat-pmp v1.0.2/go.mod h1:QPH045xvCAeXUZOxsnwmrtiCoxIr9eob+4orBN1SBKc= github.com/klauspost/compress v1.16.0 h1:iULayQNOReoYUe+1qtKOqw9CwJv3aNQu8ivo7lw1HU4= github.com/klauspost/compress v1.16.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= -github.com/klauspost/cpuid/v2 v2.2.9 h1:66ze0taIn2H33fBvCkXuv9BmCwDfafmiIVpKV9kKGuY= -github.com/klauspost/cpuid/v2 v2.2.9/go.mod h1:rqkxqrZ1EhYM9G+hXH7YdowN5R5RGN6NK4QwQ3WMXF8= +github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= +github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= @@ -195,8 +197,10 @@ github.com/pion/transport/v2 v2.2.1 h1:7qYnCBlpgSJNYMbLCKuSY9KbQdBFoETvPNETv0y4N github.com/pion/transport/v2 v2.2.1/go.mod h1:cXXWavvCnFF6McHTft3DWS9iic2Mftcz1Aq29pGcU5g= github.com/pion/transport/v3 v3.0.1 h1:gDTlPJwROfSfz6QfSi0ZmeCSkFcnWWiiR9ES0ouANiM= github.com/pion/transport/v3 v3.0.1/go.mod h1:UY7kiITrlMv7/IKgd5eTUcaahZx5oUN3l9SzK5f5xE0= -github.com/pk910/dynamic-ssz v0.0.4 h1:DT29+1055tCEPCaR4V/ez+MOKW7BzBsmjyFvBRqx0ME= -github.com/pk910/dynamic-ssz v0.0.4/go.mod h1:b6CrLaB2X7pYA+OSEEbkgXDEcRnjLOZIxZTsMuO/Y9c= +github.com/pk910/dynamic-ssz v1.4.0 h1:uwDOiBR/gmbC08gGo1TA/SLD17ArJyLKi0PHaQmuZEM= +github.com/pk910/dynamic-ssz v1.4.0/go.mod h1:mnRbhjX+4YMyP4jYMncTUA3aDpMzBLqAbjcvfCyOyRI= +github.com/pk910/hashtree-bindings v0.2.6 h1:BjRQho04nWzGrXwBCLVTyQRNV30O59iPcvQRcidFt2o= +github.com/pk910/hashtree-bindings v0.2.6/go.mod h1:zrWt88783JmhBfcgni6kkIMYRdXTZi/FL//OyI5T/l4= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= @@ -210,8 +214,6 @@ github.com/prometheus/common v0.45.0 h1:2BGz0eBc2hdMDLnO/8n0jeB3oPrt2D08CekT0lne github.com/prometheus/common v0.45.0/go.mod h1:YJmSTw9BoKxJplESWWxlbyttQR4uaEcGyv9MZjVOJsY= github.com/prometheus/procfs v0.12.0 h1:jluTpSng7V9hY0O2R9DzzJHYb2xULk9VTR1V1R/k6Bo= github.com/prometheus/procfs v0.12.0/go.mod h1:pcuDEFsWDnvcgNzo4EEweacyhjeA9Zk3cnaOZAZEfOo= -github.com/prysmaticlabs/go-bitfield v0.0.0-20240618144021-706c95b2dd15 h1:lC8kiphgdOBTcbTvo8MwkvpKjO0SlAgjv4xIK5FGJ94= -github.com/prysmaticlabs/go-bitfield v0.0.0-20240618144021-706c95b2dd15/go.mod h1:8svFBIKKu31YriBG/pNizo9N0Jr9i5PQ+dFkxWg3x5k= github.com/prysmaticlabs/gohashtree v0.0.4-beta h1:H/EbCuXPeTV3lpKeXGPpEV9gsUpkqOOVnWapUyeWro4= github.com/prysmaticlabs/gohashtree v0.0.4-beta/go.mod h1:BFdtALS+Ffhg3lGQIHv9HDWuHS8cTvHZzrHWxwOtGOs= github.com/r3labs/sse/v2 v2.10.0 h1:hFEkLLFY4LDifoHdiCN/LlGBAdVJYsANaLqNYa1l/v0= @@ -237,8 +239,8 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= -github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/supranational/blst v0.3.14 h1:xNMoHRJOTwMn63ip6qoWJ2Ymgvj7E2b9jY2FAwY+qRo= github.com/supranational/blst v0.3.14/go.mod h1:jZJtfjgudtNl4en1tzwPIV3KjUnQUvG3/j+w+fVonLw= github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 h1:epCh84lMvA70Z7CTTCmYQn2CKbY8j86K7/FAIr141uY= @@ -265,16 +267,16 @@ go.opentelemetry.io/otel/trace v1.19.0 h1:DFVQmlVbfVeOuBRrwdtaehRrWiL1JoVs9CPIQ1 go.opentelemetry.io/otel/trace v1.19.0/go.mod h1:mfaSyvGyEJEI0nyV2I4qhNQnbBOUUmYZpYojqMnX2vo= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.35.0 h1:b15kiHdrGCHrP6LvwaQ3c03kgNhhiMgvlhxHQhmg2Xs= -golang.org/x/crypto v0.35.0/go.mod h1:dy7dXNW32cAb/6/PRuTNsix8T+vJAqvuIy5Bli/x0YQ= +golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI= +golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8= golang.org/x/exp v0.0.0-20231110203233-9a3e6036ecaa h1:FRnLl4eNAQl8hwxVVC17teOw8kdjVDVAiFMtgUdTSRQ= golang.org/x/exp v0.0.0-20231110203233-9a3e6036ecaa/go.mod h1:zk2irFbV9DP96SEBUUAy67IdHUaZuSnrz1n472HUCLE= golang.org/x/net v0.0.0-20191116160921-f9c825593386/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.36.0 h1:vWF2fRbw4qslQsQzgFqZff+BItCvGFQqKzKIzx1rmoA= -golang.org/x/net v0.36.0/go.mod h1:bFmbeoIPfrw4sMHNhb4J9f6+tPziuGjq7Jk/38fxi1I= -golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w= -golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE= +golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg= +golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug= +golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -289,14 +291,14 @@ golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= -golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k= +golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM= -golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= +golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk= +golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4= golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY= golang.org/x/time v0.9.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -304,8 +306,6 @@ golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028 h1:+cNy6SZtPcJQH3LJVLOSm golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90= google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= -gopkg.in/Knetic/govaluate.v3 v3.0.0 h1:18mUyIt4ZlRlFZAAfVetz4/rzlJs9yhN+U02F4u1AOc= -gopkg.in/Knetic/govaluate.v3 v3.0.0/go.mod h1:csKLBORsPbafmSCGTEh3U7Ozmsuq8ZSIlKk1bcqph0E= gopkg.in/cenkalti/backoff.v1 v1.1.0 h1:Arh75ttbsvlpVA7WtVpH4u9h6Zl46xuptxqLxPiSo4Y= gopkg.in/cenkalti/backoff.v1 v1.1.0/go.mod h1:J6Vskwqd+OMVJl8C33mmtxTBs2gyzfv7UDAkHu8BrjI= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/oracle/block_test.go b/oracle/block_test.go index e1bcd0d..f19daef 100644 --- a/oracle/block_test.go +++ b/oracle/block_test.go @@ -9,6 +9,7 @@ import ( "path/filepath" "testing" + "github.com/OffchainLabs/go-bitfield" v1 "github.com/attestantio/go-eth2-client/api/v1" "github.com/attestantio/go-eth2-client/spec" "github.com/attestantio/go-eth2-client/spec/altair" @@ -19,7 +20,6 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/pkg/errors" - "github.com/prysmaticlabs/go-bitfield" "github.com/stretchr/testify/require" ) From 0461084d5fa36c2f03905dd3a9306cd7144234dd Mon Sep 17 00:00:00 2001 From: Marketen Date: Thu, 22 Oct 2026 17:47:02 +0200 Subject: [PATCH 2/9] Compute the vanilla reward from each tx's priority fee The vanilla reward was calculated as every fee paid minus the block gas_used times the base fee. That relies on the block gas_used being the sum of the gas charged to each tx, which Glamsterdam breaks: EIP-7778 stops subtracting refunds from it, and EIP-8037 makes it the largest of two gas dimensions. The pool would have been credited less than it received, and the onchain reconciliation would refuse to freeze the checkpoint. Sum each tx's priority fee instead, using the gas its receipt charged. Until Glamsterdam both calculations are equal, which the new tests check for every supported tx type, so no published reward changes and the change needs no activation slot. It also fixes a tx/receipt hash mismatch silently returning a nil reward with a nil error, as the error was wrapped from a nil one. Co-Authored-By: Claude Opus 5.5 --- go.mod | 2 +- oracle/block.go | 67 ++++++------ oracle/proposer_tip_test.go | 207 ++++++++++++++++++++++++++++++++++++ 3 files changed, 244 insertions(+), 32 deletions(-) create mode 100644 oracle/proposer_tip_test.go diff --git a/go.mod b/go.mod index 59efe68..1988270 100644 --- a/go.mod +++ b/go.mod @@ -8,6 +8,7 @@ require ( github.com/avast/retry-go/v4 v4.5.0 github.com/gorilla/mux v1.8.0 github.com/hako/durafmt v0.0.0-20210608085754-5c1018a4e16b + github.com/holiman/uint256 v1.3.2 github.com/miguelmota/go-solidity-sha3 v0.1.1 github.com/pkg/errors v0.9.1 github.com/prometheus/client_golang v1.17.0 @@ -44,7 +45,6 @@ require ( github.com/goccy/go-yaml v1.11.2 // indirect github.com/google/uuid v1.3.1 // indirect github.com/gorilla/websocket v1.5.0 // indirect - github.com/holiman/uint256 v1.3.2 // indirect github.com/huandu/go-clone v1.6.0 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/mattn/go-colorable v0.1.14 // indirect diff --git a/oracle/block.go b/oracle/block.go index b886476..6460396 100644 --- a/oracle/block.go +++ b/oracle/block.go @@ -671,9 +671,15 @@ func (b *FullBlock) isAddressRewarded(address string) bool { return false } -// The reward for vanila block has to be calculated by iterating all -// txs and getting the individual tips as per EIP1559. Note that to -// calculate this we need the execution header and receipts +// The reward for vanila block is the sum of the priority fee of every tx: what +// it paid per unit of gas above the base fee, times the gas it was charged for. +// The receipts are needed since only they hold the gas each tx was charged for. +// +// This used to be calculated as all the fees paid minus gas_used * base fee, +// which relies on the block gas_used being the sum of the gas charged to each +// tx. Glamsterdam breaks that: EIP-7778 no longer subtracts refunds from the +// block gas_used and EIP-8037 makes it the largest of two gas dimensions. Before +// Glamsterdam both calculations give the same result, so past rewards hold. func (b *FullBlock) GetProposerTip() (*big.Int, error) { // Ensure non nil @@ -681,23 +687,13 @@ func (b *FullBlock) GetProposerTip() (*big.Int, error) { return nil, errors.New("receipts of full block are nil, cant calculate tip") } - if b.ExecutionHeader == nil { - return nil, errors.New("header of full block are nil, cant calculate tip") - } - // Ensure tx and their receipts have the same size if len(b.GetBlockTransactions()) != len(b.ExecutionReceipts) { return nil, errors.New(fmt.Sprintf("txs and receipts not the same length. txs: %d, receipts: %d", len(b.GetBlockTransactions()), len(b.ExecutionReceipts))) } - // little-endian to big-endian - var baseFeePerGasBEBytes [32]byte - for i := 0; i < 32; i++ { - baseFeePerGasBEBytes[i] = b.GetBaseFeePerGas()[32-1-i] - } - baseFeePerGas := new(big.Int).SetBytes(baseFeePerGasBEBytes[:]) - + baseFeePerGas := b.GetBaseFeePerGasBigInt() tips := big.NewInt(0) for i, rawTx := range b.GetBlockTransactions() { @@ -706,31 +702,29 @@ func (b *FullBlock) GetProposerTip() (*big.Int, error) { return nil, errors.Wrap(err, "could not decode tx") } if tx.Hash() != b.ExecutionReceipts[i].TxHash { - return nil, errors.Wrap(err, "tx hash does not match receipt hash") + return nil, errors.New(fmt.Sprintf("tx hash does not match receipt hash. tx: %s, receipt: %s", + tx.Hash().String(), b.ExecutionReceipts[i].TxHash.String())) } - tipFee := new(big.Int) - gasPrice := tx.GasPrice() - gasUsed := big.NewInt(int64(b.ExecutionReceipts[i].GasUsed)) - + // A new tx type could pay its fees differently, so better to stop than + // to credit a wrong reward switch tx.Type() { - case 0: - tipFee.Mul(gasPrice, gasUsed) - case 1: - tipFee.Mul(gasPrice, gasUsed) - case 2, 3, 4: - // Sum gastipcap and basefee or saturate to gasfeecap - usedGasPrice := utils.SumAndSaturate(tx.GasTipCap(), b.ExecutionHeader.BaseFee, tx.GasFeeCap()) - tipFee = new(big.Int).Mul(usedGasPrice, gasUsed) + case types.LegacyTxType, types.AccessListTxType, types.DynamicFeeTxType, types.BlobTxType, types.SetCodeTxType: default: return nil, errors.New(fmt.Sprintf("unknown tx type: %d, hash: %s", tx.Type(), tx.Hash().String())) } - tips = tips.Add(tips, tipFee) + + // As per EIP-1559: min(tip cap, fee cap - base fee). Legacy txs have both + // caps set to their gas price + tipPerGas, err := tx.EffectiveGasTip(baseFeePerGas) + if err != nil { + return nil, errors.Wrap(err, "could not get effective tip of tx "+tx.Hash().String()) + } + gasUsed := new(big.Int).SetUint64(b.ExecutionReceipts[i].GasUsed) + tips.Add(tips, new(big.Int).Mul(tipPerGas, gasUsed)) } - burnt := new(big.Int).Mul(big.NewInt(int64(b.GetGasUsed())), baseFeePerGas) - proposerReward := new(big.Int).Sub(tips, burnt) - return proposerReward, nil + return tips, nil } // Returns the donations sent to the pool. There are two types of donations: @@ -1055,3 +1049,14 @@ func (b *FullBlock) GetBaseFeePerGas() [32]byte { } return baseFeePerGas } + +// Returns the base fee per gas of the block as a number, in wei +func (b *FullBlock) GetBaseFeePerGasBigInt() *big.Int { + // GetBaseFeePerGas is little-endian, big.Int expects big-endian + littleEndian := b.GetBaseFeePerGas() + var bigEndian [32]byte + for i := 0; i < 32; i++ { + bigEndian[i] = littleEndian[32-1-i] + } + return new(big.Int).SetBytes(bigEndian[:]) +} diff --git a/oracle/proposer_tip_test.go b/oracle/proposer_tip_test.go new file mode 100644 index 0000000..e96239a --- /dev/null +++ b/oracle/proposer_tip_test.go @@ -0,0 +1,207 @@ +package oracle + +import ( + "crypto/ecdsa" + "math/big" + "testing" + + v1 "github.com/attestantio/go-eth2-client/api/v1" + "github.com/attestantio/go-eth2-client/spec" + "github.com/attestantio/go-eth2-client/spec/bellatrix" + "github.com/attestantio/go-eth2-client/spec/deneb" + "github.com/attestantio/go-eth2-client/spec/electra" + "github.com/attestantio/go-eth2-client/spec/phase0" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/crypto" + "github.com/holiman/uint256" + "github.com/stretchr/testify/require" +) + +const gwei = int64(1_000_000_000) + +// A tx of the block together with the gas its receipt says it was charged for +type chargedTx struct { + tx *types.Transaction + gasUsed uint64 +} + +// Signs one tx of every type the oracle supports. Fee caps are chosen so that +// some txs pay their full tip and others are capped by the fee cap +func txsOfEveryType(t *testing.T, key *ecdsa.PrivateKey) []chargedTx { + t.Helper() + chainId := new(big.Int).SetUint64(MainnetChainId) + signer := types.LatestSignerForChainID(chainId) + to := common.HexToAddress("0x5555555555555555555555555555555555555555") + + sign := func(data types.TxData) *types.Transaction { + tx, err := types.SignNewTx(key, signer, data) + require.NoError(t, err) + return tx + } + txs := []*types.Transaction{ + sign(&types.LegacyTx{Nonce: 0, GasPrice: big.NewInt(13 * gwei), Gas: 21000, To: &to}), + sign(&types.AccessListTx{ChainID: chainId, Nonce: 1, GasPrice: big.NewInt(11 * gwei), Gas: 30000, To: &to}), + // Full tip paid: base fee + tip is below the fee cap + sign(&types.DynamicFeeTx{ChainID: chainId, Nonce: 2, GasTipCap: big.NewInt(2 * gwei), GasFeeCap: big.NewInt(50 * gwei), Gas: 90000, To: &to}), + // Tip capped by the fee cap + sign(&types.DynamicFeeTx{ChainID: chainId, Nonce: 3, GasTipCap: big.NewInt(9 * gwei), GasFeeCap: big.NewInt(12 * gwei), Gas: 50000, To: &to}), + sign(&types.BlobTx{ChainID: uint256.NewInt(MainnetChainId), Nonce: 4, GasTipCap: uint256.NewInt(uint64(3 * gwei)), + GasFeeCap: uint256.NewInt(uint64(40 * gwei)), Gas: 21000, To: to, BlobFeeCap: uint256.NewInt(1), + BlobHashes: []common.Hash{{0x01}}}), + sign(&types.SetCodeTx{ChainID: uint256.NewInt(MainnetChainId), Nonce: 5, GasTipCap: uint256.NewInt(uint64(1 * gwei)), + GasFeeCap: uint256.NewInt(uint64(30 * gwei)), Gas: 60000, To: to}), + } + gasUsed := []uint64{21000, 25400, 61234, 50000, 21000, 47311} + + charged := make([]chargedTx, len(txs)) + for i := range txs { + charged[i] = chargedTx{tx: txs[i], gasUsed: gasUsed[i]} + } + return charged +} + +// Builds a Fulu block containing the given txs and their receipts. blockGasUsed +// is what the block header says, which since Glamsterdam can differ from the +// sum of the receipts +func blockWithReceipts(t *testing.T, txs []chargedTx, baseFeeWei int64, blockGasUsed uint64) *FullBlock { + t.Helper() + rawTxs := make([]bellatrix.Transaction, len(txs)) + receipts := make([]*types.Receipt, len(txs)) + for i, charged := range txs { + raw, err := charged.tx.MarshalBinary() + require.NoError(t, err) + rawTxs[i] = raw + receipts[i] = &types.Receipt{TxHash: charged.tx.Hash(), GasUsed: charged.gasUsed} + } + + fullBlock := NewFullBlock(&v1.ProposerDuty{Slot: 100, ValidatorIndex: 7}, + &v1.Validator{Index: 7, Validator: &phase0.Validator{}}, MainnetChainId) + fullBlock.SetConsensusBlock(&spec.VersionedSignedBeaconBlock{ + Version: spec.DataVersionFulu, + Fulu: &electra.SignedBeaconBlock{Message: &electra.BeaconBlock{ + Slot: 100, ProposerIndex: 7, + Body: &electra.BeaconBlockBody{ExecutionPayload: &deneb.ExecutionPayload{ + BlockNumber: 1000, + GasUsed: blockGasUsed, + BaseFeePerGas: uint256.NewInt(uint64(baseFeeWei)), + Transactions: rawTxs, + }}, + }}, + }) + fullBlock.ExecutionHeader = &types.Header{Number: big.NewInt(1000), BaseFee: big.NewInt(baseFeeWei), GasUsed: blockGasUsed} + fullBlock.ExecutionReceipts = receipts + return fullBlock +} + +func sumGasUsed(txs []chargedTx) uint64 { + total := uint64(0) + for _, charged := range txs { + total += charged.gasUsed + } + return total +} + +// The calculation used until Glamsterdam: every fee paid minus what the block +// burnt, using the block gas_used. Kept here to prove the new one matches it +func formerProposerTip(txs []chargedTx, baseFee *big.Int, blockGasUsed uint64) *big.Int { + fees := big.NewInt(0) + for _, charged := range txs { + pricePerGas := new(big.Int).Add(charged.tx.GasTipCap(), baseFee) + if pricePerGas.Cmp(charged.tx.GasFeeCap()) > 0 { + pricePerGas = charged.tx.GasFeeCap() + } + fees.Add(fees, new(big.Int).Mul(pricePerGas, new(big.Int).SetUint64(charged.gasUsed))) + } + burnt := new(big.Int).Mul(new(big.Int).SetUint64(blockGasUsed), baseFee) + return fees.Sub(fees, burnt) +} + +// Before Glamsterdam the block gas_used is the sum of the receipts, and the new +// calculation must give exactly the old result so past rewards don't change +func Test_GetProposerTip_MatchesFormerCalculationBeforeGlamsterdam(t *testing.T) { + key, err := crypto.GenerateKey() + require.NoError(t, err) + txs := txsOfEveryType(t, key) + + for _, baseFeeGwei := range []int64{1, 7, 10} { + baseFee := big.NewInt(baseFeeGwei * gwei) + fullBlock := blockWithReceipts(t, txs, baseFee.Int64(), sumGasUsed(txs)) + + tip, err := fullBlock.GetProposerTip() + require.NoError(t, err) + require.Equal(t, formerProposerTip(txs, baseFee, sumGasUsed(txs)), tip, "base fee %d gwei", baseFeeGwei) + } +} + +// EIP-7778 stops subtracting refunds from the block gas_used, so it can exceed +// what the txs were charged. The tip must only count what was actually charged +func Test_GetProposerTip_BlockGasUsedIncludesRefunds(t *testing.T) { + key, err := crypto.GenerateKey() + require.NoError(t, err) + txs := txsOfEveryType(t, key) + baseFee := big.NewInt(7 * gwei) + refunds := uint64(19_800) + fullBlock := blockWithReceipts(t, txs, baseFee.Int64(), sumGasUsed(txs)+refunds) + + tip, err := fullBlock.GetProposerTip() + require.NoError(t, err) + + // Worked out by hand at a 7 gwei base fee: legacy 6 gwei, access list + // 4 gwei, dynamic fee 2 gwei (full tip) and 5 gwei (capped by its 12 gwei + // fee cap), blob 3 gwei and set code 1 gwei per unit of gas + expected := big.NewInt(0) + for i, tipGwei := range []int64{6, 4, 2, 5, 3, 1} { + perTx := new(big.Int).Mul(big.NewInt(tipGwei*gwei), new(big.Int).SetUint64(txs[i].gasUsed)) + expected.Add(expected, perTx) + } + require.Equal(t, expected, tip) + + // The former calculation would have burnt the refunds out of the proposer's + // reward, leaving the pool with more ETH than the oracle accounts for + under := new(big.Int).Sub(expected, formerProposerTip(txs, baseFee, sumGasUsed(txs)+refunds)) + require.Equal(t, new(big.Int).Mul(new(big.Int).SetUint64(refunds), baseFee), under) +} + +func Test_GetProposerTip_Errors(t *testing.T) { + key, err := crypto.GenerateKey() + require.NoError(t, err) + txs := txsOfEveryType(t, key) + + t.Run("no receipts", func(t *testing.T) { + fullBlock := blockWithReceipts(t, txs, 7*gwei, sumGasUsed(txs)) + fullBlock.ExecutionReceipts = nil + _, err := fullBlock.GetProposerTip() + require.ErrorContains(t, err, "receipts of full block are nil") + }) + + t.Run("missing receipt", func(t *testing.T) { + fullBlock := blockWithReceipts(t, txs, 7*gwei, sumGasUsed(txs)) + fullBlock.ExecutionReceipts = fullBlock.ExecutionReceipts[1:] + _, err := fullBlock.GetProposerTip() + require.ErrorContains(t, err, "not the same length") + }) + + // Used to return a nil error and a nil tip + t.Run("receipt of another tx", func(t *testing.T) { + fullBlock := blockWithReceipts(t, txs, 7*gwei, sumGasUsed(txs)) + fullBlock.ExecutionReceipts[0].TxHash = common.Hash{0x42} + tip, err := fullBlock.GetProposerTip() + require.ErrorContains(t, err, "tx hash does not match receipt hash") + require.Nil(t, tip) + }) + + t.Run("fee cap below base fee", func(t *testing.T) { + // The capped dynamic fee tx pays at most 12 gwei + fullBlock := blockWithReceipts(t, txs, 20*gwei, sumGasUsed(txs)) + _, err := fullBlock.GetProposerTip() + require.ErrorContains(t, err, "could not get effective tip") + }) +} + +func Test_GetBaseFeePerGasBigInt(t *testing.T) { + key, err := crypto.GenerateKey() + require.NoError(t, err) + fullBlock := blockWithReceipts(t, txsOfEveryType(t, key), 1_234_567_891, 0) + require.Equal(t, big.NewInt(1_234_567_891), fullBlock.GetBaseFeePerGasBigInt()) +} From cc5963f403bdd7a3e6f67cb927a2dbcf3da0cb3b Mon Sep 17 00:00:00 2001 From: Marketen Date: Thu, 22 Oct 2026 17:51:22 +0200 Subject: [PATCH 3/9] Read execution payloads of Gloas slots From Gloas, Glamsterdam's consensus fork, the beacon block no longer carries the execution payload (EIP-7732). It carries a builder's bid, which commits to the payload by its hash, and the builder publishes the payload separately. A slot can now be full, empty (beacon block but no execution payload) or missed. - GloasForkSlot holds the fork slot per chain, only Hoodi for now. The oracle stops at a beacon block whose version doesn't match it, so a chain must be listed before it forks and history is never processed with the wrong rules. - A slot is full when the next beacon block builds on its payload. Its payload is then fetched from the beacon node's envelope endpoint and checked against the bid. Empty slots have no execution block, so no events, txs or receipts are fetched for them. - The FullBlock getters read the payload of Gloas slots, and the code reading the execution block (donations, forced payments, the latest processed block) now also skips empty slots, not only missed ones. - The outcome of a Gloas slot is only settled after it is finalized: its payload's inclusion is decided by the next beacon block, and a withheld payload's payment at the end of the next epoch. The main loop waits until that epoch is finalized, trailing finality by ~1 epoch. Classifying Gloas proposals needs the builder payment, which the next commits add. Until then the oracle stops at the first Gloas proposal rather than classifying it with pre-Gloas rules. Co-Authored-By: Claude Opus 5.5 --- main.go | 5 +- oracle/block.go | 46 +++++- oracle/forced_payment.go | 6 +- oracle/gloas.go | 124 +++++++++++++++ oracle/gloas_onchain.go | 109 ++++++++++++++ oracle/gloas_test.go | 318 +++++++++++++++++++++++++++++++++++++++ oracle/onchain.go | 7 + oracle/oracle.go | 3 +- oracle/types.go | 5 + 9 files changed, 616 insertions(+), 7 deletions(-) create mode 100644 oracle/gloas.go create mode 100644 oracle/gloas_onchain.go create mode 100644 oracle/gloas_test.go diff --git a/main.go b/main.go index b970aea..b3e5e09 100644 --- a/main.go +++ b/main.go @@ -253,7 +253,10 @@ func mainLoop(oracleInstance *oracle.Oracle, onchain *oracle.Onchain, cfg *oracl finalizedSlot := uint64(finalizedBlockHeader.Header.Message.Slot) - if finalizedSlot >= oracleInstance.State().NextSlotToProcess { + // From Gloas on, a slot is only settled some time after it is finalized + settlementSlot := oracle.SettlementSlot(onchain.ChainId, oracleInstance.State().NextSlotToProcess) + + if finalizedSlot >= settlementSlot { // Fetch block information fullBlock := onchain.FetchFullBlock(oracleInstance.State().NextSlotToProcess, oracleInstance) diff --git a/oracle/block.go b/oracle/block.go index 6460396..a05d9d3 100644 --- a/oracle/block.go +++ b/oracle/block.go @@ -9,6 +9,7 @@ import ( v1 "github.com/attestantio/go-eth2-client/api/v1" "github.com/attestantio/go-eth2-client/spec" "github.com/attestantio/go-eth2-client/spec/bellatrix" + "github.com/attestantio/go-eth2-client/spec/capella" "github.com/attestantio/go-eth2-client/spec/phase0" "github.com/dappnode/mev-sp-oracle/contract" "github.com/dappnode/mev-sp-oracle/utils" @@ -190,10 +191,14 @@ func (b *FullBlock) SetConsensusBlock(consensusBlock *spec.VersionedSignedBeacon proposerIndex = uint64(consensusBlock.Electra.Message.ProposerIndex) } else if consensusBlock.Fulu != nil { proposerIndex = uint64(consensusBlock.Fulu.Message.ProposerIndex) + } else if consensusBlock.Gloas != nil { + proposerIndex = uint64(consensusBlock.Gloas.Message.ProposerIndex) } else { log.Fatal("Block was empty, cant get proposer index") } + b.checkGloasForkSlot(consensusBlock.Version, uint64(cBlockSlot)) + // Sanity check if uint64(b.ConsensusDuty.ValidatorIndex) != proposerIndex { log.Fatal("Proposer index mismatch between consensus duty and consensus block: ", @@ -733,8 +738,9 @@ func (b *FullBlock) GetProposerTip() (*big.Int, error) { // This fuction detects both by checking the tx and the EtherReceived event func (b *FullBlock) GetDonations(poolAddress string) []*contract.ContractEtherReceived { - // If the block was missed, there cant be any donations - if b.ConsensusBlock == nil { + // If the block was missed or its execution payload withheld, there is no + // execution block and therefore no donations + if !b.HasExecutionPayload() { return []*contract.ContractEtherReceived{} } @@ -833,6 +839,8 @@ func (b *FullBlock) SummarizedBlock(oracle *Oracle, poolAddress string) Summariz poolBlock.BlockType = MissedProposal return poolBlock + } else if b.IsGloas() { + log.Fatal("Gloas proposals can't be classified yet, slot: ", b.GetSlotUint64()) } else { // Check if the proposer is subscribed to the pool isFromSubscriber := oracle.isSubscribed(b.GetProposerIndexUint64()) @@ -882,6 +890,8 @@ func (b *FullBlock) GetFeeRecipient() string { feeRecipient = b.ConsensusBlock.Electra.Message.Body.ExecutionPayload.FeeRecipient.String() } else if b.ConsensusBlock.Fulu != nil { feeRecipient = b.ConsensusBlock.Fulu.Message.Body.ExecutionPayload.FeeRecipient.String() + } else if b.ConsensusBlock.Gloas != nil { + feeRecipient = b.gloasExecutionPayload().FeeRecipient.String() } else { log.Fatal("Block was empty, cant get fee recipient") } @@ -904,6 +914,8 @@ func (b *FullBlock) GetBlockTransactions() []bellatrix.Transaction { transactions = b.ConsensusBlock.Electra.Message.Body.ExecutionPayload.Transactions } else if b.ConsensusBlock.Fulu != nil { transactions = b.ConsensusBlock.Fulu.Message.Body.ExecutionPayload.Transactions + } else if b.ConsensusBlock.Gloas != nil { + transactions = b.gloasExecutionPayload().Transactions } else { log.Fatal("Block was empty, cant get transactions") } @@ -926,6 +938,8 @@ func (b *FullBlock) GetBlockNumber() uint64 { blockNumber = b.ConsensusBlock.Electra.Message.Body.ExecutionPayload.BlockNumber } else if b.ConsensusBlock.Fulu != nil { blockNumber = b.ConsensusBlock.Fulu.Message.Body.ExecutionPayload.BlockNumber + } else if b.ConsensusBlock.Gloas != nil { + blockNumber = b.gloasExecutionPayload().BlockNumber } else { log.Fatal("Block was empty, cant get block number") } @@ -953,6 +967,8 @@ func (b *FullBlock) GetSlot() phase0.Slot { slot = b.ConsensusBlock.Electra.Message.Slot } else if b.ConsensusBlock.Fulu != nil { slot = b.ConsensusBlock.Fulu.Message.Slot + } else if b.ConsensusBlock.Gloas != nil { + slot = b.ConsensusBlock.Gloas.Message.Slot } else { log.Fatal("Block was empty, cant get slot") } @@ -979,6 +995,8 @@ func (b *FullBlock) GetProposerIndex() phase0.ValidatorIndex { proposerIndex = b.ConsensusBlock.Electra.Message.ProposerIndex } else if b.ConsensusBlock.Fulu != nil { proposerIndex = b.ConsensusBlock.Fulu.Message.ProposerIndex + } else if b.ConsensusBlock.Gloas != nil { + proposerIndex = b.ConsensusBlock.Gloas.Message.ProposerIndex } else { log.Fatal("Block was empty, cant get proposer index") } @@ -1005,6 +1023,8 @@ func (b *FullBlock) GetGasUsed() uint64 { gasUsed = b.ConsensusBlock.Electra.Message.Body.ExecutionPayload.GasUsed } else if b.ConsensusBlock.Fulu != nil { gasUsed = b.ConsensusBlock.Fulu.Message.Body.ExecutionPayload.GasUsed + } else if b.ConsensusBlock.Gloas != nil { + gasUsed = b.gloasExecutionPayload().GasUsed } else { log.Fatal("Block was empty, cant get gas used") } @@ -1044,6 +1064,12 @@ func (b *FullBlock) GetBaseFeePerGas() [32]byte { baseFeePerGas[i] = baseFeePerGasBigEndian[32-1-i] } + } else if b.ConsensusBlock.Gloas != nil { + baseFeePerGasBigEndian := b.gloasExecutionPayload().BaseFeePerGas.Bytes32() + for i := 0; i < 32; i++ { + baseFeePerGas[i] = baseFeePerGasBigEndian[32-1-i] + } + } else { log.Fatal("Block was empty, cant get base fee per gas") } @@ -1060,3 +1086,19 @@ func (b *FullBlock) GetBaseFeePerGasBigInt() *big.Int { } return new(big.Int).SetBytes(bigEndian[:]) } + +// Returns the withdrawals credited by the execution payload, from Capella on +func (b *FullBlock) GetWithdrawals() ([]*capella.Withdrawal, error) { + if b.IsGloas() { + return b.gloasExecutionPayload().Withdrawals, nil + } + return b.ConsensusBlock.Withdrawals() +} + +// Returns the hash of the execution block +func (b *FullBlock) GetExecutionBlockHash() (phase0.Hash32, error) { + if b.IsGloas() { + return b.gloasExecutionPayload().BlockHash, nil + } + return b.ConsensusBlock.ExecutionBlockHash() +} diff --git a/oracle/forced_payment.go b/oracle/forced_payment.go index bbf029d..4575834 100644 --- a/oracle/forced_payment.go +++ b/oracle/forced_payment.go @@ -20,7 +20,7 @@ import ( // candidate. Ambiguous or unsupported inflows stop processing instead of // silently banning a validator or allocating an arbitrary amount. func (o *Onchain) DetectForcedMevPayment(b *FullBlock, opts ...retry.Option) error { - if b.ConsensusBlock == nil || !b.IsForcedPaymentDetectionActive() || + if !b.HasExecutionPayload() || !b.IsForcedPaymentDetectionActive() || !b.IsAnyPositionForcedPaymentDetectionActive() { return nil } @@ -64,7 +64,7 @@ func (o *Onchain) detectAnyPositionForcedMevPayment(b *FullBlock, opts ...retry. // A consensus withdrawal can credit any address, including the pool. It // must not be mistaken for a proposer payment of the same value. if b.ConsensusBlock.Version >= spec.DataVersionCapella { - withdrawals, err := b.ConsensusBlock.Withdrawals() + withdrawals, err := b.GetWithdrawals() if err != nil { return fmt.Errorf("read withdrawals at block %d: %w", blockNumber, err) } @@ -136,7 +136,7 @@ func (o *Onchain) forcedPaymentReceipt(b *FullBlock, tx *types.Transaction, inde return nil, fmt.Errorf("read forced payment receipt %s: %w", tx.Hash(), err) } } - blockHash, err := b.ConsensusBlock.ExecutionBlockHash() + blockHash, err := b.GetExecutionBlockHash() if err != nil { return nil, err } diff --git a/oracle/gloas.go b/oracle/gloas.go new file mode 100644 index 0000000..f8689eb --- /dev/null +++ b/oracle/gloas.go @@ -0,0 +1,124 @@ +package oracle + +import ( + "github.com/attestantio/go-eth2-client/spec" + "github.com/attestantio/go-eth2-client/spec/gloas" + "github.com/dappnode/mev-sp-oracle/constants" + log "github.com/sirupsen/logrus" +) + +// Glamsterdam's consensus fork, Gloas, takes the execution payload out of the +// beacon block (EIP-7732). The beacon block carries a builder's bid instead, +// which commits to the payload by its hash, and the builder publishes the +// payload separately, in an envelope, a few seconds later. So a slot can end: +// - full: its beacon block and its execution payload are part of the chain +// - empty: only its beacon block is. There is no execution block, no txs +// - missed: nothing was proposed, as before Gloas + +// First slot of the Gloas fork on each chain. A chain must be listed before it +// forks: the oracle stops at a Gloas beacon block it can't place rather than +// processing it, so history is never computed with the wrong rules. +var GloasForkSlot = map[uint64]uint64{ + // Epoch 132352, https://blog.ethereum.org/2026/10/16/glamsterdam-hoodi-announcement + HoodiChainId: 4235264, +} + +// Whether the slot belongs to the Gloas fork on the given chain +func IsGloasSlot(chainId uint64, slot uint64) bool { + forkSlot, found := GloasForkSlot[chainId] + return found && slot >= forkSlot +} + +// Returns the slot that must be finalized before the given slot can be +// processed. Before Gloas that is the slot itself. From Gloas on, the outcome of +// a slot is decided later: whether its execution payload was included is decided +// by the next beacon block, and whether a bid whose payload was withheld is still +// paid is decided at the end of the following epoch. Waiting until that epoch is +// finalized covers both, at the cost of trailing finality by about one epoch. +func SettlementSlot(chainId uint64, slot uint64) uint64 { + if !IsGloasSlot(chainId, slot) { + return slot + } + epoch := slot / constants.SlotsInEpoch + return (epoch+2)*constants.SlotsInEpoch - 1 +} + +// Whether the beacon block of this slot is a Gloas one, ie carries a bid +// instead of the execution payload +func (b *FullBlock) IsGloas() bool { + return b.ConsensusBlock != nil && b.ConsensusBlock.Version >= spec.DataVersionGloas +} + +// Whether the slot has an execution payload in the chain, and with it txs, +// events and an execution block number. False for missed and empty slots +func (b *FullBlock) HasExecutionPayload() bool { + if b.ConsensusBlock == nil { + return false + } + return !b.IsGloas() || b.ExecutionPayload != nil +} + +// Returns the bid the proposer included in its beacon block. Only for Gloas +func (b *FullBlock) GetExecutionPayloadBid() *gloas.ExecutionPayloadBid { + if !b.IsGloas() { + log.Fatal("only Gloas beacon blocks carry a bid, slot: ", b.ConsensusDuty.Slot) + } + return b.ConsensusBlock.Gloas.Message.Body.SignedExecutionPayloadBid.Message +} + +// Whether the proposer built its own execution payload instead of picking a +// builder's bid +func (b *FullBlock) IsSelfBuilt() bool { + return b.GetExecutionPayloadBid().BuilderIndex == gloas.BuilderIndexSelfBuild +} + +// Adds the execution payload of a full slot. It must be the payload the bid in +// the beacon block committed to +func (b *FullBlock) SetExecutionPayload(envelope *gloas.ExecutionPayloadEnvelope) { + if envelope == nil || envelope.Payload == nil { + log.Fatal("execution payload envelope can't be nil") + } + + bid := b.GetExecutionPayloadBid() + payload := envelope.Payload + + if payload.BlockHash != bid.BlockHash { + log.Fatal("Execution payload does not match the bid. Payload: ", payload.BlockHash.String(), + " bid: ", bid.BlockHash.String()) + } + if envelope.BuilderIndex != bid.BuilderIndex { + log.Fatal("Execution payload was not published by the builder of the bid. Envelope: ", + envelope.BuilderIndex, " bid: ", bid.BuilderIndex) + } + if payload.SlotNumber != uint64(bid.Slot) { + log.Fatal("Execution payload slot does not match the bid slot: ", payload.SlotNumber, " vs ", bid.Slot) + } + + b.ExecutionPayload = payload +} + +// Returns the execution payload of a Gloas slot. Stops when the slot is empty: +// any caller reaching here should have checked HasExecutionPayload first +func (b *FullBlock) gloasExecutionPayload() *gloas.ExecutionPayload { + if b.ExecutionPayload == nil { + log.Fatal("Slot ", b.ConsensusDuty.Slot, " is empty, it has no execution payload") + } + return b.ExecutionPayload +} + +// Checks that the beacon block version matches the fork the slot belongs to. +// A Gloas beacon block on a chain with no fork slot configured, or with the +// wrong one, means GloasForkSlot has to be updated before processing on +func (b *FullBlock) checkGloasForkSlot(blockVersion spec.DataVersion, slot uint64) { + isGloasBlock := blockVersion >= spec.DataVersionGloas + if isGloasBlock != IsGloasSlot(b.ChainId, slot) { + forkSlot, configured := GloasForkSlot[b.ChainId] + log.WithFields(log.Fields{ + "Slot": slot, + "ChainId": b.ChainId, + "BlockVersion": blockVersion.String(), + "GloasForkSlot": forkSlot, + "GloasForkConfigured": configured, + }).Fatal("Beacon block version does not match the configured Gloas fork slot, update GloasForkSlot") + } +} diff --git a/oracle/gloas_onchain.go b/oracle/gloas_onchain.go new file mode 100644 index 0000000..6a20a2f --- /dev/null +++ b/oracle/gloas_onchain.go @@ -0,0 +1,109 @@ +package oracle + +import ( + "context" + "fmt" + "strconv" + + "github.com/attestantio/go-eth2-client/api" + "github.com/attestantio/go-eth2-client/spec" + "github.com/attestantio/go-eth2-client/spec/gloas" + "github.com/avast/retry-go/v4" + "github.com/pkg/errors" + log "github.com/sirupsen/logrus" +) + +// Returns the execution payload envelope the builder published for the beacon +// block of the given slot +func (o *Onchain) GetExecutionPayloadEnvelope(slot uint64, opts ...retry.Option) (*gloas.ExecutionPayloadEnvelope, error) { + slotStr := strconv.FormatUint(slot, 10) + var envelope *api.Response[*spec.VersionedSignedExecutionPayloadEnvelope] + + err := retry.Do(func() error { + var err error + envelope, err = o.ConsensusClient.SignedExecutionPayloadEnvelope(context.Background(), &api.SignedExecutionPayloadEnvelopeOpts{ + Block: slotStr, + }) + if err != nil { + log.Warn("Failed attempt to fetch execution payload envelope at slot ", slotStr, ": ", err.Error(), " Retrying...") + return errors.Wrap(err, "error fetching execution payload envelope at slot "+slotStr) + } + return nil + }, o.GetRetryOpts(opts)...) + + if err != nil { + return nil, errors.Wrap(err, "could not fetch execution payload envelope at slot "+slotStr) + } + if envelope.Data == nil || envelope.Data.Gloas == nil || envelope.Data.Gloas.Message == nil { + return nil, errors.New("empty execution payload envelope at slot " + slotStr) + } + return envelope.Data.Gloas.Message, nil +} + +// Returns whether the execution payload the bid of the given slot committed to +// became part of the chain, ie whether the slot is full rather than empty +func (o *Onchain) IsExecutionPayloadIncluded(slot uint64, bid *gloas.ExecutionPayloadBid, opts ...retry.Option) (bool, error) { + finalized, err := o.FinalizedBeaconBlockHeader(opts...) + if err != nil { + return false, errors.Wrap(err, "could not get finalized beacon block header") + } + blockAtSlot := func(slot uint64) (*spec.VersionedSignedBeaconBlock, error) { + return o.GetConsensusBlockAtSlot(slot, opts...) + } + return isExecutionPayloadIncluded(slot, uint64(finalized.Header.Message.Slot), bid, blockAtSlot) +} + +// An execution payload is included when the next beacon block builds on it, +// ie when the parent payload of the next bid is this one. Otherwise the next +// bid builds on the payload before it, and this slot is empty. Only finalized +// beacon blocks are considered, so the answer can't be reorged away. +func isExecutionPayloadIncluded( + slot uint64, + finalizedSlot uint64, + bid *gloas.ExecutionPayloadBid, + blockAtSlot func(uint64) (*spec.VersionedSignedBeaconBlock, error)) (bool, error) { + + for nextSlot := slot + 1; nextSlot <= finalizedSlot; nextSlot++ { + nextBlock, err := blockAtSlot(nextSlot) + if err != nil { + return false, errors.Wrap(err, fmt.Sprintf("could not get beacon block at slot %d", nextSlot)) + } + // Missed slot, keep looking + if nextBlock == nil { + continue + } + if nextBlock.Gloas == nil { + return false, errors.New(fmt.Sprintf("beacon block at slot %d is not a Gloas one", nextSlot)) + } + nextBid := nextBlock.Gloas.Message.Body.SignedExecutionPayloadBid.Message + return nextBid.ParentBlockHash == bid.BlockHash, nil + } + return false, errors.New(fmt.Sprintf("no finalized beacon block after slot %d yet, "+ + "cant tell whether its execution payload was included", slot)) +} + +// Completes a Gloas full block with its execution payload. Returns false when +// the slot is empty, in which case there is no execution block to read events, +// txs or receipts from. +func (o *Onchain) fetchGloasExecutionPayload(fullBlock *FullBlock) bool { + slot := fullBlock.GetSlotUint64() + + included, err := o.IsExecutionPayloadIncluded(slot, fullBlock.GetExecutionPayloadBid()) + if err != nil { + log.Fatal("could not tell whether the execution payload of slot ", slot, " was included: ", err) + } + if !included { + log.WithFields(log.Fields{ + "Slot": slot, + "BuilderIndex": fullBlock.GetExecutionPayloadBid().BuilderIndex, + }).Info("Empty slot: the beacon block was proposed but its execution payload was not included") + return false + } + + envelope, err := o.GetExecutionPayloadEnvelope(slot) + if err != nil { + log.Fatal("could not get the execution payload of full slot ", slot, ": ", err) + } + fullBlock.SetExecutionPayload(envelope) + return true +} diff --git a/oracle/gloas_test.go b/oracle/gloas_test.go new file mode 100644 index 0000000..8870e2f --- /dev/null +++ b/oracle/gloas_test.go @@ -0,0 +1,318 @@ +package oracle + +import ( + "errors" + "math/big" + "testing" + + v1 "github.com/attestantio/go-eth2-client/api/v1" + "github.com/attestantio/go-eth2-client/spec" + "github.com/attestantio/go-eth2-client/spec/bellatrix" + "github.com/attestantio/go-eth2-client/spec/capella" + "github.com/attestantio/go-eth2-client/spec/deneb" + "github.com/attestantio/go-eth2-client/spec/electra" + "github.com/attestantio/go-eth2-client/spec/gloas" + "github.com/attestantio/go-eth2-client/spec/phase0" + "github.com/ethereum/go-ethereum/common" + "github.com/holiman/uint256" + log "github.com/sirupsen/logrus" + "github.com/stretchr/testify/require" +) + +// First slot of the Gloas fork on Hoodi, the only chain with a fork slot yet +var testGloasSlot = GloasForkSlot[HoodiChainId] + +// The address of a builder, which builders set as fee recipient of their +// payloads to collect the tips +const testBuilderAddress = "0x4838B106FCe9647Bdf1E7877BF73cE8B0BAD5f97" + +// Runs f expecting it to stop the oracle with log.Fatal. The exit is turned +// into a panic so the test survives it +func requireFatal(t *testing.T, f func()) { + t.Helper() + logger := log.StandardLogger() + previousExit := logger.ExitFunc + logger.ExitFunc = func(int) { panic("log.Fatal") } + defer func() { logger.ExitFunc = previousExit }() + require.PanicsWithValue(t, "log.Fatal", f) +} + +func executionAddress(address string) bellatrix.ExecutionAddress { + var executionAddress bellatrix.ExecutionAddress + copy(executionAddress[:], common.HexToAddress(address).Bytes()) + return executionAddress +} + +// A bid of the given builder paying valueGwei to feeRecipient. Its payload +// builds on the payload with hash parentHash, and has hash blockHash +func gloasBid(slot uint64, builderIndex gloas.BuilderIndex, valueGwei uint64, feeRecipient string, + parentHash byte, blockHash byte) *gloas.ExecutionPayloadBid { + return &gloas.ExecutionPayloadBid{ + Slot: phase0.Slot(slot), + BuilderIndex: builderIndex, + Value: phase0.Gwei(valueGwei), + FeeRecipient: executionAddress(feeRecipient), + ParentBlockHash: phase0.Hash32{parentHash}, + BlockHash: phase0.Hash32{blockHash}, + } +} + +// A Gloas beacon block on Hoodi, proposed by validatorIndex and carrying bid +func gloasBeaconBlock(slot uint64, validatorIndex phase0.ValidatorIndex, bid *gloas.ExecutionPayloadBid) *spec.VersionedSignedBeaconBlock { + return &spec.VersionedSignedBeaconBlock{ + Version: spec.DataVersionGloas, + Gloas: &gloas.SignedBeaconBlock{Message: &gloas.BeaconBlock{ + Slot: phase0.Slot(slot), + ProposerIndex: validatorIndex, + Body: &gloas.BeaconBlockBody{ + SignedExecutionPayloadBid: &gloas.SignedExecutionPayloadBid{Message: bid}, + }, + }}, + } +} + +// A FullBlock for a Gloas slot whose payload has not been set yet, ie that is +// empty until SetExecutionPayload is called. The proposer has 0x01 credentials +func gloasFullBlock(t *testing.T, slot uint64, validatorIndex phase0.ValidatorIndex, bid *gloas.ExecutionPayloadBid) *FullBlock { + t.Helper() + credentials := make([]byte, 32) + credentials[0] = 1 + copy(credentials[12:], common.HexToAddress("0x1111111111111111111111111111111111111111").Bytes()) + + fullBlock := NewFullBlock(&v1.ProposerDuty{Slot: phase0.Slot(slot), ValidatorIndex: validatorIndex}, + &v1.Validator{Index: validatorIndex, Validator: &phase0.Validator{WithdrawalCredentials: credentials}}, + HoodiChainId) + fullBlock.SetConsensusBlock(gloasBeaconBlock(slot, validatorIndex, bid)) + return fullBlock +} + +// The envelope the builder of bid publishes, with the given execution payload +// contents +func gloasEnvelope(bid *gloas.ExecutionPayloadBid, blockNumber uint64, feeRecipient string, + txs []bellatrix.Transaction, withdrawals []*capella.Withdrawal) *gloas.ExecutionPayloadEnvelope { + return &gloas.ExecutionPayloadEnvelope{ + BuilderIndex: bid.BuilderIndex, + Payload: &gloas.ExecutionPayload{ + BlockHash: bid.BlockHash, + SlotNumber: uint64(bid.Slot), + BlockNumber: blockNumber, + FeeRecipient: executionAddress(feeRecipient), + GasUsed: 1_500_000, + BaseFeePerGas: uint256.NewInt(7_000_000_000), + Transactions: txs, + Withdrawals: withdrawals, + }, + } +} + +func Test_IsGloasSlot(t *testing.T) { + require.False(t, IsGloasSlot(HoodiChainId, testGloasSlot-1)) + require.True(t, IsGloasSlot(HoodiChainId, testGloasSlot)) + require.True(t, IsGloasSlot(HoodiChainId, testGloasSlot+100_000)) + + // Not scheduled on mainnet yet + require.False(t, IsGloasSlot(MainnetChainId, 20_000_000)) +} + +func Test_SettlementSlot(t *testing.T) { + // Before Gloas a finalized slot is settled + require.Equal(t, testGloasSlot-1, SettlementSlot(HoodiChainId, testGloasSlot-1)) + require.Equal(t, uint64(20_000_000), SettlementSlot(MainnetChainId, 20_000_000)) + + // From Gloas on, wait until the epoch after the slot's one is finalized. + // The fork slot is the first of epoch 132352 + require.Equal(t, uint64(132352*32), testGloasSlot) + lastSlotOfNextEpoch := uint64(132354*32 - 1) + require.Equal(t, lastSlotOfNextEpoch, SettlementSlot(HoodiChainId, testGloasSlot)) + require.Equal(t, lastSlotOfNextEpoch, SettlementSlot(HoodiChainId, testGloasSlot+17)) + require.Equal(t, lastSlotOfNextEpoch, SettlementSlot(HoodiChainId, testGloasSlot+31)) + require.Equal(t, lastSlotOfNextEpoch+32, SettlementSlot(HoodiChainId, testGloasSlot+32)) +} + +func Test_GloasBlock_FullSlot(t *testing.T) { + bid := gloasBid(testGloasSlot, 42, 48_200_000, testPoolAddress, 0xaa, 0xbb) + fullBlock := gloasFullBlock(t, testGloasSlot, 1000, bid) + + require.True(t, fullBlock.IsGloas()) + require.False(t, fullBlock.IsSelfBuilt()) + require.Equal(t, bid, fullBlock.GetExecutionPayloadBid()) + require.Equal(t, phase0.ValidatorIndex(1000), fullBlock.GetProposerIndex()) + require.Equal(t, testGloasSlot, fullBlock.GetSlotUint64()) + + withdrawals := []*capella.Withdrawal{{Index: 9, ValidatorIndex: 3, Address: executionAddress(testPoolAddress), Amount: 5}} + txs := []bellatrix.Transaction{{0x01}, {0x02}} + fullBlock.SetExecutionPayload(gloasEnvelope(bid, 5000, testBuilderAddress, txs, withdrawals)) + + require.True(t, fullBlock.HasExecutionPayload()) + require.Equal(t, testBuilderAddress, fullBlock.GetFeeRecipient()) + require.Equal(t, uint64(5000), fullBlock.GetBlockNumber()) + require.Equal(t, uint64(1_500_000), fullBlock.GetGasUsed()) + require.Equal(t, big.NewInt(7_000_000_000), fullBlock.GetBaseFeePerGasBigInt()) + require.Equal(t, txs, fullBlock.GetBlockTransactions()) + + gotWithdrawals, err := fullBlock.GetWithdrawals() + require.NoError(t, err) + require.Equal(t, withdrawals, gotWithdrawals) + + blockHash, err := fullBlock.GetExecutionBlockHash() + require.NoError(t, err) + require.Equal(t, bid.BlockHash, blockHash) +} + +func Test_GloasBlock_EmptySlot(t *testing.T) { + bid := gloasBid(testGloasSlot, 42, 48_200_000, testPoolAddress, 0xaa, 0xbb) + fullBlock := gloasFullBlock(t, testGloasSlot, 1000, bid) + + require.True(t, fullBlock.IsGloas()) + require.False(t, fullBlock.HasExecutionPayload()) + require.Empty(t, fullBlock.GetDonations(testPoolAddress)) + + // Reading the execution block of an empty slot is a bug in the caller + requireFatal(t, func() { fullBlock.GetBlockNumber() }) + requireFatal(t, func() { fullBlock.GetFeeRecipient() }) +} + +func Test_GloasBlock_SelfBuilt(t *testing.T) { + bid := gloasBid(testGloasSlot, gloas.BuilderIndexSelfBuild, 0, testPoolAddress, 0xaa, 0xbb) + fullBlock := gloasFullBlock(t, testGloasSlot, 1000, bid) + require.True(t, fullBlock.IsSelfBuilt()) +} + +func Test_HasExecutionPayload_BeforeGloas(t *testing.T) { + missed := NewFullBlock(&v1.ProposerDuty{Slot: 100, ValidatorIndex: 7}, + &v1.Validator{Index: 7, Validator: &phase0.Validator{}}, MainnetChainId) + require.False(t, missed.HasExecutionPayload()) + require.False(t, missed.IsGloas()) + + proposed := buildMevBlock(t, 100, 1000, 7, testPoolAddress, big.NewInt(1)) + require.True(t, proposed.HasExecutionPayload()) + require.False(t, proposed.IsGloas()) +} + +func Test_SetExecutionPayload_MustMatchTheBid(t *testing.T) { + bid := gloasBid(testGloasSlot, 42, 48_200_000, testPoolAddress, 0xaa, 0xbb) + + tests := []struct { + name string + mutate func(*gloas.ExecutionPayloadEnvelope) + }{ + {"other payload", func(e *gloas.ExecutionPayloadEnvelope) { e.Payload.BlockHash = phase0.Hash32{0xcc} }}, + {"other builder", func(e *gloas.ExecutionPayloadEnvelope) { e.BuilderIndex = 43 }}, + {"other slot", func(e *gloas.ExecutionPayloadEnvelope) { e.Payload.SlotNumber++ }}, + {"no payload", func(e *gloas.ExecutionPayloadEnvelope) { e.Payload = nil }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + fullBlock := gloasFullBlock(t, testGloasSlot, 1000, bid) + envelope := gloasEnvelope(bid, 5000, testBuilderAddress, nil, nil) + tt.mutate(envelope) + requireFatal(t, func() { fullBlock.SetExecutionPayload(envelope) }) + require.False(t, fullBlock.HasExecutionPayload()) + }) + } +} + +// The oracle must stop on a beacon block that doesn't match the configured +// fork, instead of applying the wrong rules to it +func Test_SetConsensusBlock_ChecksGloasForkSlot(t *testing.T) { + duty := func(slot uint64) *v1.ProposerDuty { + return &v1.ProposerDuty{Slot: phase0.Slot(slot), ValidatorIndex: 7} + } + validator := &v1.Validator{Index: 7, Validator: &phase0.Validator{}} + bid := gloasBid(testGloasSlot, 42, 1, testPoolAddress, 0xaa, 0xbb) + + t.Run("Gloas block on a chain without a fork slot", func(t *testing.T) { + fullBlock := NewFullBlock(duty(testGloasSlot), validator, MainnetChainId) + requireFatal(t, func() { fullBlock.SetConsensusBlock(gloasBeaconBlock(testGloasSlot, 7, bid)) }) + }) + + t.Run("Gloas block before the fork slot", func(t *testing.T) { + fullBlock := NewFullBlock(duty(testGloasSlot-1), validator, HoodiChainId) + requireFatal(t, func() { fullBlock.SetConsensusBlock(gloasBeaconBlock(testGloasSlot-1, 7, bid)) }) + }) + + t.Run("Fulu block after the fork slot", func(t *testing.T) { + fullBlock := NewFullBlock(duty(testGloasSlot), validator, HoodiChainId) + fuluBlock := &spec.VersionedSignedBeaconBlock{Version: spec.DataVersionFulu, + Fulu: &electra.SignedBeaconBlock{Message: &electra.BeaconBlock{Slot: phase0.Slot(testGloasSlot), ProposerIndex: 7, + Body: &electra.BeaconBlockBody{ExecutionPayload: &deneb.ExecutionPayload{}}}}} + requireFatal(t, func() { fullBlock.SetConsensusBlock(fuluBlock) }) + }) + + t.Run("Gloas block from the fork slot", func(t *testing.T) { + fullBlock := NewFullBlock(duty(testGloasSlot), validator, HoodiChainId) + fullBlock.SetConsensusBlock(gloasBeaconBlock(testGloasSlot, 7, bid)) + require.True(t, fullBlock.IsGloas()) + }) +} + +func Test_IsExecutionPayloadIncluded(t *testing.T) { + slot := testGloasSlot + 10 + bid := gloasBid(slot, 42, 1, testPoolAddress, 0xaa, 0xbb) + + // Next bids either build on this slot's payload (0xbb) or skip it, building + // on the payload this slot built on (0xaa) + buildsOnThisPayload := gloasBeaconBlock(slot+1, 8, gloasBid(slot+1, 43, 1, testPoolAddress, 0xbb, 0xcc)) + skipsThisPayload := gloasBeaconBlock(slot+1, 8, gloasBid(slot+1, 43, 1, testPoolAddress, 0xaa, 0xcc)) + + chain := func(blocks map[uint64]*spec.VersionedSignedBeaconBlock) func(uint64) (*spec.VersionedSignedBeaconBlock, error) { + return func(slot uint64) (*spec.VersionedSignedBeaconBlock, error) { + return blocks[slot], nil + } + } + + t.Run("next beacon block builds on the payload", func(t *testing.T) { + included, err := isExecutionPayloadIncluded(slot, slot+64, bid, chain(map[uint64]*spec.VersionedSignedBeaconBlock{ + slot + 1: buildsOnThisPayload, + })) + require.NoError(t, err) + require.True(t, included) + }) + + t.Run("next beacon block skips the payload", func(t *testing.T) { + included, err := isExecutionPayloadIncluded(slot, slot+64, bid, chain(map[uint64]*spec.VersionedSignedBeaconBlock{ + slot + 1: skipsThisPayload, + })) + require.NoError(t, err) + require.False(t, included) + }) + + t.Run("missed slots are skipped until the next beacon block", func(t *testing.T) { + buildsAfterMissedSlots := gloasBeaconBlock(slot+4, 8, gloasBid(slot+4, 43, 1, testPoolAddress, 0xbb, 0xcc)) + included, err := isExecutionPayloadIncluded(slot, slot+64, bid, chain(map[uint64]*spec.VersionedSignedBeaconBlock{ + slot + 4: buildsAfterMissedSlots, + })) + require.NoError(t, err) + require.True(t, included) + }) + + t.Run("only the first next beacon block decides", func(t *testing.T) { + included, err := isExecutionPayloadIncluded(slot, slot+64, bid, chain(map[uint64]*spec.VersionedSignedBeaconBlock{ + slot + 1: skipsThisPayload, + slot + 2: gloasBeaconBlock(slot+2, 9, gloasBid(slot+2, 44, 1, testPoolAddress, 0xbb, 0xdd)), + })) + require.NoError(t, err) + require.False(t, included) + }) + + t.Run("no finalized beacon block after the slot yet", func(t *testing.T) { + _, err := isExecutionPayloadIncluded(slot, slot+3, bid, chain(map[uint64]*spec.VersionedSignedBeaconBlock{ + slot + 4: buildsOnThisPayload, + })) + require.ErrorContains(t, err, "no finalized beacon block after slot") + }) + + t.Run("beacon node error", func(t *testing.T) { + _, err := isExecutionPayloadIncluded(slot, slot+64, bid, func(uint64) (*spec.VersionedSignedBeaconBlock, error) { + return nil, errors.New("connection refused") + }) + require.ErrorContains(t, err, "connection refused") + }) + + t.Run("next beacon block is not a Gloas one", func(t *testing.T) { + _, err := isExecutionPayloadIncluded(slot, slot+64, bid, chain(map[uint64]*spec.VersionedSignedBeaconBlock{ + slot + 1: {Version: spec.DataVersionFulu, Fulu: &electra.SignedBeaconBlock{}}, + })) + require.ErrorContains(t, err, "not a Gloas one") + }) +} diff --git a/oracle/onchain.go b/oracle/onchain.go index 0283473..acf8008 100644 --- a/oracle/onchain.go +++ b/oracle/onchain.go @@ -1041,6 +1041,13 @@ func (o *Onchain) FetchFullBlock(slot uint64, oracle *Oracle, opt ...bool) *Full log.Fatal("slot does not match requested slot: ", fullBlock.GetSlotUint64(), " vs ", slot) } + // From Gloas on, the beacon block carries a bid and the execution payload + // is published separately. An empty slot has no execution block, so + // there are no events, txs or receipts to fetch + if fullBlock.IsGloas() && !o.fetchGloasExecutionPayload(fullBlock) { + return fullBlock + } + etherReceived, err := o.GetEtherReceivedEvents(fullBlock.GetBlockNumber()) if err != nil { log.Fatal("failed getting ether received events: ", err) diff --git a/oracle/oracle.go b/oracle/oracle.go index 2aee065..f4793bb 100644 --- a/oracle/oracle.go +++ b/oracle/oracle.go @@ -251,7 +251,8 @@ func (or *Oracle) AdvanceStateToNextSlot(fullBlock *FullBlock) (uint64, error) { processedSlot := or.state.NextSlotToProcess or.state.LatestProcessedSlot = processedSlot or.state.NextSlotToProcess++ - if summarizedBlock.BlockType != MissedProposal { + // Missed and empty slots have no execution block + if fullBlock.HasExecutionPayload() { or.state.LatestProcessedBlock = summarizedBlock.Block } return processedSlot, nil diff --git a/oracle/types.go b/oracle/types.go index 2c3e547..c799105 100644 --- a/oracle/types.go +++ b/oracle/types.go @@ -7,6 +7,7 @@ import ( api "github.com/attestantio/go-eth2-client/api/v1" v1 "github.com/attestantio/go-eth2-client/api/v1" "github.com/attestantio/go-eth2-client/spec" + "github.com/attestantio/go-eth2-client/spec/gloas" "github.com/dappnode/mev-sp-oracle/contract" "github.com/ethereum/go-ethereum/core/types" "github.com/pkg/errors" @@ -159,6 +160,10 @@ type FullBlock struct { // consensus data: block (optional, only when not missed) ConsensusBlock *spec.VersionedSignedBeaconBlock `json:"consensus_block"` + // execution payload, Gloas only: published separately from the beacon + // block, see gloas.go. Nil when the slot is empty + ExecutionPayload *gloas.ExecutionPayload `json:"execution_payload,omitempty"` + // execution data: txs (optional, only when interested in vanila reward) ExecutionHeader *types.Header `json:"execution_header"` ExecutionReceipts []*types.Receipt `json:"execution_receipts"` From 41174d80c0735bc4a096c912a74ddd0b9751fa10 Mon Sep 17 00:00:00 2001 From: Marketen Date: Thu, 22 Oct 2026 17:54:29 +0200 Subject: [PATCH 4/9] Decide whether the bid of a Gloas slot pays the pool From Gloas, a builder's bid promises a payment to the proposer's fee recipient, which the protocol takes from the builder's deposit. It is paid when the next beacon block builds on the bid's execution payload. When the payload is withheld, the protocol still pays it if the beacon block got 60% of its slot's stake in same-slot votes, deciding it in the epoch transition after the next epoch. Slashing the proposer cancels a payment not decided yet. The oracle reproduces that decision instead of trusting it: it reads the builder pending payments and the total active balance from the beacon state right before the transition, at the last slot of the next epoch, and applies the spec's quorum. Effective balances only change after the payments are decided, so the quorum is the one the protocol used. The active set is heavy to fetch, so this only happens for empty slots whose bid paid the pool. Only payments to the pool are recorded, in FullBlock.BuilderPayment. Nothing uses them yet; the next commits classify proposals and track the payments until they reach the pool. Co-Authored-By: Claude Opus 5.5 --- oracle/gloas.go | 84 ++++++++++++++ oracle/gloas_onchain.go | 139 ++++++++++++++++++++++- oracle/gloas_payment_test.go | 208 +++++++++++++++++++++++++++++++++++ oracle/onchain.go | 2 +- oracle/types.go | 23 ++++ utils/utils.go | 5 + utils/utils_test.go | 7 ++ 7 files changed, 461 insertions(+), 7 deletions(-) create mode 100644 oracle/gloas_payment_test.go diff --git a/oracle/gloas.go b/oracle/gloas.go index f8689eb..d2dd825 100644 --- a/oracle/gloas.go +++ b/oracle/gloas.go @@ -1,9 +1,14 @@ package oracle import ( + "fmt" + "github.com/attestantio/go-eth2-client/spec" "github.com/attestantio/go-eth2-client/spec/gloas" + "github.com/attestantio/go-eth2-client/spec/phase0" "github.com/dappnode/mev-sp-oracle/constants" + "github.com/dappnode/mev-sp-oracle/utils" + "github.com/pkg/errors" log "github.com/sirupsen/logrus" ) @@ -39,10 +44,69 @@ func SettlementSlot(chainId uint64, slot uint64) uint64 { if !IsGloasSlot(chainId, slot) { return slot } + return builderPaymentDecisionSlot(slot) +} + +// The last slot of the epoch after the given slot's one. The protocol decides +// whether a withheld payload's bid is paid in the epoch transition right after +// it, so its beacon state holds what that decision is based on +func builderPaymentDecisionSlot(slot uint64) uint64 { epoch := slot / constants.SlotsInEpoch return (epoch+2)*constants.SlotsInEpoch - 1 } +// BUILDER_PAYMENT_THRESHOLD_NUMERATOR and DENOMINATOR in the Gloas spec: the +// share of a slot's stake that must vote for a beacon block in its own slot for +// its bid to be paid when the payload is withheld +const ( + builderPaymentThresholdNumerator = 6 + builderPaymentThresholdDenominator = 10 +) + +// EFFECTIVE_BALANCE_INCREMENT, the floor of the total active balance +const effectiveBalanceIncrement = phase0.Gwei(1_000_000_000) + +// get_builder_payment_quorum_threshold in the Gloas spec +func builderPaymentQuorum(totalActiveBalance phase0.Gwei) phase0.Gwei { + perSlotBalance := max(totalActiveBalance, effectiveBalanceIncrement) / phase0.Gwei(constants.SlotsInEpoch) + return perSlotBalance * builderPaymentThresholdNumerator / builderPaymentThresholdDenominator +} + +// Whether the protocol pays a bid whose execution payload was withheld. It +// does if the votes its beacon block got in its own slot reach the quorum, +// unless the payment was cancelled before, as slashing the proposer does. +// +// pendingPayments and totalActiveBalance must come from the beacon state at +// builderPaymentDecisionSlot, which is just before the protocol decides it in +// process_builder_pending_payments. Effective balances only change after that +// step, so the quorum calculated here is the one the protocol uses. +func isWithheldBidPaid(bid *gloas.ExecutionPayloadBid, proposerIndex phase0.ValidatorIndex, + pendingPayments []*gloas.BuilderPendingPayment, totalActiveBalance phase0.Gwei) (bool, error) { + + if uint64(len(pendingPayments)) != 2*constants.SlotsInEpoch { + return false, errors.New(fmt.Sprintf("expected %d builder pending payments, got %d", + 2*constants.SlotsInEpoch, len(pendingPayments))) + } + + // The first half holds the payments of the previous epoch, the bid's one + payment := pendingPayments[uint64(bid.Slot)%constants.SlotsInEpoch] + + // An empty entry means the payment was cancelled + if payment == nil || payment.Withdrawal == nil || payment.Withdrawal.Amount == 0 { + return false, nil + } + + if payment.Withdrawal.BuilderIndex != bid.BuilderIndex || + payment.Withdrawal.Amount != bid.Value || + payment.Withdrawal.FeeRecipient != bid.FeeRecipient || + payment.ProposerIndex != proposerIndex { + return false, errors.New(fmt.Sprintf("builder pending payment of slot %d does not match its bid. "+ + "payment: %s, bid: %s", bid.Slot, payment.String(), bid.String())) + } + + return payment.Weight >= builderPaymentQuorum(totalActiveBalance), nil +} + // Whether the beacon block of this slot is a Gloas one, ie carries a bid // instead of the execution payload func (b *FullBlock) IsGloas() bool { @@ -72,6 +136,26 @@ func (b *FullBlock) IsSelfBuilt() bool { return b.GetExecutionPayloadBid().BuilderIndex == gloas.BuilderIndexSelfBuild } +// Whether the bid promised a payment to the given address. A self-built +// payload promises none, its proposer collects the tips instead +func (b *FullBlock) BidPromisesPaymentTo(address string) bool { + bid := b.GetExecutionPayloadBid() + return !b.IsSelfBuilt() && bid.Value > 0 && utils.Equals(bid.FeeRecipient.String(), address) +} + +// Records the payment the bid promised to the pool, and whether the protocol +// pays it +func (b *FullBlock) SetBuilderPayment(paid bool) { + bid := b.GetExecutionPayloadBid() + b.BuilderPayment = &BuilderPayment{ + Slot: uint64(bid.Slot), + ProposerIndex: b.GetProposerIndexUint64(), + BuilderIndex: uint64(bid.BuilderIndex), + AmountWei: utils.GweiToWei(uint64(bid.Value)), + Paid: paid, + } +} + // Adds the execution payload of a full slot. It must be the payload the bid in // the beacon block committed to func (b *FullBlock) SetExecutionPayload(envelope *gloas.ExecutionPayloadEnvelope) { diff --git a/oracle/gloas_onchain.go b/oracle/gloas_onchain.go index 6a20a2f..15811d7 100644 --- a/oracle/gloas_onchain.go +++ b/oracle/gloas_onchain.go @@ -2,12 +2,17 @@ package oracle import ( "context" + "encoding/json" "fmt" + "io" + "net/http" "strconv" "github.com/attestantio/go-eth2-client/api" + v1 "github.com/attestantio/go-eth2-client/api/v1" "github.com/attestantio/go-eth2-client/spec" "github.com/attestantio/go-eth2-client/spec/gloas" + "github.com/attestantio/go-eth2-client/spec/phase0" "github.com/avast/retry-go/v4" "github.com/pkg/errors" log "github.com/sirupsen/logrus" @@ -82,20 +87,39 @@ func isExecutionPayloadIncluded( "cant tell whether its execution payload was included", slot)) } -// Completes a Gloas full block with its execution payload. Returns false when -// the slot is empty, in which case there is no execution block to read events, -// txs or receipts from. -func (o *Onchain) fetchGloasExecutionPayload(fullBlock *FullBlock) bool { +// Completes a Gloas full block with what happened to its bid: whether its +// execution payload was included, and whether the payment it promised to the +// pool is paid. Returns false when the slot is empty, in which case there is +// no execution block to read events, txs or receipts from. +func (o *Onchain) fetchGloasSlot(fullBlock *FullBlock) bool { slot := fullBlock.GetSlotUint64() + bid := fullBlock.GetExecutionPayloadBid() - included, err := o.IsExecutionPayloadIncluded(slot, fullBlock.GetExecutionPayloadBid()) + included, err := o.IsExecutionPayloadIncluded(slot, bid) if err != nil { log.Fatal("could not tell whether the execution payload of slot ", slot, " was included: ", err) } + + if fullBlock.BidPromisesPaymentTo(o.PoolAddress) { + // A payload the next beacon block builds on is paid: that block settles + // the payment before processing anything else. Before that, only the + // proposer's slashing included in its own beacon block could cancel it, + // which no proposer would do. If it ever happened, the payment would + // never arrive and the onchain reconciliation would stop the oracle + paid := included + if !included { + paid, err = o.IsWithheldBidPaid(fullBlock) + if err != nil { + log.Fatal("could not tell whether the withheld bid of slot ", slot, " is paid: ", err) + } + } + fullBlock.SetBuilderPayment(paid) + } + if !included { log.WithFields(log.Fields{ "Slot": slot, - "BuilderIndex": fullBlock.GetExecutionPayloadBid().BuilderIndex, + "BuilderIndex": bid.BuilderIndex, }).Info("Empty slot: the beacon block was proposed but its execution payload was not included") return false } @@ -107,3 +131,106 @@ func (o *Onchain) fetchGloasExecutionPayload(fullBlock *FullBlock) bool { fullBlock.SetExecutionPayload(envelope) return true } + +// Returns whether the protocol pays the bid of an empty slot, reading the +// beacon state the protocol bases that decision on. See isWithheldBidPaid +func (o *Onchain) IsWithheldBidPaid(fullBlock *FullBlock, opts ...retry.Option) (bool, error) { + stateID := strconv.FormatUint(builderPaymentDecisionSlot(fullBlock.GetSlotUint64()), 10) + + pendingPayments, err := o.GetBuilderPendingPayments(stateID, opts...) + if err != nil { + return false, err + } + totalActiveBalance, err := o.GetTotalActiveBalance(stateID, opts...) + if err != nil { + return false, err + } + return isWithheldBidPaid(fullBlock.GetExecutionPayloadBid(), fullBlock.GetProposerIndex(), pendingPayments, totalActiveBalance) +} + +// Returns the builder payments of the last two epochs at the given beacon +// state. go-eth2-client has no call for this endpoint yet +func (o *Onchain) GetBuilderPendingPayments(stateID string, opts ...retry.Option) ([]*gloas.BuilderPendingPayment, error) { + var payments []*gloas.BuilderPendingPayment + err := retry.Do(func() error { + var err error + payments, err = fetchBuilderPendingPayments(o.ConsensusClient.Address(), stateID) + if err != nil { + log.Warn("Failed attempt to fetch builder pending payments at state ", stateID, ": ", err.Error(), " Retrying...") + } + return err + }, o.GetRetryOpts(opts)...) + + if err != nil { + return nil, errors.Wrap(err, "could not fetch builder pending payments at state "+stateID) + } + return payments, nil +} + +func fetchBuilderPendingPayments(beaconNodeUrl string, stateID string) ([]*gloas.BuilderPendingPayment, error) { + url := fmt.Sprintf("%s/eth/v1/beacon/states/%s/builder_pending_payments", beaconNodeUrl, stateID) + req, err := http.NewRequest(http.MethodGet, url, nil) + if err != nil { + return nil, errors.Wrap(err, "could not create request") + } + req.Header.Set("Accept", "application/json") + + resp, err := http.DefaultClient.Do(req) + if err != nil { + return nil, errors.Wrap(err, "request failed") + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(resp.Body) + return nil, errors.New(fmt.Sprintf("non-200 response: %d - %s", resp.StatusCode, string(body))) + } + + var response struct { + Data []*gloas.BuilderPendingPayment `json:"data"` + } + if err := json.NewDecoder(resp.Body).Decode(&response); err != nil { + return nil, errors.Wrap(err, "could not decode response") + } + return response.Data, nil +} + +// Returns the sum of the effective balances of the validators active at the +// given beacon state, ie get_total_active_balance in the spec. It fetches the +// whole active set, which is heavy, so it is only meant for empty slots whose +// bid promised a payment to the pool. +func (o *Onchain) GetTotalActiveBalance(stateID string, opts ...retry.Option) (phase0.Gwei, error) { + var validators *api.Response[map[phase0.ValidatorIndex]*v1.Validator] + err := retry.Do(func() error { + var err error + validators, err = o.ConsensusClient.Validators(context.Background(), &api.ValidatorsOpts{ + State: stateID, + ValidatorStates: []v1.ValidatorState{ + v1.ValidatorStateActiveOngoing, + v1.ValidatorStateActiveExiting, + v1.ValidatorStateActiveSlashed, + }, + }) + if err != nil { + log.Warn("Failed attempt to fetch active validators at state ", stateID, ": ", err.Error(), " Retrying...") + } + return err + }, o.GetRetryOpts(opts)...) + + if err != nil { + return 0, errors.Wrap(err, "could not fetch active validators at state "+stateID) + } + return totalActiveBalance(validators.Data), nil +} + +// Sums the effective balances of the active validators. The beacon node was +// asked for active ones only, but filtering again costs nothing +func totalActiveBalance(validators map[phase0.ValidatorIndex]*v1.Validator) phase0.Gwei { + total := phase0.Gwei(0) + for _, validator := range validators { + if validator.Status.IsActive() { + total += validator.Validator.EffectiveBalance + } + } + return total +} diff --git a/oracle/gloas_payment_test.go b/oracle/gloas_payment_test.go new file mode 100644 index 0000000..9360f98 --- /dev/null +++ b/oracle/gloas_payment_test.go @@ -0,0 +1,208 @@ +package oracle + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + v1 "github.com/attestantio/go-eth2-client/api/v1" + "github.com/attestantio/go-eth2-client/spec/gloas" + "github.com/attestantio/go-eth2-client/spec/phase0" + "github.com/dappnode/mev-sp-oracle/constants" + "github.com/stretchr/testify/require" +) + +const ethInGwei = phase0.Gwei(1_000_000_000) + +func Test_BuilderPaymentQuorum(t *testing.T) { + // 38.4M ETH active is 1.2M ETH per slot, of which 60% is 720k ETH + require.Equal(t, 720_000*ethInGwei, builderPaymentQuorum(38_400_000*ethInGwei)) + + // Integer division as in the spec: per slot first, then the ratio. + // 1000000000031 / 32 = 31250000000 (rounded down), * 6 / 10 = 18750000000 + require.Equal(t, phase0.Gwei(18_750_000_000), builderPaymentQuorum(1_000_000_000_031)) + + // The total active balance has a floor of one effective balance increment + require.Equal(t, phase0.Gwei(18_750_000), builderPaymentQuorum(0)) + require.Equal(t, builderPaymentQuorum(0), builderPaymentQuorum(effectiveBalanceIncrement)) +} + +func Test_BuilderPaymentDecisionSlot(t *testing.T) { + // Last slot of the epoch after the slot's one, for any slot of the epoch + require.Equal(t, uint64(95), builderPaymentDecisionSlot(32)) + require.Equal(t, uint64(95), builderPaymentDecisionSlot(63)) + require.Equal(t, uint64(127), builderPaymentDecisionSlot(64)) +} + +// The builder pending payments vector at the decision state: the first half is +// the previous epoch, where the withheld bid sits, the second the current one +func pendingPaymentsWith(slot uint64, payment *gloas.BuilderPendingPayment) []*gloas.BuilderPendingPayment { + payments := make([]*gloas.BuilderPendingPayment, 2*constants.SlotsInEpoch) + for i := range payments { + payments[i] = &gloas.BuilderPendingPayment{Withdrawal: &gloas.BuilderPendingWithdrawal{}} + } + payments[slot%constants.SlotsInEpoch] = payment + return payments +} + +func Test_IsWithheldBidPaid(t *testing.T) { + slot := testGloasSlot + 5 + proposer := phase0.ValidatorIndex(1000) + bid := gloasBid(slot, 42, 48_200_000, testPoolAddress, 0xaa, 0xbb) + totalActive := 38_400_000 * ethInGwei + quorum := builderPaymentQuorum(totalActive) + + paymentWithWeight := func(weight phase0.Gwei) *gloas.BuilderPendingPayment { + return &gloas.BuilderPendingPayment{ + Weight: weight, + ProposerIndex: proposer, + Withdrawal: &gloas.BuilderPendingWithdrawal{ + FeeRecipient: bid.FeeRecipient, + Amount: bid.Value, + BuilderIndex: bid.BuilderIndex, + }, + } + } + + tests := []struct { + name string + payments []*gloas.BuilderPendingPayment + paid bool + err string + }{ + {"votes below the quorum", pendingPaymentsWith(slot, paymentWithWeight(quorum-1)), false, ""}, + {"votes at the quorum", pendingPaymentsWith(slot, paymentWithWeight(quorum)), true, ""}, + {"votes above the quorum", pendingPaymentsWith(slot, paymentWithWeight(quorum*2)), true, ""}, + // Slashing the proposer empties its pending payments + {"cancelled payment", pendingPaymentsWith(slot, &gloas.BuilderPendingPayment{ + Weight: quorum * 2, Withdrawal: &gloas.BuilderPendingWithdrawal{}}), false, ""}, + {"no withdrawal", pendingPaymentsWith(slot, &gloas.BuilderPendingPayment{Weight: quorum * 2}), false, ""}, + {"other builder", pendingPaymentsWith(slot, func() *gloas.BuilderPendingPayment { + p := paymentWithWeight(quorum) + p.Withdrawal.BuilderIndex = 43 + return p + }()), false, "does not match its bid"}, + {"other amount", pendingPaymentsWith(slot, func() *gloas.BuilderPendingPayment { + p := paymentWithWeight(quorum) + p.Withdrawal.Amount++ + return p + }()), false, "does not match its bid"}, + {"other fee recipient", pendingPaymentsWith(slot, func() *gloas.BuilderPendingPayment { + p := paymentWithWeight(quorum) + p.Withdrawal.FeeRecipient = executionAddress(testBuilderAddress) + return p + }()), false, "does not match its bid"}, + {"other proposer", pendingPaymentsWith(slot, func() *gloas.BuilderPendingPayment { + p := paymentWithWeight(quorum) + p.ProposerIndex = 1001 + return p + }()), false, "does not match its bid"}, + {"not a full vector", pendingPaymentsWith(slot, paymentWithWeight(quorum))[:32], false, "expected 64"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + paid, err := isWithheldBidPaid(bid, proposer, tt.payments, totalActive) + if tt.err != "" { + require.ErrorContains(t, err, tt.err) + return + } + require.NoError(t, err) + require.Equal(t, tt.paid, paid) + }) + } + + // The current epoch half belongs to other slots, even if it looks alike + t.Run("reads the previous epoch half", func(t *testing.T) { + payments := pendingPaymentsWith(slot, paymentWithWeight(0)) + payments[constants.SlotsInEpoch+slot%constants.SlotsInEpoch] = paymentWithWeight(quorum * 2) + paid, err := isWithheldBidPaid(bid, proposer, payments, totalActive) + require.NoError(t, err) + require.False(t, paid) + }) +} + +func Test_BidPromisesPaymentTo(t *testing.T) { + tests := []struct { + name string + bid *gloas.ExecutionPayloadBid + promises bool + }{ + {"builder pays the pool", gloasBid(testGloasSlot, 42, 1, testPoolAddress, 0xaa, 0xbb), true}, + {"builder pays nothing", gloasBid(testGloasSlot, 42, 0, testPoolAddress, 0xaa, 0xbb), false}, + {"builder pays someone else", gloasBid(testGloasSlot, 42, 1, testBuilderAddress, 0xaa, 0xbb), false}, + {"self-built", gloasBid(testGloasSlot, gloas.BuilderIndexSelfBuild, 0, testPoolAddress, 0xaa, 0xbb), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + fullBlock := gloasFullBlock(t, testGloasSlot, 1000, tt.bid) + require.Equal(t, tt.promises, fullBlock.BidPromisesPaymentTo(testPoolAddress)) + require.Equal(t, tt.promises, fullBlock.BidPromisesPaymentTo(strings.ToLower(testPoolAddress))) + }) + } +} + +func Test_SetBuilderPayment(t *testing.T) { + bid := gloasBid(testGloasSlot+3, 42, 48_200_000, testPoolAddress, 0xaa, 0xbb) + fullBlock := gloasFullBlock(t, testGloasSlot+3, 1000, bid) + + fullBlock.SetBuilderPayment(true) + require.Equal(t, &BuilderPayment{ + Slot: testGloasSlot + 3, + ProposerIndex: 1000, + BuilderIndex: 42, + AmountWei: decimal(t, "48200000000000000"), + Paid: true, + }, fullBlock.BuilderPayment) + + fullBlock.SetBuilderPayment(false) + require.False(t, fullBlock.BuilderPayment.Paid) +} + +func Test_FetchBuilderPendingPayments(t *testing.T) { + // Shaped as the beacon API serves it: numbers as strings + body := `{"version":"gloas","execution_optimistic":false,"finalized":true,"data":[` + + `{"weight":"720000000000000","withdrawal":{"fee_recipient":"` + strings.ToLower(testPoolAddress) + + `","amount":"48200000","builder_index":"42"},"proposer_index":"1000"},` + + `{"weight":"0","withdrawal":{"fee_recipient":"0x0000000000000000000000000000000000000000","amount":"0","builder_index":"0"},"proposer_index":"0"}]}` + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/eth/v1/beacon/states/4235327/builder_pending_payments" { + http.Error(w, `{"code":404,"message":"not found"}`, http.StatusNotFound) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(body)) + })) + defer server.Close() + + payments, err := fetchBuilderPendingPayments(server.URL, "4235327") + require.NoError(t, err) + require.Len(t, payments, 2) + require.Equal(t, 720_000*ethInGwei, payments[0].Weight) + require.Equal(t, phase0.ValidatorIndex(1000), payments[0].ProposerIndex) + require.Equal(t, gloas.BuilderIndex(42), payments[0].Withdrawal.BuilderIndex) + require.Equal(t, phase0.Gwei(48_200_000), payments[0].Withdrawal.Amount) + require.Equal(t, executionAddress(testPoolAddress), payments[0].Withdrawal.FeeRecipient) + require.Zero(t, payments[1].Withdrawal.Amount) + + _, err = fetchBuilderPendingPayments(server.URL, "1") + require.ErrorContains(t, err, "non-200 response: 404") +} + +func Test_TotalActiveBalance(t *testing.T) { + validator := func(status v1.ValidatorState, effectiveBalanceEth phase0.Gwei) *v1.Validator { + return &v1.Validator{Status: status, Validator: &phase0.Validator{EffectiveBalance: effectiveBalanceEth * ethInGwei}} + } + validators := map[phase0.ValidatorIndex]*v1.Validator{ + 1: validator(v1.ValidatorStateActiveOngoing, 32), + 2: validator(v1.ValidatorStateActiveExiting, 2048), + 3: validator(v1.ValidatorStateActiveSlashed, 31), + // Not active, so not counted even if the beacon node returned them + 4: validator(v1.ValidatorStatePendingQueued, 32), + 5: validator(v1.ValidatorStateExitedUnslashed, 32), + } + require.Equal(t, (32+2048+31)*ethInGwei, totalActiveBalance(validators)) + require.Zero(t, totalActiveBalance(nil)) +} diff --git a/oracle/onchain.go b/oracle/onchain.go index acf8008..63e3ac0 100644 --- a/oracle/onchain.go +++ b/oracle/onchain.go @@ -1044,7 +1044,7 @@ func (o *Onchain) FetchFullBlock(slot uint64, oracle *Oracle, opt ...bool) *Full // From Gloas on, the beacon block carries a bid and the execution payload // is published separately. An empty slot has no execution block, so // there are no events, txs or receipts to fetch - if fullBlock.IsGloas() && !o.fetchGloasExecutionPayload(fullBlock) { + if fullBlock.IsGloas() && !o.fetchGloasSlot(fullBlock) { return fullBlock } diff --git a/oracle/types.go b/oracle/types.go index c799105..705d61c 100644 --- a/oracle/types.go +++ b/oracle/types.go @@ -149,6 +149,26 @@ type ForcedMevPayment struct { BlockHash string `json:"block_hash"` } +// From Gloas on, a builder's bid promises a payment to the proposer's fee +// recipient. The protocol takes it from the builder's deposit and pays it as a +// withdrawal in a later execution payload, so it arrives without any tx or +// event. Only payments to the pool are tracked. +type BuilderPayment struct { + // Slot whose bid promised the payment, and who proposed it + Slot uint64 `json:"slot"` + ProposerIndex uint64 `json:"proposer_index"` + + BuilderIndex uint64 `json:"builder_index"` + AmountWei *big.Int `json:"amount_wei"` + + // False when the protocol dropped the payment: the payload was withheld + // and the beacon block got too few votes, or the proposer was slashed + Paid bool `json:"paid"` + + // Execution block whose withdrawals paid it. Zero while it is in flight + ArrivalBlock uint64 `json:"arrival_block,omitempty"` +} + type FullBlock struct { // consensus data: duty (mandatory, who should propose the block) @@ -175,6 +195,9 @@ type FullBlock struct { // payment was detected but its apparent recipient was not the pool ForcedMevPayment *ForcedMevPayment `json:"forced_mev_payment,omitempty"` + // Gloas only: set when the bid promised a payment to the pool + BuilderPayment *BuilderPayment `json:"builder_payment,omitempty"` + // Populated with the validators if there are sub/unsub events ValidatorsSubs []*v1.Validator `json:"validators_subs"` ValidatorsUnsubs []*v1.Validator `json:"validators_unsubs"` diff --git a/utils/utils.go b/utils/utils.go index f3a5db9..6a431d1 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -260,6 +260,11 @@ func WeiToEther(wei *big.Int) *big.Float { return new(big.Float).Quo(new(big.Float).SetInt(wei), big.NewFloat(params.Ether)) } +// Converts an amount in gwei, the unit of the beacon chain, to wei +func GweiToWei(gwei uint64) *big.Int { + return new(big.Int).Mul(new(big.Int).SetUint64(gwei), big.NewInt(params.GWei)) +} + func IsIn(a string, list []string) bool { for _, b := range list { if Equals(a, b) { diff --git a/utils/utils_test.go b/utils/utils_test.go index 9b93f14..9a71b58 100644 --- a/utils/utils_test.go +++ b/utils/utils_test.go @@ -232,3 +232,10 @@ func Test_IsIn(t *testing.T) { require.Equal(t, true, IsIn("0x000A", []string{"0x000a"})) require.Equal(t, false, IsIn("a", []string{"c", "d"})) } + +func Test_GweiToWei(t *testing.T) { + require.Equal(t, "0", GweiToWei(0).String()) + require.Equal(t, "48200000000000000", GweiToWei(48_200_000).String()) + // Does not overflow for the largest gwei amount + require.Equal(t, "18446744073709551615000000000", GweiToWei(^uint64(0)).String()) +} From 940d5697d2081335ad6f9878715ed3341bd47e40 Mon Sep 17 00:00:00 2001 From: Marketen Date: Thu, 22 Oct 2026 17:57:57 +0200 Subject: [PATCH 5/9] Classify Gloas proposals from the builder bid A Gloas proposal is judged on what the proposer chose, the bid and who it pays, and never on what a builder failed to do: - Self-built payload: judged as before Gloas, on the payload's fee recipient. If its payload was not included, the slot counts as missed. - Bid paying the pool: a valid proposal, rewarded with whatever reached the pool: the bid value when the protocol paid it, plus anything the payload itself paid (an execution_payment tx, or the tips when the builder made the pool its fee recipient). An unpaid execution_payment is the builder's fault, so it no longer gets the validator banned. - Bid paying the pool but withheld payload and dropped payment: missed, as the beacon block was too late to collect its votes. - Bid paying someone else: wrong fee recipient, as before. If the payload still paid the pool, that ETH is credited rather than left unallocated. Missed and wrong fee keep their existing consequences, so no new block types or state machine events are introduced and the API is unchanged. The part of a reward paid from the builder's deposit is stored in the new SummarizedBlock.BuilderPaymentWei, since it arrives with no event. The offchain reconciliation counts it as an asset. The field is omitted when nil, so states saved before this change keep their hash. Co-Authored-By: Claude Opus 5.5 --- oracle/block.go | 21 +- oracle/gloas.go | 73 +++++++ oracle/gloas_proposal_test.go | 401 ++++++++++++++++++++++++++++++++++ oracle/oracle.go | 14 +- oracle/proposer_tip_test.go | 16 +- oracle/types.go | 6 + 6 files changed, 516 insertions(+), 15 deletions(-) create mode 100644 oracle/gloas_proposal_test.go diff --git a/oracle/block.go b/oracle/block.go index a05d9d3..05e21b6 100644 --- a/oracle/block.go +++ b/oracle/block.go @@ -839,19 +839,32 @@ func (b *FullBlock) SummarizedBlock(oracle *Oracle, poolAddress string) Summariz poolBlock.BlockType = MissedProposal return poolBlock - } else if b.IsGloas() { - log.Fatal("Gloas proposals can't be classified yet, slot: ", b.GetSlotUint64()) } else { // Check if the proposer is subscribed to the pool isFromSubscriber := oracle.isSubscribed(b.GetProposerIndexUint64()) // Fetch block information - reward, correctFeeRec, rewardType := b.GetSentRewardAndType(poolAddress, isFromSubscriber) + var reward *big.Int + var correctFeeRec bool + var rewardType RewardType + if b.IsGloas() { + proposal := b.gloasProposal(poolAddress, isFromSubscriber) + if proposal.missed { + poolBlock.BlockType = MissedProposal + return poolBlock + } + reward, correctFeeRec, rewardType = proposal.reward, proposal.correctFeeRecipient, proposal.rewardType + poolBlock.BuilderPaymentWei = proposal.builderPaymentWei + } else { + reward, correctFeeRec, rewardType = b.GetSentRewardAndType(poolAddress, isFromSubscriber) + } // Populate common parameters poolBlock.Reward = reward poolBlock.RewardType = rewardType - poolBlock.Block = b.GetBlockNumber() + if b.HasExecutionPayload() { + poolBlock.Block = b.GetBlockNumber() + } if correctFeeRec { // If the fee recipient was correct diff --git a/oracle/gloas.go b/oracle/gloas.go index d2dd825..91a7292 100644 --- a/oracle/gloas.go +++ b/oracle/gloas.go @@ -2,6 +2,7 @@ package oracle import ( "fmt" + "math/big" "github.com/attestantio/go-eth2-client/spec" "github.com/attestantio/go-eth2-client/spec/gloas" @@ -206,3 +207,75 @@ func (b *FullBlock) checkGloasForkSlot(blockVersion spec.DataVersion, slot uint6 }).Fatal("Beacon block version does not match the configured Gloas fork slot, update GloasForkSlot") } } + +// How a Gloas proposal went for the pool +type gloasProposal struct { + // Counts as missed: nothing reached the pool and no execution payload was + // included, so the proposer's beacon block was most likely late + missed bool + + // The proposer pointed its proposal at the pool + correctFeeRecipient bool + + // Everything the proposal sent to the pool, and its type + reward *big.Int + rewardType RewardType + + // The part of reward paid from the builder's deposit, nil if none. It + // reaches the pool as a withdrawal instead of through the payload + builderPaymentWei *big.Int +} + +// Classifies a Gloas proposal and adds up what it sent to the pool. The +// proposer is accountable for what it chose: the bid and where it pays, or the +// fee recipient when it built its own payload. It is not for what the builder +// failed to do, like withholding the payload or skipping a promised payment. +func (b *FullBlock) gloasProposal(poolAddress string, isSubscriber bool) gloasProposal { + if b.IsSelfBuilt() { + // The proposer's own payload, judged as before Gloas + if !b.HasExecutionPayload() { + return gloasProposal{missed: true, reward: big.NewInt(0)} + } + reward, sent, rewardType := b.GetSentRewardAndType(poolAddress, isSubscriber) + return gloasProposal{correctFeeRecipient: sent, reward: reward, rewardType: rewardType} + } + + proposal := gloasProposal{reward: big.NewInt(0), rewardType: MevBlock} + + if b.BuilderPayment != nil && b.BuilderPayment.Paid { + proposal.builderPaymentWei = new(big.Int).Set(b.BuilderPayment.AmountWei) + proposal.reward.Add(proposal.reward, proposal.builderPaymentWei) + } + + // Whatever the payload itself sent to the pool: a tx paying the bid's + // execution_payment, or the tips if the builder made the pool its fee + // recipient. Builders keep the tips otherwise, so they don't count + payloadPaidPool := false + if b.HasExecutionPayload() { + payloadReward, sent, payloadRewardType := b.GetSentRewardAndType(poolAddress, false) + if sent { + payloadPaidPool = true + proposal.reward.Add(proposal.reward, payloadReward) + proposal.rewardType = payloadRewardType + } + } + + bid := b.GetExecutionPayloadBid() + if utils.Equals(bid.FeeRecipient.String(), poolAddress) { + // A withheld payload whose payment was dropped sent nothing + if !b.HasExecutionPayload() && proposal.builderPaymentWei == nil { + return gloasProposal{missed: true, reward: big.NewInt(0)} + } + proposal.correctFeeRecipient = true + return proposal + } + + // The bid paid someone else. Should the payload still have paid the pool, + // that ETH is credited as before Gloas, otherwise it would be left + // unallocated + if payloadPaidPool { + proposal.correctFeeRecipient = true + return proposal + } + return gloasProposal{correctFeeRecipient: false, reward: utils.GweiToWei(uint64(bid.Value)), rewardType: MevBlock} +} diff --git a/oracle/gloas_proposal_test.go b/oracle/gloas_proposal_test.go new file mode 100644 index 0000000..11f0404 --- /dev/null +++ b/oracle/gloas_proposal_test.go @@ -0,0 +1,401 @@ +package oracle + +import ( + "crypto/ecdsa" + "math/big" + "testing" + + v1 "github.com/attestantio/go-eth2-client/api/v1" + "github.com/attestantio/go-eth2-client/spec/bellatrix" + "github.com/attestantio/go-eth2-client/spec/gloas" + "github.com/attestantio/go-eth2-client/spec/phase0" + "github.com/avast/retry-go/v4" + "github.com/dappnode/mev-sp-oracle/contract" + "github.com/dappnode/mev-sp-oracle/utils" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/crypto" + "github.com/stretchr/testify/require" +) + +// A slot after the fork that is not a validator cleanup slot +var testProposalSlot = testGloasSlot + 7 + +const testProposer = phase0.ValidatorIndex(1000) + +// What a bid in the tests promises the pool: 0.0482 ETH +const testBidValueGwei = uint64(48_200_000) + +// A payment the builder sends with a tx in its own payload, ie an +// execution_payment, and the EtherReceived event the pool emits for it +func executionPaymentTx(t *testing.T, builderKey *ecdsa.PrivateKey, amount *big.Int) (bellatrix.Transaction, *contract.ContractEtherReceived) { + t.Helper() + pool := common.HexToAddress(testPoolAddress) + chainId := new(big.Int).SetUint64(HoodiChainId) + tx, err := types.SignNewTx(builderKey, types.LatestSignerForChainID(chainId), &types.DynamicFeeTx{ + ChainID: chainId, GasTipCap: big.NewInt(0), GasFeeCap: big.NewInt(0), Gas: 21000, To: &pool, Value: amount, + }) + require.NoError(t, err) + raw, err := tx.MarshalBinary() + require.NoError(t, err) + event := &contract.ContractEtherReceived{ + Sender: crypto.PubkeyToAddress(builderKey.PublicKey), + DonationAmount: new(big.Int).Set(amount), + Raw: types.Log{Address: pool, TxHash: tx.Hash(), BlockNumber: 5000}, + } + return raw, event +} + +// Each scenario describes a Gloas slot: the bid, what happened to it, and what +// its payload contained +type gloasScenario struct { + builder gloas.BuilderIndex + bidValueGwei uint64 + bidFeeRecipient string + + // Whether the next beacon block built on the payload, and when it did + // not, whether the protocol still paid the bid + included bool + withheldPaid bool + bidPaidToPool bool + + // Payload contents, for full slots + payloadFeeRecipient string + executionPaymentWei *big.Int + tipsToPayloadFeeRec bool +} + +// Builds the FullBlock FetchFullBlock would have built for the scenario +func (s gloasScenario) block(t *testing.T) *FullBlock { + t.Helper() + bid := gloasBid(testProposalSlot, s.builder, s.bidValueGwei, s.bidFeeRecipient, 0xaa, 0xbb) + fullBlock := gloasFullBlock(t, testProposalSlot, testProposer, bid) + + if fullBlock.BidPromisesPaymentTo(testPoolAddress) { + fullBlock.SetBuilderPayment(s.included || s.withheldPaid) + } + if !s.included { + return fullBlock + } + + var txs []bellatrix.Transaction + var receipts []*types.Receipt + payloadFeeRecipient := s.payloadFeeRecipient + + if s.tipsToPayloadFeeRec { + userKey, err := crypto.GenerateKey() + require.NoError(t, err) + for _, charged := range txsOfEveryType(t, userKey, HoodiChainId) { + raw, err := charged.tx.MarshalBinary() + require.NoError(t, err) + txs = append(txs, raw) + receipts = append(receipts, &types.Receipt{TxHash: charged.tx.Hash(), GasUsed: charged.gasUsed}) + } + } + + if s.executionPaymentWei != nil { + builderKey, err := crypto.GenerateKey() + require.NoError(t, err) + // The builder pays from the payload's fee recipient, as relays check + payloadFeeRecipient = crypto.PubkeyToAddress(builderKey.PublicKey).Hex() + raw, event := executionPaymentTx(t, builderKey, s.executionPaymentWei) + txs = append(txs, raw) + fullBlock.Events.EtherReceived = append(fullBlock.Events.EtherReceived, event) + } + + fullBlock.SetExecutionPayload(gloasEnvelope(bid, 5000, payloadFeeRecipient, txs, nil)) + if receipts != nil { + fullBlock.ExecutionReceipts = receipts + } + return fullBlock +} + +func tipsOf(t *testing.T, fullBlock *FullBlock) *big.Int { + t.Helper() + tips, err := fullBlock.GetProposerTip() + require.NoError(t, err) + return tips +} + +func Test_SummarizedBlock_GloasProposals(t *testing.T) { + bidValueWei := utils.GweiToWei(testBidValueGwei) + executionPayment := big.NewInt(3_000_000_000_000_000) + + tests := []struct { + name string + scenario gloasScenario + blockType BlockType + rewardType RewardType + reward func(*FullBlock) *big.Int + builderPaymentWei *big.Int + hasExecutionBlock bool + expectedDonations int + }{ + // The proposer built its own payload, judged as before Gloas + { + name: "self-built, pool as fee recipient", + scenario: gloasScenario{builder: gloas.BuilderIndexSelfBuild, bidFeeRecipient: testPoolAddress, included: true, payloadFeeRecipient: testPoolAddress, tipsToPayloadFeeRec: true}, + blockType: OkPoolProposal, + rewardType: VanilaBlock, + reward: func(b *FullBlock) *big.Int { return tipsOf(t, b) }, + hasExecutionBlock: true, + }, + { + name: "self-built, another fee recipient", + scenario: gloasScenario{builder: gloas.BuilderIndexSelfBuild, bidFeeRecipient: testPoolAddress, included: true, payloadFeeRecipient: testBuilderAddress, tipsToPayloadFeeRec: true}, + blockType: WrongFeeRecipient, + // As before Gloas, the tips are only worked out for subscribers + rewardType: UnknownRewardType, + reward: func(b *FullBlock) *big.Int { return big.NewInt(0) }, + hasExecutionBlock: true, + }, + { + name: "self-built, payload not included", + scenario: gloasScenario{builder: gloas.BuilderIndexSelfBuild, bidFeeRecipient: testPoolAddress}, + blockType: MissedProposal, + reward: func(*FullBlock) *big.Int { return big.NewInt(0) }, + }, + + // A builder's bid paying the pool + { + name: "bid paid to the pool", + scenario: gloasScenario{builder: 42, bidValueGwei: testBidValueGwei, bidFeeRecipient: testPoolAddress, included: true, payloadFeeRecipient: testBuilderAddress}, + blockType: OkPoolProposal, + rewardType: MevBlock, + reward: func(*FullBlock) *big.Int { return bidValueWei }, + builderPaymentWei: bidValueWei, + hasExecutionBlock: true, + }, + { + name: "payload withheld, beacon block got its votes", + scenario: gloasScenario{builder: 42, bidValueGwei: testBidValueGwei, bidFeeRecipient: testPoolAddress, withheldPaid: true}, + blockType: OkPoolProposal, + rewardType: MevBlock, + reward: func(*FullBlock) *big.Int { return bidValueWei }, + builderPaymentWei: bidValueWei, + }, + { + name: "payload withheld, beacon block lacked votes", + scenario: gloasScenario{builder: 42, bidValueGwei: testBidValueGwei, bidFeeRecipient: testPoolAddress}, + blockType: MissedProposal, + reward: func(*FullBlock) *big.Int { return big.NewInt(0) }, + }, + { + name: "bid and execution payment, both to the pool", + scenario: gloasScenario{builder: 42, bidValueGwei: testBidValueGwei, bidFeeRecipient: testPoolAddress, included: true, + executionPaymentWei: executionPayment}, + blockType: OkPoolProposal, + rewardType: MevBlock, + reward: func(*FullBlock) *big.Int { return new(big.Int).Add(bidValueWei, executionPayment) }, + builderPaymentWei: bidValueWei, + hasExecutionBlock: true, + }, + { + name: "bid paid to the pool and the pool as payload fee recipient", + scenario: gloasScenario{builder: 42, bidValueGwei: testBidValueGwei, bidFeeRecipient: testPoolAddress, included: true, + payloadFeeRecipient: testPoolAddress, tipsToPayloadFeeRec: true}, + blockType: OkPoolProposal, + rewardType: VanilaBlock, + reward: func(b *FullBlock) *big.Int { return new(big.Int).Add(bidValueWei, tipsOf(t, b)) }, + builderPaymentWei: bidValueWei, + hasExecutionBlock: true, + }, + + // A relay's bid, paying by tx only + { + name: "execution payment to the pool", + scenario: gloasScenario{builder: 42, bidFeeRecipient: testPoolAddress, included: true, + executionPaymentWei: executionPayment}, + blockType: OkPoolProposal, + rewardType: MevBlock, + reward: func(*FullBlock) *big.Int { return executionPayment }, + hasExecutionBlock: true, + }, + { + // The builder broke its promise, the proposer did nothing wrong + name: "execution payment promised but never sent", + scenario: gloasScenario{builder: 42, bidFeeRecipient: testPoolAddress, included: true, payloadFeeRecipient: testBuilderAddress}, + blockType: OkPoolProposal, + rewardType: MevBlock, + reward: func(*FullBlock) *big.Int { return big.NewInt(0) }, + hasExecutionBlock: true, + }, + + // The proposer picked a bid paying someone else + { + name: "bid paid to another address", + scenario: gloasScenario{builder: 42, bidValueGwei: testBidValueGwei, bidFeeRecipient: testBuilderAddress, included: true, payloadFeeRecipient: testBuilderAddress}, + blockType: WrongFeeRecipient, + rewardType: MevBlock, + reward: func(*FullBlock) *big.Int { return bidValueWei }, + hasExecutionBlock: true, + }, + { + name: "bid paid to another address, payload withheld", + scenario: gloasScenario{builder: 42, bidValueGwei: testBidValueGwei, bidFeeRecipient: testBuilderAddress}, + blockType: WrongFeeRecipient, + rewardType: MevBlock, + reward: func(*FullBlock) *big.Int { return bidValueWei }, + }, + { + // Credited anyway, or it would be left unallocated in the pool + name: "bid paid to another address, but the payload paid the pool", + scenario: gloasScenario{builder: 42, bidValueGwei: testBidValueGwei, bidFeeRecipient: testBuilderAddress, included: true, + executionPaymentWei: executionPayment}, + blockType: OkPoolProposal, + rewardType: MevBlock, + reward: func(*FullBlock) *big.Int { return executionPayment }, + hasExecutionBlock: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + fullBlock := tt.scenario.block(t) + oracle := NewOracle(&Config{Network: Hoodi, PoolAddress: testPoolAddress}) + + summary := fullBlock.SummarizedBlock(oracle, testPoolAddress) + + require.Equal(t, tt.blockType, summary.BlockType) + require.Equal(t, tt.reward(fullBlock), summary.Reward) + require.Equal(t, tt.builderPaymentWei, summary.BuilderPaymentWei) + if tt.blockType != MissedProposal { + require.Equal(t, tt.rewardType, summary.RewardType) + } + if tt.hasExecutionBlock { + require.Equal(t, uint64(5000), summary.Block) + } else { + require.Zero(t, summary.Block) + } + + // An execution payment is a MEV reward, not a donation + require.Empty(t, fullBlock.GetDonations(testPoolAddress)) + }) + } +} + +// A validator with BLS credentials can't be subscribed, its reward goes to the +// pool fees as before Gloas +func Test_SummarizedBlock_GloasBlsCredentials(t *testing.T) { + fullBlock := gloasScenario{builder: 42, bidValueGwei: testBidValueGwei, bidFeeRecipient: testPoolAddress, included: true, + payloadFeeRecipient: testBuilderAddress}.block(t) + fullBlock.Validator.Validator.WithdrawalCredentials = make([]byte, 32) + + summary := fullBlock.SummarizedBlock(NewOracle(&Config{Network: Hoodi, PoolAddress: testPoolAddress}), testPoolAddress) + require.Equal(t, OkPoolProposalBlsKeys, summary.BlockType) + require.Equal(t, utils.GweiToWei(testBidValueGwei), summary.Reward) +} + +// An oracle on Hoodi starting at testProposalSlot, whose validators all have 32 +// ETH of effective balance +func gloasTestOracle(t *testing.T) *Oracle { + t.Helper() + oracle := NewOracle(&Config{ + Network: Hoodi, + PoolAddress: testPoolAddress, + PoolFeesAddress: "0x2222222222222222222222222222222222222222", + PoolFeesPercentOver10000: 500, + CollateralInWei: big.NewInt(1), + CheckPointSizeInSlots: 7200, + DeployedSlot: testProposalSlot, + }) + oracle.SetGetSetOfValidatorsFunc(func(indices []phase0.ValidatorIndex, _ string, _ ...retry.Option) (map[phase0.ValidatorIndex]*v1.Validator, error) { + validators := make(map[phase0.ValidatorIndex]*v1.Validator) + for _, index := range indices { + validators[index] = &v1.Validator{Index: index, Validator: &phase0.Validator{EffectiveBalance: 32_000_000_000}} + } + return validators, nil + }) + return oracle +} + +func Test_AdvanceStateToNextSlot_GloasProposals(t *testing.T) { + withdrawalAddress := "0x1111111111111111111111111111111111111111" + + t.Run("withheld payload paid credits the proposer", func(t *testing.T) { + oracle := gloasTestOracle(t) + oracle.addSubscription(uint64(testProposer), withdrawalAddress, "0x") + oracle.state.LatestProcessedBlock = 4999 + + fullBlock := gloasScenario{builder: 42, bidValueGwei: testBidValueGwei, bidFeeRecipient: testPoolAddress, withheldPaid: true}.block(t) + _, err := oracle.AdvanceStateToNextSlot(fullBlock) + require.NoError(t, err) + + validator := oracle.state.Validators[uint64(testProposer)] + require.Equal(t, Active, validator.ValidatorStatus) + require.Len(t, oracle.state.ProposedBlocks, 1) + require.Positive(t, validator.AccumulatedRewardsWei.Sign()) + // An empty slot has no execution block + require.Equal(t, uint64(4999), oracle.state.LatestProcessedBlock) + require.NoError(t, oracle.RunOffchainReconciliation()) + }) + + t.Run("withheld payload not paid counts as missed", func(t *testing.T) { + oracle := gloasTestOracle(t) + oracle.addSubscription(uint64(testProposer), withdrawalAddress, "0x") + + fullBlock := gloasScenario{builder: 42, bidValueGwei: testBidValueGwei, bidFeeRecipient: testPoolAddress}.block(t) + _, err := oracle.AdvanceStateToNextSlot(fullBlock) + require.NoError(t, err) + + require.Equal(t, YellowCard, oracle.state.Validators[uint64(testProposer)].ValidatorStatus) + require.Len(t, oracle.state.MissedBlocks, 1) + require.Empty(t, oracle.state.ProposedBlocks) + require.NoError(t, oracle.RunOffchainReconciliation()) + }) + + t.Run("bid paying another address bans the proposer", func(t *testing.T) { + oracle := gloasTestOracle(t) + oracle.addSubscription(uint64(testProposer), withdrawalAddress, "0x") + + fullBlock := gloasScenario{builder: 42, bidValueGwei: testBidValueGwei, bidFeeRecipient: testBuilderAddress, included: true, + payloadFeeRecipient: testBuilderAddress}.block(t) + _, err := oracle.AdvanceStateToNextSlot(fullBlock) + require.NoError(t, err) + + require.Equal(t, Banned, oracle.state.Validators[uint64(testProposer)].ValidatorStatus) + require.NoError(t, oracle.RunOffchainReconciliation()) + }) + + t.Run("unpaid execution payment does not ban the proposer", func(t *testing.T) { + oracle := gloasTestOracle(t) + oracle.addSubscription(uint64(testProposer), withdrawalAddress, "0x") + + fullBlock := gloasScenario{builder: 42, bidFeeRecipient: testPoolAddress, included: true, payloadFeeRecipient: testBuilderAddress}.block(t) + _, err := oracle.AdvanceStateToNextSlot(fullBlock) + require.NoError(t, err) + + require.Equal(t, Active, oracle.state.Validators[uint64(testProposer)].ValidatorStatus) + require.Equal(t, uint64(5000), oracle.state.LatestProcessedBlock) + require.NoError(t, oracle.RunOffchainReconciliation()) + }) + + t.Run("bid paid to the pool auto subscribes an unknown proposer", func(t *testing.T) { + oracle := gloasTestOracle(t) + + fullBlock := gloasScenario{builder: 42, bidValueGwei: testBidValueGwei, bidFeeRecipient: testPoolAddress, included: true, + payloadFeeRecipient: testBuilderAddress}.block(t) + _, err := oracle.AdvanceStateToNextSlot(fullBlock) + require.NoError(t, err) + + validator := oracle.state.Validators[uint64(testProposer)] + require.Equal(t, Active, validator.ValidatorStatus) + require.Equal(t, Auto, validator.SubscriptionType) + require.NoError(t, oracle.RunOffchainReconciliation()) + }) + + // Both the builder payment and the tips are credited and accounted for + t.Run("bid and tips to the pool reconcile", func(t *testing.T) { + oracle := gloasTestOracle(t) + oracle.addSubscription(uint64(testProposer), withdrawalAddress, "0x") + + fullBlock := gloasScenario{builder: 42, bidValueGwei: testBidValueGwei, bidFeeRecipient: testPoolAddress, included: true, + payloadFeeRecipient: testPoolAddress, tipsToPayloadFeeRec: true}.block(t) + _, err := oracle.AdvanceStateToNextSlot(fullBlock) + require.NoError(t, err) + + total := new(big.Int).Add(utils.GweiToWei(testBidValueGwei), tipsOf(t, fullBlock)) + require.Equal(t, total, oracle.state.ProposedBlocks[0].Reward) + require.NoError(t, oracle.RunOffchainReconciliation()) + }) +} diff --git a/oracle/oracle.go b/oracle/oracle.go index f4793bb..e38705e 100644 --- a/oracle/oracle.go +++ b/oracle/oracle.go @@ -925,9 +925,17 @@ func (or *Oracle) RunOffchainReconciliation() error { for _, subs := range or.state.SubscriptionEvents { assets.Add(assets, subs.SubscriptionCollateral) } - for _, vanilaBlock := range or.state.ProposedBlocks { - if vanilaBlock.RewardType == VanilaBlock { - assets.Add(assets, vanilaBlock.Reward) + for _, block := range or.state.ProposedBlocks { + // Paid from the builder's deposit, without any event + executionReward := block.Reward + if block.BuilderPaymentWei != nil { + assets.Add(assets, block.BuilderPaymentWei) + executionReward = new(big.Int).Sub(block.Reward, block.BuilderPaymentWei) + } + // Tips reach the pool without any event either. MEV paid through the + // execution payload is already counted with the EtherReceived events + if block.RewardType == VanilaBlock { + assets.Add(assets, executionReward) } } diff --git a/oracle/proposer_tip_test.go b/oracle/proposer_tip_test.go index e96239a..837da16 100644 --- a/oracle/proposer_tip_test.go +++ b/oracle/proposer_tip_test.go @@ -28,9 +28,9 @@ type chargedTx struct { // Signs one tx of every type the oracle supports. Fee caps are chosen so that // some txs pay their full tip and others are capped by the fee cap -func txsOfEveryType(t *testing.T, key *ecdsa.PrivateKey) []chargedTx { +func txsOfEveryType(t *testing.T, key *ecdsa.PrivateKey, chain uint64) []chargedTx { t.Helper() - chainId := new(big.Int).SetUint64(MainnetChainId) + chainId := new(big.Int).SetUint64(chain) signer := types.LatestSignerForChainID(chainId) to := common.HexToAddress("0x5555555555555555555555555555555555555555") @@ -46,10 +46,10 @@ func txsOfEveryType(t *testing.T, key *ecdsa.PrivateKey) []chargedTx { sign(&types.DynamicFeeTx{ChainID: chainId, Nonce: 2, GasTipCap: big.NewInt(2 * gwei), GasFeeCap: big.NewInt(50 * gwei), Gas: 90000, To: &to}), // Tip capped by the fee cap sign(&types.DynamicFeeTx{ChainID: chainId, Nonce: 3, GasTipCap: big.NewInt(9 * gwei), GasFeeCap: big.NewInt(12 * gwei), Gas: 50000, To: &to}), - sign(&types.BlobTx{ChainID: uint256.NewInt(MainnetChainId), Nonce: 4, GasTipCap: uint256.NewInt(uint64(3 * gwei)), + sign(&types.BlobTx{ChainID: uint256.NewInt(chain), Nonce: 4, GasTipCap: uint256.NewInt(uint64(3 * gwei)), GasFeeCap: uint256.NewInt(uint64(40 * gwei)), Gas: 21000, To: to, BlobFeeCap: uint256.NewInt(1), BlobHashes: []common.Hash{{0x01}}}), - sign(&types.SetCodeTx{ChainID: uint256.NewInt(MainnetChainId), Nonce: 5, GasTipCap: uint256.NewInt(uint64(1 * gwei)), + sign(&types.SetCodeTx{ChainID: uint256.NewInt(chain), Nonce: 5, GasTipCap: uint256.NewInt(uint64(1 * gwei)), GasFeeCap: uint256.NewInt(uint64(30 * gwei)), Gas: 60000, To: to}), } gasUsed := []uint64{21000, 25400, 61234, 50000, 21000, 47311} @@ -122,7 +122,7 @@ func formerProposerTip(txs []chargedTx, baseFee *big.Int, blockGasUsed uint64) * func Test_GetProposerTip_MatchesFormerCalculationBeforeGlamsterdam(t *testing.T) { key, err := crypto.GenerateKey() require.NoError(t, err) - txs := txsOfEveryType(t, key) + txs := txsOfEveryType(t, key, MainnetChainId) for _, baseFeeGwei := range []int64{1, 7, 10} { baseFee := big.NewInt(baseFeeGwei * gwei) @@ -139,7 +139,7 @@ func Test_GetProposerTip_MatchesFormerCalculationBeforeGlamsterdam(t *testing.T) func Test_GetProposerTip_BlockGasUsedIncludesRefunds(t *testing.T) { key, err := crypto.GenerateKey() require.NoError(t, err) - txs := txsOfEveryType(t, key) + txs := txsOfEveryType(t, key, MainnetChainId) baseFee := big.NewInt(7 * gwei) refunds := uint64(19_800) fullBlock := blockWithReceipts(t, txs, baseFee.Int64(), sumGasUsed(txs)+refunds) @@ -166,7 +166,7 @@ func Test_GetProposerTip_BlockGasUsedIncludesRefunds(t *testing.T) { func Test_GetProposerTip_Errors(t *testing.T) { key, err := crypto.GenerateKey() require.NoError(t, err) - txs := txsOfEveryType(t, key) + txs := txsOfEveryType(t, key, MainnetChainId) t.Run("no receipts", func(t *testing.T) { fullBlock := blockWithReceipts(t, txs, 7*gwei, sumGasUsed(txs)) @@ -202,6 +202,6 @@ func Test_GetProposerTip_Errors(t *testing.T) { func Test_GetBaseFeePerGasBigInt(t *testing.T) { key, err := crypto.GenerateKey() require.NoError(t, err) - fullBlock := blockWithReceipts(t, txsOfEveryType(t, key), 1_234_567_891, 0) + fullBlock := blockWithReceipts(t, txsOfEveryType(t, key, MainnetChainId), 1_234_567_891, 0) require.Equal(t, big.NewInt(1_234_567_891), fullBlock.GetBaseFeePerGasBigInt()) } diff --git a/oracle/types.go b/oracle/types.go index 705d61c..babdf63 100644 --- a/oracle/types.go +++ b/oracle/types.go @@ -217,6 +217,12 @@ type SummarizedBlock struct { Reward *big.Int `json:"reward_wei"` RewardType RewardType `json:"reward_type"` WithdrawalAddress string `json:"withdrawal_address"` + + // Gloas only: the part of Reward the protocol paid from the builder's + // deposit, which reaches the pool as a withdrawal instead of through the + // execution payload. RewardType then describes the rest of Reward. Omitted + // when nil, so states saved before Gloas keep their hash + BuilderPaymentWei *big.Int `json:"builder_payment_wei,omitempty"` } // Represents all the information that is stored of a validator From 488d266d780cb95ceca779a2ba29b052406cdcde Mon Sep 17 00:00:00 2001 From: Marketen Date: Thu, 22 Oct 2026 18:02:04 +0200 Subject: [PATCH 6/9] Track builder payments until they reach the pool A builder payment is credited when its slot is processed, but reaches the pool later, as a withdrawal in another execution payload: usually the next one, about an epoch later when the payload was withheld. Until then the oracle owes ETH the pool doesn't hold yet, and the exact onchain reconciliation run before every checkpoint would fail. - Credited builder payments are kept in the state as in flight. They are removed when a builder withdrawal to the pool with the same builder and amount is processed. A builder withdrawal to the pool that matches no credited payment rejects the slot, as that ETH would otherwise be left unallocated. - The onchain reconciliation counts the payments in flight as part of what the pool holds. It stays exact, with no tolerance. - The forced payment detector reads the pool balance across a block, so it now explains builder withdrawals to the pool instead of rejecting them. Any other withdrawal to the pool is still rejected. The state only keeps the payments in flight, so it doesn't grow. The new field is omitted when empty, and a test checks states saved before Gloas still load with their hash. Co-Authored-By: Claude Opus 5.5 --- oracle/builder_payments.go | 116 ++++++++++++ oracle/builder_payments_test.go | 318 ++++++++++++++++++++++++++++++++ oracle/forced_payment.go | 6 +- oracle/gloas_proposal_test.go | 19 +- oracle/onchain.go | 7 +- oracle/oracle.go | 26 ++- oracle/types.go | 9 +- 7 files changed, 487 insertions(+), 14 deletions(-) create mode 100644 oracle/builder_payments.go create mode 100644 oracle/builder_payments_test.go diff --git a/oracle/builder_payments.go b/oracle/builder_payments.go new file mode 100644 index 0000000..ec652ab --- /dev/null +++ b/oracle/builder_payments.go @@ -0,0 +1,116 @@ +package oracle + +import ( + "fmt" + "math/big" + + "github.com/attestantio/go-eth2-client/spec/capella" + "github.com/attestantio/go-eth2-client/spec/phase0" + "github.com/dappnode/mev-sp-oracle/utils" + "github.com/pkg/errors" + log "github.com/sirupsen/logrus" +) + +// A builder's payment to the pool is credited when its slot is processed, but +// it reaches the pool later, as a withdrawal in another execution payload (see +// gloas.go). Until then it is in flight: the oracle already owes it to the +// validators, but the pool doesn't hold it yet. This file keeps track of them. + +// BUILDER_INDEX_FLAG in the Gloas spec. Builder withdrawals reuse the +// validator index field of the withdrawal, with this bit set +const builderIndexFlag = phase0.ValidatorIndex(1 << 40) + +// Whether the withdrawal pays a builder payment rather than a validator's +func isBuilderWithdrawal(withdrawal *capella.Withdrawal) bool { + return withdrawal.ValidatorIndex&builderIndexFlag != 0 +} + +// Returns the builder payments the execution payload of the slot paid to the +// given address. Empty before Gloas and for slots without a payload +func (b *FullBlock) BuilderWithdrawalsTo(address string) []*capella.Withdrawal { + if !b.IsGloas() || !b.HasExecutionPayload() { + return nil + } + received := make([]*capella.Withdrawal, 0) + for _, withdrawal := range b.gloasExecutionPayload().Withdrawals { + if isBuilderWithdrawal(withdrawal) && utils.Equals(withdrawal.Address.String(), address) { + received = append(received, withdrawal) + } + } + return received +} + +// Total amount of the builder payments the slot paid to the given address +func (b *FullBlock) BuilderWithdrawalsWeiTo(address string) *big.Int { + total := big.NewInt(0) + for _, withdrawal := range b.BuilderWithdrawalsTo(address) { + total.Add(total, utils.GweiToWei(uint64(withdrawal.Amount))) + } + return total +} + +// Starts tracking a builder payment just credited to the pool +func (or *Oracle) trackBuilderPayment(payment *BuilderPayment) { + or.state.InFlightBuilderPayments = append(or.state.InFlightBuilderPayments, payment) + log.WithFields(log.Fields{ + "Slot": payment.Slot, + "BuilderIndex": payment.BuilderIndex, + "AmountWei": payment.AmountWei, + }).Info("Builder payment to the pool credited, waiting for its withdrawal") +} + +// Stops tracking the builder payments whose withdrawal reached the pool in the +// execution payload of this slot. Every builder withdrawal to the pool must +// match a credited payment: otherwise that ETH would be left unallocated, so +// the slot is rejected and the state left untouched. +// +// A payment is matched by builder and amount. When two in flight share both, +// which one is matched first makes no difference to the books. +func (or *Oracle) settleArrivedBuilderPayments(fullBlock *FullBlock) error { + withdrawals := fullBlock.BuilderWithdrawalsTo(or.cfg.PoolAddress) + if len(withdrawals) == 0 { + return nil + } + + remaining := append([]*BuilderPayment{}, or.state.InFlightBuilderPayments...) + arrived := make([]*BuilderPayment, 0, len(withdrawals)) + + for _, withdrawal := range withdrawals { + builderIndex := uint64(withdrawal.ValidatorIndex &^ builderIndexFlag) + amountWei := utils.GweiToWei(uint64(withdrawal.Amount)) + + matched := -1 + for i, payment := range remaining { + if payment.BuilderIndex == builderIndex && payment.AmountWei.Cmp(amountWei) == 0 { + matched = i + break + } + } + if matched < 0 { + return errors.New(fmt.Sprintf("withdrawal %d in block %d pays %s wei from builder %d to the pool, "+ + "but no such builder payment was credited", withdrawal.Index, fullBlock.GetBlockNumber(), amountWei, builderIndex)) + } + arrived = append(arrived, remaining[matched]) + remaining = append(remaining[:matched], remaining[matched+1:]...) + } + + or.state.InFlightBuilderPayments = remaining + for _, payment := range arrived { + log.WithFields(log.Fields{ + "Slot": payment.Slot, + "BuilderIndex": payment.BuilderIndex, + "AmountWei": payment.AmountWei, + "ArrivalBlock": fullBlock.GetBlockNumber(), + }).Info("Builder payment reached the pool") + } + return nil +} + +// Total amount of the builder payments credited but not in the pool yet +func (or *Oracle) inFlightBuilderPaymentsWei() *big.Int { + total := big.NewInt(0) + for _, payment := range or.state.InFlightBuilderPayments { + total.Add(total, payment.AmountWei) + } + return total +} diff --git a/oracle/builder_payments_test.go b/oracle/builder_payments_test.go new file mode 100644 index 0000000..8035c45 --- /dev/null +++ b/oracle/builder_payments_test.go @@ -0,0 +1,318 @@ +package oracle + +import ( + "math/big" + "strings" + "testing" + + v1 "github.com/attestantio/go-eth2-client/api/v1" + "github.com/attestantio/go-eth2-client/spec/bellatrix" + "github.com/attestantio/go-eth2-client/spec/capella" + "github.com/attestantio/go-eth2-client/spec/gloas" + "github.com/attestantio/go-eth2-client/spec/phase0" + "github.com/dappnode/mev-sp-oracle/contract" + "github.com/dappnode/mev-sp-oracle/utils" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/crypto" + "github.com/stretchr/testify/require" +) + +// The withdrawal that pays a builder payment of amountGwei to address +func builderWithdrawal(builderIndex uint64, address string, amountGwei uint64) *capella.Withdrawal { + return &capella.Withdrawal{ + Index: capella.WithdrawalIndex(builderIndex), + ValidatorIndex: builderIndexFlag | phase0.ValidatorIndex(builderIndex), + Address: executionAddress(address), + Amount: phase0.Gwei(amountGwei), + } +} + +// The sweep of a validator's balance, as before Gloas +func validatorWithdrawal(validatorIndex uint64, address string, amountGwei uint64) *capella.Withdrawal { + return &capella.Withdrawal{ + ValidatorIndex: phase0.ValidatorIndex(validatorIndex), + Address: executionAddress(address), + Amount: phase0.Gwei(amountGwei), + } +} + +func inFlightPayment(slot uint64, builderIndex uint64, amountGwei uint64) *BuilderPayment { + return &BuilderPayment{Slot: slot, ProposerIndex: 1, BuilderIndex: builderIndex, AmountWei: utils.GweiToWei(amountGwei), Paid: true} +} + +func Test_IsBuilderWithdrawal(t *testing.T) { + require.True(t, isBuilderWithdrawal(builderWithdrawal(42, testPoolAddress, 1))) + require.True(t, isBuilderWithdrawal(builderWithdrawal(0, testPoolAddress, 1))) + require.False(t, isBuilderWithdrawal(validatorWithdrawal(42, testPoolAddress, 1))) + // Validator indices are far from reaching the flag + require.False(t, isBuilderWithdrawal(validatorWithdrawal(uint64(builderIndexFlag)-1, testPoolAddress, 1))) +} + +func Test_BuilderWithdrawalsTo(t *testing.T) { + poolPayment := builderWithdrawal(42, testPoolAddress, 48_200_000) + otherPoolPayment := builderWithdrawal(7, strings.ToLower(testPoolAddress), 31_000_000) + + fullBlock := gloasScenario{builder: 42, bidFeeRecipient: testPoolAddress, included: true, payloadFeeRecipient: testBuilderAddress, + withdrawals: []*capella.Withdrawal{ + validatorWithdrawal(5, "0x1111111111111111111111111111111111111111", 18_000_000), + poolPayment, + builderWithdrawal(43, testBuilderAddress, 10_000_000), + // A validator sweeping to the pool is not a builder payment + validatorWithdrawal(6, testPoolAddress, 1_000_000), + otherPoolPayment, + }}.block(t) + + require.Equal(t, []*capella.Withdrawal{poolPayment, otherPoolPayment}, fullBlock.BuilderWithdrawalsTo(testPoolAddress)) + require.Equal(t, utils.GweiToWei(48_200_000+31_000_000), fullBlock.BuilderWithdrawalsWeiTo(testPoolAddress)) + + t.Run("empty slot", func(t *testing.T) { + empty := gloasScenario{builder: 42, bidFeeRecipient: testPoolAddress}.block(t) + require.Empty(t, empty.BuilderWithdrawalsTo(testPoolAddress)) + require.Zero(t, empty.BuilderWithdrawalsWeiTo(testPoolAddress).Sign()) + }) + + t.Run("before Gloas", func(t *testing.T) { + fulu := buildMevBlock(t, 100, 1000, 7, testPoolAddress, big.NewInt(1)) + require.Empty(t, fulu.BuilderWithdrawalsTo(testPoolAddress)) + }) +} + +func Test_SettleArrivedBuilderPayments(t *testing.T) { + blockPaying := func(t *testing.T, withdrawals ...*capella.Withdrawal) *FullBlock { + return gloasScenario{builder: gloas.BuilderIndexSelfBuild, bidFeeRecipient: testPoolAddress, included: true, + payloadFeeRecipient: testBuilderAddress, withdrawals: withdrawals}.block(t) + } + + t.Run("settles the arrived payment only", func(t *testing.T) { + oracle := gloasTestOracle(t) + first, second := inFlightPayment(10, 42, 48_200_000), inFlightPayment(11, 7, 31_000_000) + oracle.state.InFlightBuilderPayments = []*BuilderPayment{first, second} + + require.NoError(t, oracle.settleArrivedBuilderPayments(blockPaying(t, builderWithdrawal(7, testPoolAddress, 31_000_000)))) + require.Equal(t, []*BuilderPayment{first}, oracle.state.InFlightBuilderPayments) + }) + + t.Run("several in the same payload", func(t *testing.T) { + oracle := gloasTestOracle(t) + oracle.state.InFlightBuilderPayments = []*BuilderPayment{inFlightPayment(10, 42, 48_200_000), inFlightPayment(11, 7, 31_000_000)} + + require.NoError(t, oracle.settleArrivedBuilderPayments(blockPaying(t, + builderWithdrawal(42, testPoolAddress, 48_200_000), builderWithdrawal(7, testPoolAddress, 31_000_000)))) + require.Empty(t, oracle.state.InFlightBuilderPayments) + require.Zero(t, oracle.inFlightBuilderPaymentsWei().Sign()) + }) + + t.Run("identical payments settle one at a time", func(t *testing.T) { + oracle := gloasTestOracle(t) + oracle.state.InFlightBuilderPayments = []*BuilderPayment{inFlightPayment(10, 42, 1_000), inFlightPayment(11, 42, 1_000)} + + require.NoError(t, oracle.settleArrivedBuilderPayments(blockPaying(t, builderWithdrawal(42, testPoolAddress, 1_000)))) + require.Len(t, oracle.state.InFlightBuilderPayments, 1) + }) + + t.Run("withdrawals that are not builder payments to the pool are ignored", func(t *testing.T) { + oracle := gloasTestOracle(t) + payment := inFlightPayment(10, 42, 48_200_000) + oracle.state.InFlightBuilderPayments = []*BuilderPayment{payment} + + require.NoError(t, oracle.settleArrivedBuilderPayments(blockPaying(t, + builderWithdrawal(42, testBuilderAddress, 48_200_000), validatorWithdrawal(42, testPoolAddress, 48_200_000)))) + require.Equal(t, []*BuilderPayment{payment}, oracle.state.InFlightBuilderPayments) + }) + + t.Run("a payment never credited is rejected without touching the state", func(t *testing.T) { + oracle := gloasTestOracle(t) + payment := inFlightPayment(10, 42, 48_200_000) + oracle.state.InFlightBuilderPayments = []*BuilderPayment{payment} + + // The first one matches, but the slot is rejected as a whole + err := oracle.settleArrivedBuilderPayments(blockPaying(t, + builderWithdrawal(42, testPoolAddress, 48_200_000), builderWithdrawal(42, testPoolAddress, 1))) + require.ErrorContains(t, err, "no such builder payment was credited") + require.Equal(t, []*BuilderPayment{payment}, oracle.state.InFlightBuilderPayments) + }) +} + +func Test_RunOnchainReconciliation_CountsInFlightBuilderPayments(t *testing.T) { + oracle := gloasTestOracle(t) + oracle.state.PoolAccumulatedFees = utils.GweiToWei(100_000_000) + oracle.state.InFlightBuilderPayments = []*BuilderPayment{inFlightPayment(10, 42, 30_000_000)} + + // The pool holds what it owes minus what is still on its way + require.NoError(t, oracle.RunOnchainReconciliation(utils.GweiToWei(70_000_000), nil)) + require.ErrorContains(t, oracle.RunOnchainReconciliation(utils.GweiToWei(100_000_000), nil), "dont match") + + // Once the payment arrives the pool holds everything + oracle.state.InFlightBuilderPayments = nil + require.NoError(t, oracle.RunOnchainReconciliation(utils.GweiToWei(100_000_000), nil)) +} + +// The slots of the worked example: a builder payment credited in one slot +// reaches the pool slots later, and a withheld payload's one even an epoch +// later. Both reconciliations hold at every step, with the pool balance +// following what really reaches it. +func Test_BuilderPayments_FromCreditToArrival(t *testing.T) { + slot := testProposalSlot + oracle := gloasTestOracle(t) + oracle.addSubscription(uint64(testProposer), "0x1111111111111111111111111111111111111111", "0x") + poolBalance := big.NewInt(0) + + process := func(t *testing.T, fullBlock *FullBlock) { + t.Helper() + _, err := oracle.AdvanceStateToNextSlot(fullBlock) + require.NoError(t, err) + require.NoError(t, oracle.RunOffchainReconciliation()) + require.NoError(t, oracle.RunOnchainReconciliation(poolBalance, nil)) + } + + // Slot 1: builder 42's payload is included. 0.0482 ETH is owed + process(t, gloasScenario{slot: slot, builder: 42, bidValueGwei: 48_200_000, bidFeeRecipient: testPoolAddress, included: true, + payloadFeeRecipient: testBuilderAddress, blockNumber: 5000}.block(t)) + require.Equal(t, utils.GweiToWei(48_200_000), oracle.inFlightBuilderPaymentsWei()) + + // Slot 2: builder 7 withholds its payload, but the beacon block got its + // votes and the protocol pays 0.031 ETH. The slot is empty, so slot 1's + // payment can't reach the pool yet + process(t, gloasScenario{slot: slot + 1, builder: 7, bidValueGwei: 31_000_000, bidFeeRecipient: testPoolAddress, + withheldPaid: true}.block(t)) + require.Equal(t, utils.GweiToWei(48_200_000+31_000_000), oracle.inFlightBuilderPaymentsWei()) + require.Equal(t, uint64(5000), oracle.state.LatestProcessedBlock) + + // Slot 3: missed by another validator + credentials := make([]byte, 32) + credentials[0] = 1 + process(t, NewFullBlock(&v1.ProposerDuty{Slot: phase0.Slot(slot + 2), ValidatorIndex: 2000}, + &v1.Validator{Index: 2000, Validator: &phase0.Validator{WithdrawalCredentials: credentials}}, HoodiChainId)) + + // Slot 4: a self-built payload with the pool as fee recipient carries slot + // 1's payment. The pool receives it and the tips in the same block + selfBuilt := gloasScenario{slot: slot + 3, builder: gloas.BuilderIndexSelfBuild, bidFeeRecipient: testPoolAddress, included: true, + payloadFeeRecipient: testPoolAddress, tipsToPayloadFeeRec: true, blockNumber: 5001, + withdrawals: []*capella.Withdrawal{builderWithdrawal(42, testPoolAddress, 48_200_000)}}.block(t) + poolBalance.Add(poolBalance, utils.GweiToWei(48_200_000)) + poolBalance.Add(poolBalance, tipsOf(t, selfBuilt)) + process(t, selfBuilt) + require.Equal(t, utils.GweiToWei(31_000_000), oracle.inFlightBuilderPaymentsWei()) + require.Equal(t, uint64(5001), oracle.state.LatestProcessedBlock) + + // An epoch later, slot 2's payment arrives in whatever payload comes + // next. Here a relay's, whose promised execution payment never came + poolBalance.Add(poolBalance, utils.GweiToWei(31_000_000)) + process(t, gloasScenario{slot: slot + 4, builder: 43, bidFeeRecipient: testPoolAddress, included: true, + payloadFeeRecipient: testBuilderAddress, blockNumber: 5002, + withdrawals: []*capella.Withdrawal{builderWithdrawal(7, testPoolAddress, 31_000_000)}}.block(t)) + require.Empty(t, oracle.state.InFlightBuilderPayments) + require.Equal(t, uint64(5002), oracle.state.LatestProcessedBlock) + + // Slots 1, 2, 4 and 5 were valid proposals, slot 3 was missed + require.Len(t, oracle.state.ProposedBlocks, 4) + require.Equal(t, Active, oracle.state.Validators[uint64(testProposer)].ValidatorStatus) +} + +// The forced payment detector reads the pool balance across the block. A +// builder payment arriving in it must count as explained, not as a forced one +func Test_DetectForcedMevPayment_BuilderWithdrawals(t *testing.T) { + payment := builderWithdrawal(42, testPoolAddress, 48_200_000) + paymentWei := utils.GweiToWei(48_200_000) + before := decimal(t, "1000000000000000000") + + t.Run("builder payment alone", func(t *testing.T) { + fullBlock := gloasScenario{builder: 43, bidFeeRecipient: testBuilderAddress, included: true, payloadFeeRecipient: testBuilderAddress, + withdrawals: []*capella.Withdrawal{payment}}.block(t) + o, _ := newForcedPaymentRPC(t, fullBlock, before, new(big.Int).Add(before, paymentWei), nil) + + require.NoError(t, o.DetectForcedMevPayment(fullBlock)) + require.Nil(t, fullBlock.ForcedMevPayment) + }) + + t.Run("a validator withdrawal to the pool is still rejected", func(t *testing.T) { + fullBlock := gloasScenario{builder: 43, bidFeeRecipient: testBuilderAddress, included: true, payloadFeeRecipient: testBuilderAddress, + withdrawals: []*capella.Withdrawal{validatorWithdrawal(42, testPoolAddress, 48_200_000)}}.block(t) + o, _ := newForcedPaymentRPC(t, fullBlock, before, new(big.Int).Add(before, paymentWei), nil) + + require.ErrorContains(t, o.DetectForcedMevPayment(fullBlock), "credits a consensus withdrawal to the pool") + }) + + t.Run("builder payment and a forced payment in the same block", func(t *testing.T) { + forced := big.NewInt(3_000_000_000_000_000) + builderKey, err := crypto.GenerateKey() + require.NoError(t, err) + forwarder := common.HexToAddress(titanForwarder) + chainId := new(big.Int).SetUint64(HoodiChainId) + tx, err := types.SignNewTx(builderKey, types.LatestSignerForChainID(chainId), &types.DynamicFeeTx{ + ChainID: chainId, GasTipCap: big.NewInt(0), GasFeeCap: big.NewInt(0), Gas: 21000, To: &forwarder, Value: forced, + }) + require.NoError(t, err) + raw, err := tx.MarshalBinary() + require.NoError(t, err) + + bid := gloasBid(testProposalSlot, 43, 0, testPoolAddress, 0xaa, 0xbb) + fullBlock := gloasFullBlock(t, testProposalSlot, testProposer, bid) + fullBlock.SetExecutionPayload(gloasEnvelope(bid, 5000, crypto.PubkeyToAddress(builderKey.PublicKey).Hex(), + []bellatrix.Transaction{raw}, []*capella.Withdrawal{payment})) + receipt := &types.Receipt{TxHash: tx.Hash(), BlockNumber: big.NewInt(5000), BlockHash: common.Hash(bid.BlockHash), + TransactionIndex: 0, Status: types.ReceiptStatusSuccessful, Logs: []*types.Log{}} + + after := new(big.Int).Add(before, paymentWei) + after.Add(after, forced) + o, _ := newForcedPaymentRPC(t, fullBlock, before, after, receipt) + + require.NoError(t, o.DetectForcedMevPayment(fullBlock)) + require.NotNil(t, fullBlock.ForcedMevPayment) + require.Equal(t, forced, fullBlock.ForcedMevPayment.AmountWei) + }) +} + +// States saved before Gloas have none of the new fields, and must load with +// their hash intact. States with builder payments in flight must round trip +func Test_StateHash_BuilderPaymentFields(t *testing.T) { + newState := func(oracle *Oracle) *OracleState { + return &OracleState{ + PoolAccumulatedFees: big.NewInt(0), + Validators: make(map[uint64]*ValidatorInfo), + CommitedStates: make(map[uint64]*OnchainState), + SubscriptionEvents: make([]*contract.ContractSubscribeValidator, 0), + UnsubscriptionEvents: make([]*contract.ContractUnsubscribeValidator, 0), + EtherReceivedEvents: make([]*contract.ContractEtherReceived, 0), + Donations: make([]*contract.ContractEtherReceived, 0), + ProposedBlocks: []SummarizedBlock{{Slot: 10, Block: 9, Reward: big.NewInt(5), RewardType: VanilaBlock, BlockType: OkPoolProposal}}, + MissedBlocks: make([]SummarizedBlock, 0), + WrongFeeBlocks: make([]SummarizedBlock, 0), + PoolFeesPercentOver10000: oracle.cfg.PoolFeesPercentOver10000, + PoolAddress: oracle.cfg.PoolAddress, + Network: oracle.cfg.Network, + PoolFeesAddress: oracle.cfg.PoolFeesAddress, + CheckPointSizeInSlots: oracle.cfg.CheckPointSizeInSlots, + DeployedBlock: oracle.cfg.DeployedBlock, + DeployedSlot: oracle.cfg.DeployedSlot, + CollateralInWei: oracle.cfg.CollateralInWei, + } + } + + t.Run("state from before Gloas", func(t *testing.T) { + oracle := testOracle(Hoodi, 500) + rawBytes, err := serializeStateWithHash(newState(oracle)) + require.NoError(t, err) + require.NotContains(t, string(rawBytes), "builder_payment") + + found, err := oracle.LoadFromBytes(rawBytes) + require.NoError(t, err) + require.True(t, found) + }) + + t.Run("state with builder payments", func(t *testing.T) { + oracle := testOracle(Hoodi, 500) + state := newState(oracle) + state.ProposedBlocks[0].BuilderPaymentWei = big.NewInt(3) + state.InFlightBuilderPayments = []*BuilderPayment{inFlightPayment(10, 42, 48_200_000)} + rawBytes, err := serializeStateWithHash(state) + require.NoError(t, err) + + found, err := oracle.LoadFromBytes(rawBytes) + require.NoError(t, err) + require.True(t, found) + require.Equal(t, big.NewInt(3), oracle.state.ProposedBlocks[0].BuilderPaymentWei) + require.Equal(t, utils.GweiToWei(48_200_000), oracle.state.InFlightBuilderPayments[0].AmountWei) + }) +} diff --git a/oracle/forced_payment.go b/oracle/forced_payment.go index 4575834..9740c92 100644 --- a/oracle/forced_payment.go +++ b/oracle/forced_payment.go @@ -52,6 +52,10 @@ func (o *Onchain) detectAnyPositionForcedMevPayment(b *FullBlock, opts ...retry. return err } inflow := unexplainedPoolInflow(new(big.Int).Sub(after, before), b.Events) + // From Gloas, builder payments reach the pool as withdrawals, without any + // event. They are matched to the credited payments when the slot is + // processed, see settleArrivedBuilderPayments + inflow.Sub(inflow, b.BuilderWithdrawalsWeiTo(o.PoolAddress)) if inflow.Sign() == 0 { return nil } @@ -69,7 +73,7 @@ func (o *Onchain) detectAnyPositionForcedMevPayment(b *FullBlock, opts ...retry. return fmt.Errorf("read withdrawals at block %d: %w", blockNumber, err) } for _, withdrawal := range withdrawals { - if withdrawal.Amount > 0 && utils.Equals(withdrawal.Address.String(), o.PoolAddress) { + if withdrawal.Amount > 0 && utils.Equals(withdrawal.Address.String(), o.PoolAddress) && !isBuilderWithdrawal(withdrawal) { return fmt.Errorf("block %d credits a consensus withdrawal to the pool; cannot attribute unexplained inflow %s wei to MEV", blockNumber, inflow) } } diff --git a/oracle/gloas_proposal_test.go b/oracle/gloas_proposal_test.go index 11f0404..4d4575a 100644 --- a/oracle/gloas_proposal_test.go +++ b/oracle/gloas_proposal_test.go @@ -7,6 +7,7 @@ import ( v1 "github.com/attestantio/go-eth2-client/api/v1" "github.com/attestantio/go-eth2-client/spec/bellatrix" + "github.com/attestantio/go-eth2-client/spec/capella" "github.com/attestantio/go-eth2-client/spec/gloas" "github.com/attestantio/go-eth2-client/spec/phase0" "github.com/avast/retry-go/v4" @@ -63,13 +64,25 @@ type gloasScenario struct { payloadFeeRecipient string executionPaymentWei *big.Int tipsToPayloadFeeRec bool + withdrawals []*capella.Withdrawal + + // Default to testProposalSlot and execution block 5000 + slot uint64 + blockNumber uint64 } // Builds the FullBlock FetchFullBlock would have built for the scenario func (s gloasScenario) block(t *testing.T) *FullBlock { t.Helper() - bid := gloasBid(testProposalSlot, s.builder, s.bidValueGwei, s.bidFeeRecipient, 0xaa, 0xbb) - fullBlock := gloasFullBlock(t, testProposalSlot, testProposer, bid) + slot, blockNumber := s.slot, s.blockNumber + if slot == 0 { + slot = testProposalSlot + } + if blockNumber == 0 { + blockNumber = 5000 + } + bid := gloasBid(slot, s.builder, s.bidValueGwei, s.bidFeeRecipient, 0xaa, byte(slot)) + fullBlock := gloasFullBlock(t, slot, testProposer, bid) if fullBlock.BidPromisesPaymentTo(testPoolAddress) { fullBlock.SetBuilderPayment(s.included || s.withheldPaid) @@ -103,7 +116,7 @@ func (s gloasScenario) block(t *testing.T) *FullBlock { fullBlock.Events.EtherReceived = append(fullBlock.Events.EtherReceived, event) } - fullBlock.SetExecutionPayload(gloasEnvelope(bid, 5000, payloadFeeRecipient, txs, nil)) + fullBlock.SetExecutionPayload(gloasEnvelope(bid, blockNumber, payloadFeeRecipient, txs, s.withdrawals)) if receipts != nil { fullBlock.ExecutionReceipts = receipts } diff --git a/oracle/onchain.go b/oracle/onchain.go index 63e3ac0..aff31e5 100644 --- a/oracle/onchain.go +++ b/oracle/onchain.go @@ -910,9 +910,10 @@ func (o *Onchain) GetPoolEthBalance(blockNumber *big.Int, opts ...retry.Option) // read the block computes the same result, now and on any future resync. // // Note it does not model beacon chain withdrawals credited to the pool address. -// That cannot happen with the current pool contract, and if it ever did the -// result would be an unexpected value that fails the exact match below, which -// is the safe direction: it never turns a missing payment into a valid one. +// From Gloas, builder payments arrive that way, and DetectForcedMevPayment +// subtracts them. Any other withdrawal to the pool would be an unexpected value +// that fails the exact match, which is the safe direction: it never turns a +// missing payment into a valid one. func unexplainedPoolInflow(balanceDelta *big.Int, events *Events) *big.Int { explained := big.NewInt(0) diff --git a/oracle/oracle.go b/oracle/oracle.go index e38705e..a5eeb99 100644 --- a/oracle/oracle.go +++ b/oracle/oracle.go @@ -183,6 +183,12 @@ func (or *Oracle) AdvanceStateToNextSlot(fullBlock *FullBlock) (uint64, error) { return 0, errors.Wrap(err, "Error validating full block config") } + // Builder payments credited in earlier slots may reach the pool in this one + err = or.settleArrivedBuilderPayments(fullBlock) + if err != nil { + return 0, errors.Wrap(err, "Error settling builder payments") + } + // Full block is too heavy to be stored in the state, so we summarize it summarizedBlock := fullBlock.SummarizedBlock(or, or.cfg.PoolAddress) @@ -224,6 +230,11 @@ func (or *Oracle) AdvanceStateToNextSlot(fullBlock *FullBlock) (uint64, error) { or.handleBanValidator(summarizedBlock) } + // Credited above, but only reaches the pool in a later slot + if summarizedBlock.BuilderPaymentWei != nil { + or.trackBuilderPayment(fullBlock.BuilderPayment) + } + // Handle unsubscriptions the last thing after distributing rewards or.handleManualUnsubscriptions(fullBlock.Events.UnsubscribeValidator, fullBlock.ValidatorsUnsubs) @@ -898,12 +909,19 @@ func (or *Oracle) RunOnchainReconciliation( log.Info("[Reconciliation] Total pool balance (what we have): ", contractBalanceWei) - if totalLiabilities.Cmp(contractBalanceWei) != 0 { - return errors.New(fmt.Sprintf("[Reconciliation] Liabilities and balance dont match: %d vs %d", - totalLiabilities, contractBalanceWei)) + // Builder payments already credited but not in the pool yet. The pool + // will hold them once their withdrawal is processed + inFlight := or.inFlightBuilderPaymentsWei() + assets := new(big.Int).Add(contractBalanceWei, inFlight) + + log.Info("[Reconciliation] Builder payments on their way to the pool: ", inFlight) + + if totalLiabilities.Cmp(assets) != 0 { + return errors.New(fmt.Sprintf("[Reconciliation] Liabilities and balance dont match: %d vs %d (balance %d + in flight %d)", + totalLiabilities, assets, contractBalanceWei, inFlight)) } - log.Info("[Reconciliation] Success! Liabilities and balance match: ", totalLiabilities, " vs ", contractBalanceWei) + log.Info("[Reconciliation] Success! Liabilities and balance match: ", totalLiabilities, " vs ", assets) return nil } diff --git a/oracle/types.go b/oracle/types.go index babdf63..c89dc4b 100644 --- a/oracle/types.go +++ b/oracle/types.go @@ -164,9 +164,6 @@ type BuilderPayment struct { // False when the protocol dropped the payment: the payload was withheld // and the beacon block got too few votes, or the proposer was slashed Paid bool `json:"paid"` - - // Execution block whose withdrawals paid it. Zero while it is in flight - ArrivalBlock uint64 `json:"arrival_block,omitempty"` } type FullBlock struct { @@ -270,6 +267,12 @@ type OracleState struct { // Stores a subset of EtherReceived events, just donations Donations []*contract.ContractEtherReceived `json:"donations"` + // Builder payments to the pool already credited, whose withdrawal has not + // reached the pool yet. They are part of what the pool has, see + // RunOnchainReconciliation. Omitted when empty, so states saved before + // Gloas keep their hash + InFlightBuilderPayments []*BuilderPayment `json:"in_flight_builder_payments,omitempty"` + // Summarized versions of the blocks ProposedBlocks []SummarizedBlock `json:"proposed_blocks"` MissedBlocks []SummarizedBlock `json:"missed_blocks"` From 75abbb21e04c288e93d9183a6a037ed7b2fca726 Mon Sep 17 00:00:00 2001 From: Marketen Date: Thu, 22 Oct 2026 18:32:55 +0200 Subject: [PATCH 7/9] Count the oracle in sync against its latest settled slot From the Gloas fork on, the oracle processes a slot only once the epoch after it is finalized, so in sync it trails the finalized slot by 33 slots. The API still measured sync against the finalized slot: - /status would report is_oracle_in_sync false forever, since it required the processed slot to equal the finalized one. - OracleReady(64), which gates the proofs and validators endpoints, allows 64 slots behind finality. Right after each epoch is finalized the oracle is 65 behind until it processes it, so those endpoints would refuse requests briefly every epoch. LatestSettledSlot returns the latest slot the oracle can process given the finalized one. The main loop, /status and OracleReady now all use it, so they can't disagree, and a test checks it against the per-slot settlement rule by brute force. oracle_sync_distance_slots and the time to the next checkpoint are counted from it too. Before the fork it is the finalized slot, so nothing changes until then. The distance_from_finalized_slot metric keeps its meaning, so from the fork on it will read about 33 when the oracle is in sync. Co-Authored-By: Claude Opus 5.5 --- api/api.go | 38 +++++++++++++++++--------------------- api/api_test.go | 30 ++++++++++++++++++++++++++++++ main.go | 4 ++-- oracle/gloas.go | 28 +++++++++++++++++++++++++++- oracle/gloas_test.go | 39 +++++++++++++++++++++++++++++++++------ 5 files changed, 109 insertions(+), 30 deletions(-) diff --git a/api/api.go b/api/api.go index 8c42474..f94a7b2 100644 --- a/api/api.go +++ b/api/api.go @@ -462,10 +462,9 @@ func (m *ApiService) handleStatus(w http.ResponseWriter, req *http.Request) { finalizedSlot := uint64(finality.Header.Message.Slot) - oracleSync := false - if m.oracle.State().LatestProcessedSlot-finalizedSlot == 0 { - oracleSync = true - } + // From Gloas on the oracle trails finality by design, see LatestSettledSlot + latestSettledSlot := oracle.LatestSettledSlot(m.Onchain.ChainId, finalizedSlot) + oracleSync, oracleDistance := syncDistance(latestSettledSlot, m.oracle.State().LatestProcessedSlot) _, onchainSlot, err := m.Onchain.GetOnchainSlotAndRoot(apiRetryOpts...) if err != nil { @@ -476,8 +475,8 @@ func (m *ApiService) handleStatus(w http.ResponseWriter, req *http.Request) { // If the oracle is not in sync, we cant really calculate the slots till the next checkpoint // because we are behind. So we just set it to 0 nextCheckpointInSlots := uint64(0) - if finalizedSlot < (onchainSlot + m.cfg.CheckPointSizeInSlots) { - nextCheckpointInSlots = onchainSlot + m.cfg.CheckPointSizeInSlots - finalizedSlot + if latestSettledSlot < (onchainSlot + m.cfg.CheckPointSizeInSlots) { + nextCheckpointInSlots = onchainSlot + m.cfg.CheckPointSizeInSlots - latestSettledSlot } status := httpOkStatus{ @@ -488,7 +487,7 @@ func (m *ApiService) handleStatus(w http.ResponseWriter, req *http.Request) { LatestProcessedBlock: m.oracle.State().LatestProcessedBlock, LatestFinalizedEpoch: finalizedSlot / 32, LatestFinalizedSlot: finalizedSlot, - OracleHeadDistance: finalizedSlot - m.oracle.State().LatestProcessedSlot, + OracleHeadDistance: oracleDistance, NextCheckpointSlot: onchainSlot + m.cfg.CheckPointSizeInSlots, NextCheckpointTime: "", // TODO: NextCheckpointRemaining: utils.SlotsToTime(nextCheckpointInSlots, constants.SecondsInSlot), @@ -1259,23 +1258,20 @@ func (m *ApiService) OracleReady(maxSlotsBehind uint64) bool { } finalizedSlot := uint64(finality.Header.Message.Slot) - if err != nil { - return false - } + latestSettledSlot := oracle.LatestSettledSlot(m.Onchain.ChainId, finalizedSlot) - slotsFromFinalized := finalizedSlot - m.oracle.State().LatestProcessedSlot - - // Use this if we want full in sync to latest finalized - /*oracleInSync := false - if slotsFromFinalized == 0 { - oracleInSync = true - } - _ = oracleInSync*/ + _, slotsBehind := syncDistance(latestSettledSlot, m.oracle.State().LatestProcessedSlot) + return slotsBehind <= maxSlotsBehind +} - if slotsFromFinalized > maxSlotsBehind { - return false +// Returns whether the oracle processed every slot it can, and how many slots +// it still has to. It can process up to the latest settled slot, which before +// Gloas is the latest finalized one +func syncDistance(latestSettledSlot uint64, latestProcessedSlot uint64) (bool, uint64) { + if latestProcessedSlot >= latestSettledSlot { + return true, 0 } - return true + return false, latestSettledSlot - latestProcessedSlot } func GetSubInBlock(subs []Subscription, block uint64) []Subscription { diff --git a/api/api_test.go b/api/api_test.go index 09a284d..3f00cc3 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -314,3 +314,33 @@ func Test_ApiEndpoint(t *testing.T) { require.Equal(t, 1, 1) */ } + +func Test_SyncDistance(t *testing.T) { + inSync, distance := syncDistance(1000, 1000) + require.True(t, inSync) + require.Zero(t, distance) + + inSync, distance = syncDistance(1000, 960) + require.False(t, inSync) + require.Equal(t, uint64(40), distance) +} + +// From Gloas on, an oracle that processed every settled slot is in sync even if +// it trails finality, and its distance is counted from the latest settled slot +func Test_SyncDistance_FromGloas(t *testing.T) { + forkSlot := oracle.GloasForkSlot[oracle.HoodiChainId] + finalized := forkSlot + 64 + latestSettled := oracle.LatestSettledSlot(oracle.HoodiChainId, finalized) + require.Equal(t, finalized-33, latestSettled) + + inSync, distance := syncDistance(latestSettled, latestSettled) + require.True(t, inSync) + require.Zero(t, distance) + + inSync, distance = syncDistance(latestSettled, latestSettled-10) + require.False(t, inSync) + require.Equal(t, uint64(10), distance) + + // Before the fork nothing changes: the finalized slot is the settled one + require.Equal(t, forkSlot-100, oracle.LatestSettledSlot(oracle.HoodiChainId, forkSlot-100)) +} diff --git a/main.go b/main.go index b3e5e09..904511a 100644 --- a/main.go +++ b/main.go @@ -254,9 +254,9 @@ func mainLoop(oracleInstance *oracle.Oracle, onchain *oracle.Onchain, cfg *oracl finalizedSlot := uint64(finalizedBlockHeader.Header.Message.Slot) // From Gloas on, a slot is only settled some time after it is finalized - settlementSlot := oracle.SettlementSlot(onchain.ChainId, oracleInstance.State().NextSlotToProcess) + latestSettledSlot := oracle.LatestSettledSlot(onchain.ChainId, finalizedSlot) - if finalizedSlot >= settlementSlot { + if oracleInstance.State().NextSlotToProcess <= latestSettledSlot { // Fetch block information fullBlock := onchain.FetchFullBlock(oracleInstance.State().NextSlotToProcess, oracleInstance) diff --git a/oracle/gloas.go b/oracle/gloas.go index 91a7292..229c9f5 100644 --- a/oracle/gloas.go +++ b/oracle/gloas.go @@ -41,13 +41,39 @@ func IsGloasSlot(chainId uint64, slot uint64) bool { // by the next beacon block, and whether a bid whose payload was withheld is still // paid is decided at the end of the following epoch. Waiting until that epoch is // finalized covers both, at the cost of trailing finality by about one epoch. -func SettlementSlot(chainId uint64, slot uint64) uint64 { +func settlementSlot(chainId uint64, slot uint64) uint64 { if !IsGloasSlot(chainId, slot) { return slot } return builderPaymentDecisionSlot(slot) } +// Returns the latest slot that can be processed when finalizedSlot is the +// latest finalized one, ie the latest slot whose settlementSlot is not after +// it. An oracle that processed it is in sync, even if it trails finality. +func LatestSettledSlot(chainId uint64, finalizedSlot uint64) uint64 { + forkSlot, found := GloasForkSlot[chainId] + if !found || finalizedSlot < forkSlot { + return finalizedSlot + } + + // Number of epochs whose last slot is finalized. A Gloas slot of epoch e is + // settled when the last slot of epoch e+1 is, ie when e+2 epochs are + settledEpochs := (finalizedSlot + 1) / constants.SlotsInEpoch + if settledEpochs >= 2 { + latestSettledGloasSlot := (settledEpochs-1)*constants.SlotsInEpoch - 1 + if latestSettledGloasSlot >= forkSlot { + return latestSettledGloasSlot + } + } + + // No Gloas slot is settled yet, but every slot before the fork is + if forkSlot == 0 { + return 0 + } + return forkSlot - 1 +} + // The last slot of the epoch after the given slot's one. The protocol decides // whether a withheld payload's bid is paid in the epoch transition right after // it, so its beacon state holds what that decision is based on diff --git a/oracle/gloas_test.go b/oracle/gloas_test.go index 8870e2f..e825e57 100644 --- a/oracle/gloas_test.go +++ b/oracle/gloas_test.go @@ -116,17 +116,44 @@ func Test_IsGloasSlot(t *testing.T) { func Test_SettlementSlot(t *testing.T) { // Before Gloas a finalized slot is settled - require.Equal(t, testGloasSlot-1, SettlementSlot(HoodiChainId, testGloasSlot-1)) - require.Equal(t, uint64(20_000_000), SettlementSlot(MainnetChainId, 20_000_000)) + require.Equal(t, testGloasSlot-1, settlementSlot(HoodiChainId, testGloasSlot-1)) + require.Equal(t, uint64(20_000_000), settlementSlot(MainnetChainId, 20_000_000)) // From Gloas on, wait until the epoch after the slot's one is finalized. // The fork slot is the first of epoch 132352 require.Equal(t, uint64(132352*32), testGloasSlot) lastSlotOfNextEpoch := uint64(132354*32 - 1) - require.Equal(t, lastSlotOfNextEpoch, SettlementSlot(HoodiChainId, testGloasSlot)) - require.Equal(t, lastSlotOfNextEpoch, SettlementSlot(HoodiChainId, testGloasSlot+17)) - require.Equal(t, lastSlotOfNextEpoch, SettlementSlot(HoodiChainId, testGloasSlot+31)) - require.Equal(t, lastSlotOfNextEpoch+32, SettlementSlot(HoodiChainId, testGloasSlot+32)) + require.Equal(t, lastSlotOfNextEpoch, settlementSlot(HoodiChainId, testGloasSlot)) + require.Equal(t, lastSlotOfNextEpoch, settlementSlot(HoodiChainId, testGloasSlot+17)) + require.Equal(t, lastSlotOfNextEpoch, settlementSlot(HoodiChainId, testGloasSlot+31)) + require.Equal(t, lastSlotOfNextEpoch+32, settlementSlot(HoodiChainId, testGloasSlot+32)) +} + +func Test_LatestSettledSlot(t *testing.T) { + // Before Gloas, and on chains without it, every finalized slot is settled + require.Equal(t, uint64(20_000_000), LatestSettledSlot(MainnetChainId, 20_000_000)) + require.Equal(t, testGloasSlot-1, LatestSettledSlot(HoodiChainId, testGloasSlot-1)) + + // Right after the fork only the slots before it are settled + require.Equal(t, testGloasSlot-1, LatestSettledSlot(HoodiChainId, testGloasSlot)) + require.Equal(t, testGloasSlot-1, LatestSettledSlot(HoodiChainId, testGloasSlot+62)) + + // The first Gloas epoch settles with the last slot of the next one + require.Equal(t, testGloasSlot+31, LatestSettledSlot(HoodiChainId, testGloasSlot+63)) + // An oracle in sync trails a finalized epoch boundary by 33 slots + require.Equal(t, testGloasSlot+64-33, LatestSettledSlot(HoodiChainId, testGloasSlot+64)) +} + +// LatestSettledSlot is the inverse of settlementSlot: the latest slot that +// settlementSlot allows processing. Check it against a brute force search +func Test_LatestSettledSlot_MatchesSettlementSlot(t *testing.T) { + for finalized := testGloasSlot - 70; finalized < testGloasSlot+300; finalized++ { + expected := finalized + for settlementSlot(HoodiChainId, expected) > finalized { + expected-- + } + require.Equal(t, expected, LatestSettledSlot(HoodiChainId, finalized), "finalized slot %d", finalized) + } } func Test_GloasBlock_FullSlot(t *testing.T) { From b669fbd9f9973a275652accade7784828cf8ee6f Mon Sep 17 00:00:00 2001 From: Marketen Date: Thu, 22 Oct 2026 18:33:12 +0200 Subject: [PATCH 8/9] Decide exactly whether an included bid pays the pool A bid whose payload the next beacon block built on was assumed paid. The next block does settle it before anything else, but slashing the proposer cancels a pending payment, and a slashing of the proposer included in its own beacon block happens before that. It is not as unlikely as it sounds: a validator run on two machines gets slashed with evidence that its own node may then include. Had it happened, the oracle would have credited ETH that never comes, and the onchain reconciliation would have counted it in flight forever, hiding that the pool lacks it rather than stopping. So a full slot's payment is now checked like a withheld one's, against the beacon state: it is paid if its builder_pending_payments entry survived its own beacon block. The exception, also from the spec, is a next beacon block two or more epochs later, which appends the payment directly whatever that entry says. Only read for bids paying the pool, and the endpoint returns 64 entries. A cancelled payment is not credited nor tracked. The proposer still chose a bid paying the pool, so it is not banned. Co-Authored-By: Claude Opus 5.5 --- oracle/builder_payments_test.go | 16 ++++++++ oracle/gloas.go | 73 +++++++++++++++++++++++++-------- oracle/gloas_onchain.go | 56 ++++++++++++++++--------- oracle/gloas_payment_test.go | 60 +++++++++++++++++++++++++++ oracle/gloas_proposal_test.go | 29 ++++++++++--- oracle/gloas_test.go | 17 ++++---- 6 files changed, 203 insertions(+), 48 deletions(-) diff --git a/oracle/builder_payments_test.go b/oracle/builder_payments_test.go index 8035c45..75fb02f 100644 --- a/oracle/builder_payments_test.go +++ b/oracle/builder_payments_test.go @@ -316,3 +316,19 @@ func Test_StateHash_BuilderPaymentFields(t *testing.T) { require.Equal(t, utils.GweiToWei(48_200_000), oracle.state.InFlightBuilderPayments[0].AmountWei) }) } + +// A cancelled payment is never tracked, so the onchain reconciliation does not +// count ETH that will never come +func Test_AdvanceStateToNextSlot_CancelledPaymentIsNotTracked(t *testing.T) { + oracle := gloasTestOracle(t) + oracle.addSubscription(uint64(testProposer), "0x1111111111111111111111111111111111111111", "0x") + + fullBlock := gloasScenario{builder: 42, bidValueGwei: testBidValueGwei, bidFeeRecipient: testPoolAddress, included: true, + paymentCancelled: true, payloadFeeRecipient: testBuilderAddress}.block(t) + _, err := oracle.AdvanceStateToNextSlot(fullBlock) + require.NoError(t, err) + + require.Empty(t, oracle.state.InFlightBuilderPayments) + require.NoError(t, oracle.RunOffchainReconciliation()) + require.NoError(t, oracle.RunOnchainReconciliation(big.NewInt(0), nil)) +} diff --git a/oracle/gloas.go b/oracle/gloas.go index 229c9f5..e5b5735 100644 --- a/oracle/gloas.go +++ b/oracle/gloas.go @@ -99,38 +99,79 @@ func builderPaymentQuorum(totalActiveBalance phase0.Gwei) phase0.Gwei { return perSlotBalance * builderPaymentThresholdNumerator / builderPaymentThresholdDenominator } -// Whether the protocol pays a bid whose execution payload was withheld. It -// does if the votes its beacon block got in its own slot reach the quorum, -// unless the payment was cancelled before, as slashing the proposer does. -// -// pendingPayments and totalActiveBalance must come from the beacon state at -// builderPaymentDecisionSlot, which is just before the protocol decides it in -// process_builder_pending_payments. Effective balances only change after that -// step, so the quorum calculated here is the one the protocol uses. -func isWithheldBidPaid(bid *gloas.ExecutionPayloadBid, proposerIndex phase0.ValidatorIndex, - pendingPayments []*gloas.BuilderPendingPayment, totalActiveBalance phase0.Gwei) (bool, error) { +// Returns the pending payment of the bid, read from the beacon state's +// builder_pending_payments: the first half holds the payments of the previous +// epoch, the second half those of the current one. Nil if its entry is empty, +// which is what cancelling a payment does, as slashing the proposer does. +func pendingPaymentOfBid(bid *gloas.ExecutionPayloadBid, proposerIndex phase0.ValidatorIndex, + pendingPayments []*gloas.BuilderPendingPayment, ofCurrentEpoch bool) (*gloas.BuilderPendingPayment, error) { if uint64(len(pendingPayments)) != 2*constants.SlotsInEpoch { - return false, errors.New(fmt.Sprintf("expected %d builder pending payments, got %d", + return nil, errors.New(fmt.Sprintf("expected %d builder pending payments, got %d", 2*constants.SlotsInEpoch, len(pendingPayments))) } - // The first half holds the payments of the previous epoch, the bid's one - payment := pendingPayments[uint64(bid.Slot)%constants.SlotsInEpoch] + index := uint64(bid.Slot) % constants.SlotsInEpoch + if ofCurrentEpoch { + index += constants.SlotsInEpoch + } + payment := pendingPayments[index] - // An empty entry means the payment was cancelled if payment == nil || payment.Withdrawal == nil || payment.Withdrawal.Amount == 0 { - return false, nil + return nil, nil } if payment.Withdrawal.BuilderIndex != bid.BuilderIndex || payment.Withdrawal.Amount != bid.Value || payment.Withdrawal.FeeRecipient != bid.FeeRecipient || payment.ProposerIndex != proposerIndex { - return false, errors.New(fmt.Sprintf("builder pending payment of slot %d does not match its bid. "+ + return nil, errors.New(fmt.Sprintf("builder pending payment of slot %d does not match its bid. "+ "payment: %s, bid: %s", bid.Slot, payment.String(), bid.String())) } + return payment, nil +} + +// Whether the protocol pays the bid of a full slot, whose execution payload the +// next beacon block built on. That block settles the payment before processing +// anything else (apply_parent_execution_payload), so it is paid unless it was +// cancelled before: only a slashing of the proposer included in its own beacon +// block can do that, which happens to validators running on two machines, whose +// slashing evidence their own node then includes. +// +// pendingPayments must come from the beacon state right after the beacon block +// of the bid's slot. When the next beacon block is two epochs later or more, +// the protocol appends the payment directly, regardless of that state. +func isIncludedBidPaid(bid *gloas.ExecutionPayloadBid, proposerIndex phase0.ValidatorIndex, + nextBlockSlot uint64, pendingPayments []*gloas.BuilderPendingPayment) (bool, error) { + + bidEpoch := uint64(bid.Slot) / constants.SlotsInEpoch + if nextBlockSlot/constants.SlotsInEpoch >= bidEpoch+2 { + return true, nil + } + payment, err := pendingPaymentOfBid(bid, proposerIndex, pendingPayments, true) + if err != nil { + return false, err + } + return payment != nil, nil +} + +// Whether the protocol pays a bid whose execution payload was withheld. It +// does if the votes its beacon block got in its own slot reach the quorum, +// unless the payment was cancelled before, as slashing the proposer does. +// +// pendingPayments and totalActiveBalance must come from the beacon state at +// builderPaymentDecisionSlot, which is just before the protocol decides it in +// process_builder_pending_payments. Effective balances only change after that +// step, so the quorum calculated here is the one the protocol uses. +func isWithheldBidPaid(bid *gloas.ExecutionPayloadBid, proposerIndex phase0.ValidatorIndex, + pendingPayments []*gloas.BuilderPendingPayment, totalActiveBalance phase0.Gwei) (bool, error) { + + // By then the bid's epoch is the previous one + payment, err := pendingPaymentOfBid(bid, proposerIndex, pendingPayments, false) + if err != nil || payment == nil { + return false, err + } return payment.Weight >= builderPaymentQuorum(totalActiveBalance), nil } diff --git a/oracle/gloas_onchain.go b/oracle/gloas_onchain.go index 15811d7..e3f72f8 100644 --- a/oracle/gloas_onchain.go +++ b/oracle/gloas_onchain.go @@ -14,6 +14,7 @@ import ( "github.com/attestantio/go-eth2-client/spec/gloas" "github.com/attestantio/go-eth2-client/spec/phase0" "github.com/avast/retry-go/v4" + "github.com/dappnode/mev-sp-oracle/constants" "github.com/pkg/errors" log "github.com/sirupsen/logrus" ) @@ -46,11 +47,12 @@ func (o *Onchain) GetExecutionPayloadEnvelope(slot uint64, opts ...retry.Option) } // Returns whether the execution payload the bid of the given slot committed to -// became part of the chain, ie whether the slot is full rather than empty -func (o *Onchain) IsExecutionPayloadIncluded(slot uint64, bid *gloas.ExecutionPayloadBid, opts ...retry.Option) (bool, error) { +// became part of the chain, ie whether the slot is full rather than empty, and +// the slot of the next beacon block, which decided it +func (o *Onchain) IsExecutionPayloadIncluded(slot uint64, bid *gloas.ExecutionPayloadBid, opts ...retry.Option) (bool, uint64, error) { finalized, err := o.FinalizedBeaconBlockHeader(opts...) if err != nil { - return false, errors.Wrap(err, "could not get finalized beacon block header") + return false, 0, errors.Wrap(err, "could not get finalized beacon block header") } blockAtSlot := func(slot uint64) (*spec.VersionedSignedBeaconBlock, error) { return o.GetConsensusBlockAtSlot(slot, opts...) @@ -66,24 +68,24 @@ func isExecutionPayloadIncluded( slot uint64, finalizedSlot uint64, bid *gloas.ExecutionPayloadBid, - blockAtSlot func(uint64) (*spec.VersionedSignedBeaconBlock, error)) (bool, error) { + blockAtSlot func(uint64) (*spec.VersionedSignedBeaconBlock, error)) (bool, uint64, error) { for nextSlot := slot + 1; nextSlot <= finalizedSlot; nextSlot++ { nextBlock, err := blockAtSlot(nextSlot) if err != nil { - return false, errors.Wrap(err, fmt.Sprintf("could not get beacon block at slot %d", nextSlot)) + return false, 0, errors.Wrap(err, fmt.Sprintf("could not get beacon block at slot %d", nextSlot)) } // Missed slot, keep looking if nextBlock == nil { continue } if nextBlock.Gloas == nil { - return false, errors.New(fmt.Sprintf("beacon block at slot %d is not a Gloas one", nextSlot)) + return false, 0, errors.New(fmt.Sprintf("beacon block at slot %d is not a Gloas one", nextSlot)) } nextBid := nextBlock.Gloas.Message.Body.SignedExecutionPayloadBid.Message - return nextBid.ParentBlockHash == bid.BlockHash, nil + return nextBid.ParentBlockHash == bid.BlockHash, nextSlot, nil } - return false, errors.New(fmt.Sprintf("no finalized beacon block after slot %d yet, "+ + return false, 0, errors.New(fmt.Sprintf("no finalized beacon block after slot %d yet, "+ "cant tell whether its execution payload was included", slot)) } @@ -95,23 +97,22 @@ func (o *Onchain) fetchGloasSlot(fullBlock *FullBlock) bool { slot := fullBlock.GetSlotUint64() bid := fullBlock.GetExecutionPayloadBid() - included, err := o.IsExecutionPayloadIncluded(slot, bid) + included, nextBlockSlot, err := o.IsExecutionPayloadIncluded(slot, bid) if err != nil { log.Fatal("could not tell whether the execution payload of slot ", slot, " was included: ", err) } + // Whether the payment is made has to be exact: a payment credited but never + // made would be counted in flight forever, hiding that the pool lacks it if fullBlock.BidPromisesPaymentTo(o.PoolAddress) { - // A payload the next beacon block builds on is paid: that block settles - // the payment before processing anything else. Before that, only the - // proposer's slashing included in its own beacon block could cancel it, - // which no proposer would do. If it ever happened, the payment would - // never arrive and the onchain reconciliation would stop the oracle - paid := included - if !included { + var paid bool + if included { + paid, err = o.IsIncludedBidPaid(fullBlock, nextBlockSlot) + } else { paid, err = o.IsWithheldBidPaid(fullBlock) - if err != nil { - log.Fatal("could not tell whether the withheld bid of slot ", slot, " is paid: ", err) - } + } + if err != nil { + log.Fatal("could not tell whether the bid of slot ", slot, " is paid: ", err) } fullBlock.SetBuilderPayment(paid) } @@ -132,6 +133,23 @@ func (o *Onchain) fetchGloasSlot(fullBlock *FullBlock) bool { return true } +// Returns whether the protocol pays the bid of a full slot, reading the beacon +// state right after its beacon block. See isIncludedBidPaid +func (o *Onchain) IsIncludedBidPaid(fullBlock *FullBlock, nextBlockSlot uint64, opts ...retry.Option) (bool, error) { + slot := fullBlock.GetSlotUint64() + var pendingPayments []*gloas.BuilderPendingPayment + + // When the payment is made regardless of the state, don't read it + if nextBlockSlot/constants.SlotsInEpoch < slot/constants.SlotsInEpoch+2 { + var err error + pendingPayments, err = o.GetBuilderPendingPayments(strconv.FormatUint(slot, 10), opts...) + if err != nil { + return false, err + } + } + return isIncludedBidPaid(fullBlock.GetExecutionPayloadBid(), fullBlock.GetProposerIndex(), nextBlockSlot, pendingPayments) +} + // Returns whether the protocol pays the bid of an empty slot, reading the // beacon state the protocol bases that decision on. See isWithheldBidPaid func (o *Onchain) IsWithheldBidPaid(fullBlock *FullBlock, opts ...retry.Option) (bool, error) { diff --git a/oracle/gloas_payment_test.go b/oracle/gloas_payment_test.go index 9360f98..b7d1fd8 100644 --- a/oracle/gloas_payment_test.go +++ b/oracle/gloas_payment_test.go @@ -206,3 +206,63 @@ func Test_TotalActiveBalance(t *testing.T) { require.Equal(t, (32+2048+31)*ethInGwei, totalActiveBalance(validators)) require.Zero(t, totalActiveBalance(nil)) } + +// Right after the bid's beacon block, its payment is in the second half of the +// builder pending payments, which holds the current epoch +func pendingPaymentsAfterBlock(slot uint64, payment *gloas.BuilderPendingPayment) []*gloas.BuilderPendingPayment { + payments := pendingPaymentsWith(slot, &gloas.BuilderPendingPayment{Withdrawal: &gloas.BuilderPendingWithdrawal{}}) + payments[constants.SlotsInEpoch+slot%constants.SlotsInEpoch] = payment + return payments +} + +func Test_IsIncludedBidPaid(t *testing.T) { + slot := testGloasSlot + 5 + proposer := phase0.ValidatorIndex(1000) + bid := gloasBid(slot, 42, 48_200_000, testPoolAddress, 0xaa, 0xbb) + pending := &gloas.BuilderPendingPayment{ + ProposerIndex: proposer, + Withdrawal: &gloas.BuilderPendingWithdrawal{ + FeeRecipient: bid.FeeRecipient, + Amount: bid.Value, + BuilderIndex: bid.BuilderIndex, + }, + } + // What slashing the proposer leaves behind + cancelled := &gloas.BuilderPendingPayment{Withdrawal: &gloas.BuilderPendingWithdrawal{}} + epochAfterNext := (slot/constants.SlotsInEpoch + 2) * constants.SlotsInEpoch + + tests := []struct { + name string + nextBlockSlot uint64 + payments []*gloas.BuilderPendingPayment + paid bool + err string + }{ + {"next slot builds on it", slot + 1, pendingPaymentsAfterBlock(slot, pending), true, ""}, + {"next epoch builds on it", epochAfterNext - 1, pendingPaymentsAfterBlock(slot, pending), true, ""}, + {"cancelled in its own beacon block", slot + 1, pendingPaymentsAfterBlock(slot, cancelled), false, ""}, + {"cancelled, next epoch builds on it", epochAfterNext - 1, pendingPaymentsAfterBlock(slot, cancelled), false, ""}, + // apply_parent_execution_payload appends a parent older than the + // previous epoch directly, whatever its pending payment entry says + {"two epochs later builds on it", epochAfterNext, nil, true, ""}, + {"previous epoch half is not this bid's", slot + 1, pendingPaymentsWith(slot, pending), false, ""}, + {"does not match the bid", slot + 1, pendingPaymentsAfterBlock(slot, func() *gloas.BuilderPendingPayment { + p := *pending + p.ProposerIndex = 1001 + return &p + }()), false, "does not match its bid"}, + {"not a full vector", slot + 1, pendingPaymentsAfterBlock(slot, pending)[:32], false, "expected 64"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + paid, err := isIncludedBidPaid(bid, proposer, tt.nextBlockSlot, tt.payments) + if tt.err != "" { + require.ErrorContains(t, err, tt.err) + return + } + require.NoError(t, err) + require.Equal(t, tt.paid, paid) + }) + } +} diff --git a/oracle/gloas_proposal_test.go b/oracle/gloas_proposal_test.go index 4d4575a..737883d 100644 --- a/oracle/gloas_proposal_test.go +++ b/oracle/gloas_proposal_test.go @@ -54,11 +54,12 @@ type gloasScenario struct { bidValueGwei uint64 bidFeeRecipient string - // Whether the next beacon block built on the payload, and when it did - // not, whether the protocol still paid the bid - included bool - withheldPaid bool - bidPaidToPool bool + // Whether the next beacon block built on the payload, and whether the + // protocol paid the bid: when it did, unless its payment was cancelled, + // and when it did not, if its beacon block got the votes + included bool + paymentCancelled bool + withheldPaid bool // Payload contents, for full slots payloadFeeRecipient string @@ -85,7 +86,11 @@ func (s gloasScenario) block(t *testing.T) *FullBlock { fullBlock := gloasFullBlock(t, slot, testProposer, bid) if fullBlock.BidPromisesPaymentTo(testPoolAddress) { - fullBlock.SetBuilderPayment(s.included || s.withheldPaid) + paid := s.withheldPaid + if s.included { + paid = !s.paymentCancelled + } + fullBlock.SetBuilderPayment(paid) } if !s.included { return fullBlock @@ -193,6 +198,18 @@ func Test_SummarizedBlock_GloasProposals(t *testing.T) { blockType: MissedProposal, reward: func(*FullBlock) *big.Int { return big.NewInt(0) }, }, + { + // The proposer was slashed in its own beacon block, which cancels + // the payment. Nothing reached the pool, but the proposer chose a + // bid paying it, so it is not banned + name: "bid paid to the pool, payment cancelled", + scenario: gloasScenario{builder: 42, bidValueGwei: testBidValueGwei, bidFeeRecipient: testPoolAddress, included: true, + paymentCancelled: true, payloadFeeRecipient: testBuilderAddress}, + blockType: OkPoolProposal, + rewardType: MevBlock, + reward: func(*FullBlock) *big.Int { return big.NewInt(0) }, + hasExecutionBlock: true, + }, { name: "bid and execution payment, both to the pool", scenario: gloasScenario{builder: 42, bidValueGwei: testBidValueGwei, bidFeeRecipient: testPoolAddress, included: true, diff --git a/oracle/gloas_test.go b/oracle/gloas_test.go index e825e57..21d991f 100644 --- a/oracle/gloas_test.go +++ b/oracle/gloas_test.go @@ -289,32 +289,35 @@ func Test_IsExecutionPayloadIncluded(t *testing.T) { } t.Run("next beacon block builds on the payload", func(t *testing.T) { - included, err := isExecutionPayloadIncluded(slot, slot+64, bid, chain(map[uint64]*spec.VersionedSignedBeaconBlock{ + included, nextSlot, err := isExecutionPayloadIncluded(slot, slot+64, bid, chain(map[uint64]*spec.VersionedSignedBeaconBlock{ slot + 1: buildsOnThisPayload, })) require.NoError(t, err) require.True(t, included) + require.Equal(t, slot+1, nextSlot) }) t.Run("next beacon block skips the payload", func(t *testing.T) { - included, err := isExecutionPayloadIncluded(slot, slot+64, bid, chain(map[uint64]*spec.VersionedSignedBeaconBlock{ + included, nextSlot, err := isExecutionPayloadIncluded(slot, slot+64, bid, chain(map[uint64]*spec.VersionedSignedBeaconBlock{ slot + 1: skipsThisPayload, })) require.NoError(t, err) require.False(t, included) + require.Equal(t, slot+1, nextSlot) }) t.Run("missed slots are skipped until the next beacon block", func(t *testing.T) { buildsAfterMissedSlots := gloasBeaconBlock(slot+4, 8, gloasBid(slot+4, 43, 1, testPoolAddress, 0xbb, 0xcc)) - included, err := isExecutionPayloadIncluded(slot, slot+64, bid, chain(map[uint64]*spec.VersionedSignedBeaconBlock{ + included, nextSlot, err := isExecutionPayloadIncluded(slot, slot+64, bid, chain(map[uint64]*spec.VersionedSignedBeaconBlock{ slot + 4: buildsAfterMissedSlots, })) require.NoError(t, err) require.True(t, included) + require.Equal(t, slot+4, nextSlot) }) t.Run("only the first next beacon block decides", func(t *testing.T) { - included, err := isExecutionPayloadIncluded(slot, slot+64, bid, chain(map[uint64]*spec.VersionedSignedBeaconBlock{ + included, _, err := isExecutionPayloadIncluded(slot, slot+64, bid, chain(map[uint64]*spec.VersionedSignedBeaconBlock{ slot + 1: skipsThisPayload, slot + 2: gloasBeaconBlock(slot+2, 9, gloasBid(slot+2, 44, 1, testPoolAddress, 0xbb, 0xdd)), })) @@ -323,21 +326,21 @@ func Test_IsExecutionPayloadIncluded(t *testing.T) { }) t.Run("no finalized beacon block after the slot yet", func(t *testing.T) { - _, err := isExecutionPayloadIncluded(slot, slot+3, bid, chain(map[uint64]*spec.VersionedSignedBeaconBlock{ + _, _, err := isExecutionPayloadIncluded(slot, slot+3, bid, chain(map[uint64]*spec.VersionedSignedBeaconBlock{ slot + 4: buildsOnThisPayload, })) require.ErrorContains(t, err, "no finalized beacon block after slot") }) t.Run("beacon node error", func(t *testing.T) { - _, err := isExecutionPayloadIncluded(slot, slot+64, bid, func(uint64) (*spec.VersionedSignedBeaconBlock, error) { + _, _, err := isExecutionPayloadIncluded(slot, slot+64, bid, func(uint64) (*spec.VersionedSignedBeaconBlock, error) { return nil, errors.New("connection refused") }) require.ErrorContains(t, err, "connection refused") }) t.Run("next beacon block is not a Gloas one", func(t *testing.T) { - _, err := isExecutionPayloadIncluded(slot, slot+64, bid, chain(map[uint64]*spec.VersionedSignedBeaconBlock{ + _, _, err := isExecutionPayloadIncluded(slot, slot+64, bid, chain(map[uint64]*spec.VersionedSignedBeaconBlock{ slot + 1: {Version: spec.DataVersionFulu, Fulu: &electra.SignedBeaconBlock{}}, })) require.ErrorContains(t, err, "not a Gloas one") From addd703d140431f2cac59f4a5a7ad6bdc6ae4da1 Mon Sep 17 00:00:00 2001 From: Marketen Date: Thu, 22 Oct 2026 18:33:12 +0200 Subject: [PATCH 9/9] Ignore zero builder withdrawals and warn about late builder payments A builder withdrawal of zero to the pool moves no ETH, so it is not matched against credited payments. Before, it would have stopped the oracle as an unknown payment. The forced payment check already skips zero amounts. Builder payments reach the pool within about two epochs. One credited but still in flight after four is now logged once per epoch: it may never arrive, and until it does it counts as a pool asset in the onchain reconciliation. It only warns. Slots are processed in order, so stopping would also stop the oracle from reaching the slot where a slow payment lands, and with whether payments are made now decided exactly, one missing would point at a consensus client bug. Co-Authored-By: Claude Opus 5.5 --- oracle/builder_payments.go | 31 +++++++++++++++++++++++++++++- oracle/builder_payments_test.go | 34 +++++++++++++++++++++++++++++++++ oracle/oracle.go | 1 + 3 files changed, 65 insertions(+), 1 deletion(-) diff --git a/oracle/builder_payments.go b/oracle/builder_payments.go index ec652ab..feb3dc8 100644 --- a/oracle/builder_payments.go +++ b/oracle/builder_payments.go @@ -6,6 +6,7 @@ import ( "github.com/attestantio/go-eth2-client/spec/capella" "github.com/attestantio/go-eth2-client/spec/phase0" + "github.com/dappnode/mev-sp-oracle/constants" "github.com/dappnode/mev-sp-oracle/utils" "github.com/pkg/errors" log "github.com/sirupsen/logrus" @@ -33,7 +34,8 @@ func (b *FullBlock) BuilderWithdrawalsTo(address string) []*capella.Withdrawal { } received := make([]*capella.Withdrawal, 0) for _, withdrawal := range b.gloasExecutionPayload().Withdrawals { - if isBuilderWithdrawal(withdrawal) && utils.Equals(withdrawal.Address.String(), address) { + // A zero amount moves no ETH, so there is nothing to match + if withdrawal.Amount > 0 && isBuilderWithdrawal(withdrawal) && utils.Equals(withdrawal.Address.String(), address) { received = append(received, withdrawal) } } @@ -106,6 +108,33 @@ func (or *Oracle) settleArrivedBuilderPayments(fullBlock *FullBlock) error { return nil } +// A builder payment reaches the pool within about two epochs of its slot: in +// the next full payload, or after the end of the next epoch if its payload was +// withheld. One still in flight long after may never arrive, and meanwhile it +// counts as an asset in the onchain reconciliation, so it is worth a look. +// +// This only warns. Stopping would be wrong: slots are processed in order, so +// the oracle could never reach the one where a slow payment finally lands. +const lateBuilderPaymentSlots = 4 * 32 + +// Warns, once per epoch, about the builder payments still in flight long +// after their slot +func (or *Oracle) warnAboutLateBuilderPayments(processedSlot uint64) { + if processedSlot%constants.SlotsInEpoch != 0 { + return + } + for _, payment := range or.state.InFlightBuilderPayments { + if processedSlot > payment.Slot+lateBuilderPaymentSlots { + log.WithFields(log.Fields{ + "Slot": payment.Slot, + "BuilderIndex": payment.BuilderIndex, + "AmountWei": payment.AmountWei, + "SlotsInFlight": processedSlot - payment.Slot, + }).Warn("Builder payment credited long ago still has not reached the pool, check it was paid") + } + } +} + // Total amount of the builder payments credited but not in the pool yet func (or *Oracle) inFlightBuilderPaymentsWei() *big.Int { total := big.NewInt(0) diff --git a/oracle/builder_payments_test.go b/oracle/builder_payments_test.go index 75fb02f..7b7ceae 100644 --- a/oracle/builder_payments_test.go +++ b/oracle/builder_payments_test.go @@ -15,6 +15,8 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" + log "github.com/sirupsen/logrus" + logtest "github.com/sirupsen/logrus/hooks/test" "github.com/stretchr/testify/require" ) @@ -121,6 +123,12 @@ func Test_SettleArrivedBuilderPayments(t *testing.T) { require.Equal(t, []*BuilderPayment{payment}, oracle.state.InFlightBuilderPayments) }) + t.Run("zero amount withdrawals move nothing and are ignored", func(t *testing.T) { + oracle := gloasTestOracle(t) + require.NoError(t, oracle.settleArrivedBuilderPayments(blockPaying(t, builderWithdrawal(42, testPoolAddress, 0)))) + require.Empty(t, oracle.state.InFlightBuilderPayments) + }) + t.Run("a payment never credited is rejected without touching the state", func(t *testing.T) { oracle := gloasTestOracle(t) payment := inFlightPayment(10, 42, 48_200_000) @@ -332,3 +340,29 @@ func Test_AdvanceStateToNextSlot_CancelledPaymentIsNotTracked(t *testing.T) { require.NoError(t, oracle.RunOffchainReconciliation()) require.NoError(t, oracle.RunOnchainReconciliation(big.NewInt(0), nil)) } + +func Test_WarnAboutLateBuilderPayments(t *testing.T) { + hook := logtest.NewGlobal() + defer hook.Reset() + + oracle := gloasTestOracle(t) + oracle.state.InFlightBuilderPayments = []*BuilderPayment{inFlightPayment(1000, 42, 1), inFlightPayment(1100, 7, 1)} + + countWarnings := func(processedSlot uint64) int { + hook.Reset() + oracle.warnAboutLateBuilderPayments(processedSlot) + warnings := 0 + for _, entry := range hook.AllEntries() { + if entry.Level == log.WarnLevel { + warnings++ + } + } + return warnings + } + + // Once per epoch, for each payment in flight for more than 4 epochs + require.Equal(t, 0, countWarnings(1120)) + require.Equal(t, 1, countWarnings(1152)) + require.Equal(t, 0, countWarnings(1153)) + require.Equal(t, 2, countWarnings(1248)) +} diff --git a/oracle/oracle.go b/oracle/oracle.go index a5eeb99..2575623 100644 --- a/oracle/oracle.go +++ b/oracle/oracle.go @@ -234,6 +234,7 @@ func (or *Oracle) AdvanceStateToNextSlot(fullBlock *FullBlock) (uint64, error) { if summarizedBlock.BuilderPaymentWei != nil { or.trackBuilderPayment(fullBlock.BuilderPayment) } + or.warnAboutLateBuilderPayments(summarizedBlock.Slot) // Handle unsubscriptions the last thing after distributing rewards or.handleManualUnsubscriptions(fullBlock.Events.UnsubscribeValidator, fullBlock.ValidatorsUnsubs)