prefetching_eth_client.go 9.23 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
package sources

import (
	"context"
	"math/big"
	"sync"
	"time"

	"github.com/ethereum-optimism/optimism/op-service/eth"
	"github.com/ethereum/go-ethereum"
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core/types"
)

type EthClientInterface interface {
	SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (ethereum.Subscription, error)
	ChainID(ctx context.Context) (*big.Int, error)
	InfoByHash(ctx context.Context, hash common.Hash) (eth.BlockInfo, error)
	InfoByNumber(ctx context.Context, number uint64) (eth.BlockInfo, error)
	InfoByLabel(ctx context.Context, label eth.BlockLabel) (eth.BlockInfo, error)
	InfoAndTxsByHash(ctx context.Context, hash common.Hash) (eth.BlockInfo, types.Transactions, error)
	InfoAndTxsByNumber(ctx context.Context, number uint64) (eth.BlockInfo, types.Transactions, error)
	InfoAndTxsByLabel(ctx context.Context, label eth.BlockLabel) (eth.BlockInfo, types.Transactions, error)
	PayloadByHash(ctx context.Context, hash common.Hash) (*eth.ExecutionPayload, error)
	PayloadByNumber(ctx context.Context, number uint64) (*eth.ExecutionPayload, error)
	PayloadByLabel(ctx context.Context, label eth.BlockLabel) (*eth.ExecutionPayload, error)
	FetchReceipts(ctx context.Context, blockHash common.Hash) (eth.BlockInfo, types.Receipts, error)
	GetProof(ctx context.Context, address common.Address, storage []common.Hash, blockTag string) (*eth.AccountResult, error)
	GetStorageAt(ctx context.Context, address common.Address, storageSlot common.Hash, blockTag string) (common.Hash, error)
	ReadStorageAt(ctx context.Context, address common.Address, storageSlot common.Hash, blockHash common.Hash) (common.Hash, error)
	Close()
}

type PrefetchingEthClient struct {
	inner                 EthClientInterface
	PrefetchingRange      uint64
	PrefetchingTimeout    time.Duration
	runningCtx            context.Context
	runningCancel         context.CancelFunc
	highestHeadRequesting uint64
	highestHeadLock       sync.Mutex
	wg                    *sync.WaitGroup // used for testing
}

// NewPrefetchingEthClient creates a new [PrefetchingEthClient] with the given underlying [EthClient]
// and a prefetching range.
func NewPrefetchingEthClient(inner EthClientInterface, prefetchingRange uint64, timeout time.Duration) (*PrefetchingEthClient, error) {
	// Create a new context for the prefetching goroutines
	runningCtx, runningCancel := context.WithCancel(context.Background())
	return &PrefetchingEthClient{
		inner:                 inner,
		PrefetchingRange:      prefetchingRange,
		PrefetchingTimeout:    timeout,
		runningCtx:            runningCtx,
		runningCancel:         runningCancel,
		highestHeadRequesting: 0,
	}, nil
}

func (p *PrefetchingEthClient) updateRequestingHead(start, end uint64) (newStart uint64, shouldFetch bool) {
	// Acquire lock before reading/updating highestHeadRequesting
	p.highestHeadLock.Lock()
	defer p.highestHeadLock.Unlock()
	if start <= p.highestHeadRequesting {
		start = p.highestHeadRequesting + 1
	}
	if p.highestHeadRequesting < end {
		p.highestHeadRequesting = end
	}
	return start, start <= end
}

func (p *PrefetchingEthClient) FetchWindow(start, end uint64) {
	if p.wg != nil {
		defer p.wg.Done()
	}

	start, shouldFetch := p.updateRequestingHead(start, end)
	if !shouldFetch {
		return
	}

	ctx, cancel := context.WithTimeout(p.runningCtx, p.PrefetchingTimeout)
	defer cancel()
	for i := start; i <= end; i++ {
		p.FetchBlockAndReceipts(ctx, i)
	}
}

func (p *PrefetchingEthClient) FetchBlockAndReceipts(ctx context.Context, number uint64) {
	blockInfo, _, err := p.inner.InfoAndTxsByNumber(ctx, number)
	if err != nil {
		return
	}
	_, _, _ = p.inner.FetchReceipts(ctx, blockInfo.Hash())
}

func (p *PrefetchingEthClient) SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (ethereum.Subscription, error) {
	return p.inner.SubscribeNewHead(ctx, ch)
}

func (p *PrefetchingEthClient) ChainID(ctx context.Context) (*big.Int, error) {
	return p.inner.ChainID(ctx)
}

func (p *PrefetchingEthClient) InfoByHash(ctx context.Context, hash common.Hash) (eth.BlockInfo, error) {
	// Fetch the block information for the given hash
	blockInfo, err := p.inner.InfoByHash(ctx, hash)
	if err != nil {
		return blockInfo, err
	}

	if p.wg != nil {
		p.wg.Add(1)
	}
	// Prefetch the next n blocks and their receipts starting from the block number of the fetched block
	go p.FetchWindow(blockInfo.NumberU64()+1, blockInfo.NumberU64()+p.PrefetchingRange)

	return blockInfo, nil
}

func (p *PrefetchingEthClient) InfoByNumber(ctx context.Context, number uint64) (eth.BlockInfo, error) {
	if p.wg != nil {
		p.wg.Add(1)
	}
	// Trigger prefetching in the background
	go p.FetchWindow(number+1, number+p.PrefetchingRange)

	// Fetch the requested block
	return p.inner.InfoByNumber(ctx, number)
}

func (p *PrefetchingEthClient) InfoByLabel(ctx context.Context, label eth.BlockLabel) (eth.BlockInfo, error) {
	// Fetch the block information for the given label
	blockInfo, err := p.inner.InfoByLabel(ctx, label)
	if err != nil {
		return blockInfo, err
	}

	if p.wg != nil {
		p.wg.Add(1)
	}
	// Prefetch the next n blocks and their receipts starting from the block number of the fetched block
	go p.FetchWindow(blockInfo.NumberU64()+1, blockInfo.NumberU64()+p.PrefetchingRange)

	return blockInfo, nil
}

func (p *PrefetchingEthClient) InfoAndTxsByHash(ctx context.Context, hash common.Hash) (eth.BlockInfo, types.Transactions, error) {
	// Fetch the block info and transactions for the requested hash
	blockInfo, txs, err := p.inner.InfoAndTxsByHash(ctx, hash)
	if err != nil {
		return blockInfo, txs, err
	}

	if p.wg != nil {
		p.wg.Add(1)
	}
	// Prefetch the next n blocks and their receipts
	go p.FetchWindow(blockInfo.NumberU64()+1, blockInfo.NumberU64()+p.PrefetchingRange)

	return blockInfo, txs, nil
}

func (p *PrefetchingEthClient) InfoAndTxsByNumber(ctx context.Context, number uint64) (eth.BlockInfo, types.Transactions, error) {
	// Fetch the block info and transactions for the requested number
	blockInfo, txs, err := p.inner.InfoAndTxsByNumber(ctx, number)
	if err != nil {
		return blockInfo, txs, err
	}

	if p.wg != nil {
		p.wg.Add(1)
	}
	// Prefetch the next n blocks and their receipts
	go p.FetchWindow(number+1, number+p.PrefetchingRange)

	return blockInfo, txs, nil
}

func (p *PrefetchingEthClient) InfoAndTxsByLabel(ctx context.Context, label eth.BlockLabel) (eth.BlockInfo, types.Transactions, error) {
	// Fetch the block info and transactions for the requested label
	blockInfo, txs, err := p.inner.InfoAndTxsByLabel(ctx, label)
	if err != nil {
		return blockInfo, txs, err
	}

	if p.wg != nil {
		p.wg.Add(1)
	}
	// Prefetch the next n blocks and their receipts
	go p.FetchWindow(blockInfo.NumberU64()+1, blockInfo.NumberU64()+p.PrefetchingRange)

	return blockInfo, txs, nil
}

func (p *PrefetchingEthClient) PayloadByHash(ctx context.Context, hash common.Hash) (*eth.ExecutionPayload, error) {
	// Fetch the payload for the requested hash
	payload, err := p.inner.PayloadByHash(ctx, hash)
	if err != nil {
		return payload, err
	}

	if p.wg != nil {
		p.wg.Add(1)
	}
	// Prefetch the next n blocks and their receipts
	go p.FetchWindow(uint64(payload.BlockNumber)+1, uint64(payload.BlockNumber)+p.PrefetchingRange)

	return payload, nil
}

func (p *PrefetchingEthClient) PayloadByNumber(ctx context.Context, number uint64) (*eth.ExecutionPayload, error) {
	// Fetch the payload for the requested number
	payload, err := p.inner.PayloadByNumber(ctx, number)
	if err != nil {
		return payload, err
	}

	if p.wg != nil {
		p.wg.Add(1)
	}
	// Prefetch the next n blocks and their receipts
	go p.FetchWindow(number+1, number+p.PrefetchingRange)

	return payload, nil
}

func (p *PrefetchingEthClient) PayloadByLabel(ctx context.Context, label eth.BlockLabel) (*eth.ExecutionPayload, error) {
	// Fetch the payload for the requested label
	payload, err := p.inner.PayloadByLabel(ctx, label)
	if err != nil {
		return payload, err
	}

	if p.wg != nil {
		p.wg.Add(1)
	}
	// Prefetch the next n blocks and their receipts
	go p.FetchWindow(uint64(payload.BlockNumber)+1, uint64(payload.BlockNumber)+p.PrefetchingRange)

	return payload, nil
}

func (p *PrefetchingEthClient) FetchReceipts(ctx context.Context, blockHash common.Hash) (eth.BlockInfo, types.Receipts, error) {
	// Fetch the block info and receipts for the requested hash
	blockInfo, receipts, err := p.inner.FetchReceipts(ctx, blockHash)
	if err != nil {
		return blockInfo, receipts, err
	}

	if p.wg != nil {
		p.wg.Add(1)
	}
	// Prefetch the next n blocks and their receipts
	go p.FetchWindow(blockInfo.NumberU64(), blockInfo.NumberU64()+p.PrefetchingRange)

	return blockInfo, receipts, nil
}

func (p *PrefetchingEthClient) GetProof(ctx context.Context, address common.Address, storage []common.Hash, blockTag string) (*eth.AccountResult, error) {
	return p.inner.GetProof(ctx, address, storage, blockTag)
}

func (p *PrefetchingEthClient) GetStorageAt(ctx context.Context, address common.Address, storageSlot common.Hash, blockTag string) (common.Hash, error) {
	return p.inner.GetStorageAt(ctx, address, storageSlot, blockTag)
}

func (p *PrefetchingEthClient) ReadStorageAt(ctx context.Context, address common.Address, storageSlot common.Hash, blockHash common.Hash) (common.Hash, error) {
	return p.inner.ReadStorageAt(ctx, address, storageSlot, blockHash)
}

func (p *PrefetchingEthClient) Close() {
	p.runningCancel()
	p.inner.Close()
}