snap

package
v1.17.10 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 23, 2026 License: GPL-3.0, LGPL-3.0 Imports: 38 Imported by: 248

Documentation

Index

Constants

View Source
const (
	SNAP1 = 1
	SNAP2 = 2
)

Constants to match up protocol versions and messages

View Source
const (
	GetAccountRangeMsg  = 0x00
	AccountRangeMsg     = 0x01
	GetStorageRangesMsg = 0x02
	StorageRangesMsg    = 0x03
	GetByteCodesMsg     = 0x04
	ByteCodesMsg        = 0x05
	GetTrieNodesMsg     = 0x06
	TrieNodesMsg        = 0x07
	GetAccessListsMsg   = 0x08
	AccessListsMsg      = 0x09
)
View Source
const ProtocolName = "snap"

ProtocolName is the official short name of the `snap` protocol used during devp2p capability negotiation.

Variables

View Source
var (
	IngressRegistrationErrorMeter = metrics.NewRegisteredMeter(ingressRegistrationErrorName, nil)
	EgressRegistrationErrorMeter  = metrics.NewRegisteredMeter(egressRegistrationErrorName, nil)
)
View Source
var ErrCancelled = errors.New("sync cancelled")

ErrCancelled is returned from snap syncing if the operation was prematurely terminated.

View Source
var ProtocolVersions = []uint{SNAP2, SNAP1}

ProtocolVersions are all the `snap` protocol versions this node implements (first is primary). What's actually advertised on the wire is decided by MakeProtocols.

Functions

func Handle added in v1.10.14

func Handle(backend Backend, peer *Peer) error

Handle is the callback invoked to manage the life cycle of a `snap` peer. When this function terminates, the peer is disconnected.

func HandleMessage added in v1.10.14

func HandleMessage(backend Backend, peer *Peer) error

HandleMessage is invoked whenever an inbound message is received from a remote peer on the `snap` protocol. The remote connection is torn down upon returning any error.

func HasLegacySyncProgress added in v1.17.10

func HasLegacySyncProgress(db ethdb.KeyValueReader) bool

HasLegacySyncProgress reports whether an unfinished snap/1 sync is persisted. snap/1 stores its progress as bare JSON, snap/2 prefixes a version byte.

func MakeProtocols

func MakeProtocols(backend Backend, advertiseV2 bool) []p2p.Protocol

MakeProtocols constructs the P2P protocol definitions for `snap`. snap/2 is advertised alongside snap/1 only when advertiseV2 is set; otherwise snap/1 alone is offered on the wire.

func ServiceGetAccessListsQuery added in v1.17.3

func ServiceGetAccessListsQuery(chain *core.BlockChain, req *GetAccessListsPacket) rlp.RawList[rlp.RawValue]

ServiceGetAccessListsQuery assembles the response to an access list query. It is exposed to allow external packages to test protocol behavior.

func ServiceGetByteCodesQuery added in v1.10.14

func ServiceGetByteCodesQuery(chain *core.BlockChain, req *GetByteCodesPacket) [][]byte

ServiceGetByteCodesQuery assembles the response to a byte codes query. It is exposed to allow external packages to test protocol behavior.

func ServiceGetStorageRangesQuery added in v1.10.14

func ServiceGetStorageRangesQuery(chain *core.BlockChain, req *GetStorageRangesPacket) ([][]*StorageData, [][]byte)

func ServiceGetTrieNodesQuery added in v1.10.14

func ServiceGetTrieNodesQuery(chain *core.BlockChain, req *GetTrieNodesPacket) ([][]byte, error)

ServiceGetTrieNodesQuery assembles the response to a trie nodes query. It is exposed to allow external packages to test protocol behavior.

Types

type AccessListsPacket added in v1.17.3

type AccessListsPacket struct {
	ID          uint64                    // ID of the request this is a response for
	AccessLists rlp.RawList[rlp.RawValue] // Requested BALs
}

AccessListsPacket is the response to GetAccessListsPacket. Each entry corresponds to the requested hash at the same index. Empty entries indicate the BAL is unavailable.

func (*AccessListsPacket) Kind added in v1.17.3

func (*AccessListsPacket) Kind() byte

func (*AccessListsPacket) Name added in v1.17.3

func (*AccessListsPacket) Name() string

type AccountData

type AccountData struct {
	Hash common.Hash  // Hash of the account
	Body rlp.RawValue // Account body in slim format
}

AccountData represents a single account in a query response.

func ServiceGetAccountRangeQuery added in v1.10.14

func ServiceGetAccountRangeQuery(chain *core.BlockChain, req *GetAccountRangePacket) ([]*AccountData, [][]byte)

ServiceGetAccountRangeQuery assembles the response to an account range query. It is exposed to allow external packages to test protocol behavior.

type AccountRangePacket

type AccountRangePacket struct {
	ID       uint64         // ID of the request this is a response for
	Accounts []*AccountData // List of consecutive accounts from the trie
	Proof    [][]byte       // List of trie nodes proving the account range
}

AccountRangePacket represents an account query response.

func (*AccountRangePacket) Kind

func (*AccountRangePacket) Kind() byte

func (*AccountRangePacket) Name

func (*AccountRangePacket) Name() string

func (*AccountRangePacket) Unpack

func (p *AccountRangePacket) Unpack() ([]common.Hash, [][]byte, error)

Unpack retrieves the accounts from the range packet and converts from slim wire representation to consensus format. The returned data is RLP encoded since it's expected to be serialized to disk without further interpretation.

Note, this method does a round of RLP decoding and reencoding, so only use it once and cache the results if need be. Ideally discard the packet afterwards to not double the memory use.

type Backend

type Backend interface {
	// Chain retrieves the blockchain object to serve data.
	Chain() *core.BlockChain

	// RunPeer is invoked when a peer joins on the `eth` protocol. The handler
	// should do any peer maintenance work, handshakes and validations. If all
	// is passed, control should be given back to the `handler` to process the
	// inbound messages going forward.
	RunPeer(peer *Peer, handler Handler) error

	// PeerInfo retrieves all known `snap` information about a peer.
	PeerInfo(id enode.ID) interface{}

	// Handle is a callback to be invoked when a data packet is received from
	// the remote peer. Only packets not consumed by the protocol handler will
	// be forwarded to the backend.
	Handle(peer *Peer, packet Packet) error
}

Backend defines the data retrieval methods to serve remote requests and the callback methods to invoke on remote deliveries.

type ByteCodesPacket

type ByteCodesPacket struct {
	ID    uint64   // ID of the request this is a response for
	Codes [][]byte // Requested contract bytecodes
}

ByteCodesPacket represents a contract bytecode query response.

func (*ByteCodesPacket) Kind

func (*ByteCodesPacket) Kind() byte

func (*ByteCodesPacket) Name

func (*ByteCodesPacket) Name() string

type Decoder added in v1.17.3

type Decoder interface {
	Decode(val interface{}) error
}

type GetAccessListsPacket added in v1.17.3

type GetAccessListsPacket struct {
	ID     uint64        // Request ID to match up responses with
	Hashes []common.Hash // Block hashes to retrieve BALs for
	Bytes  uint64        // Soft limit at which to stop returning data
}

GetAccessListsPacket requests BALs for a set of block hashes.

func (*GetAccessListsPacket) Kind added in v1.17.3

func (*GetAccessListsPacket) Kind() byte

func (*GetAccessListsPacket) Name added in v1.17.3

func (*GetAccessListsPacket) Name() string

type GetAccountRangePacket

type GetAccountRangePacket struct {
	ID     uint64      // Request ID to match up responses with
	Root   common.Hash // Root hash of the account trie to serve
	Origin common.Hash // Hash of the first account to retrieve
	Limit  common.Hash // Hash of the last account to retrieve
	Bytes  uint64      // Soft limit at which to stop returning data
}

GetAccountRangePacket represents an account query.

func (*GetAccountRangePacket) Kind

func (*GetAccountRangePacket) Kind() byte

func (*GetAccountRangePacket) Name

func (*GetAccountRangePacket) Name() string

type GetByteCodesPacket

type GetByteCodesPacket struct {
	ID     uint64        // Request ID to match up responses with
	Hashes []common.Hash // Code hashes to retrieve the code for
	Bytes  uint64        // Soft limit at which to stop returning data
}

GetByteCodesPacket represents a contract bytecode query.

func (*GetByteCodesPacket) Kind

func (*GetByteCodesPacket) Kind() byte

func (*GetByteCodesPacket) Name

func (*GetByteCodesPacket) Name() string

type GetStorageRangesPacket

type GetStorageRangesPacket struct {
	ID       uint64        // Request ID to match up responses with
	Root     common.Hash   // Root hash of the account trie to serve
	Accounts []common.Hash // Account hashes of the storage tries to serve
	Origin   []byte        // Hash of the first storage slot to retrieve (large contract mode)
	Limit    []byte        // Hash of the last storage slot to retrieve (large contract mode)
	Bytes    uint64        // Soft limit at which to stop returning data
}

GetStorageRangesPacket represents an storage slot query.

func (*GetStorageRangesPacket) Kind

func (*GetStorageRangesPacket) Kind() byte

func (*GetStorageRangesPacket) Name

type GetTrieNodesPacket

type GetTrieNodesPacket struct {
	ID    uint64                       // Request ID to match up responses with
	Root  common.Hash                  // Root hash of the account trie to serve
	Paths rlp.RawList[TrieNodePathSet] // Trie node hashes to retrieve the nodes for
	Bytes uint64                       // Soft limit at which to stop returning data
}

GetTrieNodesPacket represents a state trie node query.

func (*GetTrieNodesPacket) Kind

func (*GetTrieNodesPacket) Kind() byte

func (*GetTrieNodesPacket) Name

func (*GetTrieNodesPacket) Name() string

type Handler

type Handler func(peer *Peer) error

Handler is a callback to invoke from an outside runner after the boilerplate exchanges have passed.

type NodeInfo

type NodeInfo struct{}

NodeInfo represents a short summary of the `snap` sub-protocol metadata known about the host peer.

type Packet

type Packet interface {
	Name() string // Name returns a string corresponding to the message type.
	Kind() byte   // Kind returns the message type.
}

Packet represents a p2p message in the `snap` protocol.

type Peer

type Peer struct {
	*p2p.Peer // The embedded P2P package peer
	// contains filtered or unexported fields
}

Peer is a collection of relevant information we have about a `snap` peer.

func NewFakePeer added in v1.10.14

func NewFakePeer(version uint, id string, rw p2p.MsgReadWriter) *Peer

NewFakePeer creates a fake snap peer without a backing p2p peer, for testing purposes.

func NewPeer added in v1.10.14

func NewPeer(version uint, p *p2p.Peer, rw p2p.MsgReadWriter) *Peer

NewPeer creates a wrapper for a network connection and negotiated protocol version.

func (*Peer) Close added in v1.17.0

func (p *Peer) Close()

Close releases resources associated with the peer.

func (*Peer) ID

func (p *Peer) ID() string

ID retrieves the peer's unique identifier.

func (*Peer) Log

func (p *Peer) Log() log.Logger

Log overrides the P2P logger with the higher level one containing only the id.

func (*Peer) RequestAccessLists added in v1.17.4

func (p *Peer) RequestAccessLists(id uint64, hashes []common.Hash, bytes int) error

RequestAccessLists fetches a batch of BALs by block hash.

func (*Peer) RequestAccountRange

func (p *Peer) RequestAccountRange(id uint64, root common.Hash, origin, limit common.Hash, bytes int) error

RequestAccountRange fetches a batch of accounts rooted in a specific account trie, starting with the origin.

func (*Peer) RequestByteCodes

func (p *Peer) RequestByteCodes(id uint64, hashes []common.Hash, bytes int) error

RequestByteCodes fetches a batch of bytecodes by hash.

func (*Peer) RequestStorageRanges

func (p *Peer) RequestStorageRanges(id uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, bytes int) error

RequestStorageRanges fetches a batch of storage slots belonging to one or more accounts. If slots from only one account is requested, an origin marker may also be used to retrieve from there.

func (*Peer) RequestTrieNodes

func (p *Peer) RequestTrieNodes(id uint64, root common.Hash, count int, paths []TrieNodePathSet, bytes int) error

RequestTrieNodes fetches a batch of account or storage trie nodes rooted in a specific state trie, or off of a specific account.

func (*Peer) Version

func (p *Peer) Version() uint

Version retrieves the peer's negotiated `snap` protocol version.

type Progress added in v1.17.4

type Progress struct {
	AccountSynced  uint64
	AccountBytes   common.StorageSize
	BytecodeSynced uint64
	BytecodeBytes  common.StorageSize
	StorageSynced  uint64
	StorageBytes   common.StorageSize

	// Healing-phase status. Reported by snap/1 only.
	TrienodeHealSynced uint64
	TrienodeHealBytes  common.StorageSize
	BytecodeHealSynced uint64
	BytecodeHealBytes  common.StorageSize
	HealingTrienodes   uint64
	HealingBytecode    uint64

	// snap/2-specific status. Reported by snap/2 only.
	AccessListSynced uint64 // Block access lists fetched during catch-up
	AccessListTotal  uint64 // Total block access lists to fetch for catch-up
	TrieGenPercent   uint64 // Trie generation completion, in percent (0..100)
}

Progress is the set of snap-syncer progress that eth/downloader surfaces in ethereum.SyncProgress. The two syncer versions report it via different types (syncProgress / syncProgressV2). The adapters normalize to this.

type StorageData

type StorageData struct {
	Hash common.Hash // Hash of the storage slot
	Body []byte      // Data content of the slot
}

StorageData represents a single storage slot in a query response.

type StorageRangesPacket

type StorageRangesPacket struct {
	ID    uint64           // ID of the request this is a response for
	Slots [][]*StorageData // Lists of consecutive storage slots for the requested accounts
	Proof [][]byte         // Merkle proofs for the *last* slot range, if it's incomplete
}

StorageRangesPacket represents a storage slot query response.

func (*StorageRangesPacket) Kind

func (*StorageRangesPacket) Kind() byte

func (*StorageRangesPacket) Name

func (*StorageRangesPacket) Name() string

func (*StorageRangesPacket) Unpack

func (p *StorageRangesPacket) Unpack() ([][]common.Hash, [][][]byte)

Unpack retrieves the storage slots from the range packet and returns them in a split flat format that's more consistent with the internal data structures.

type SyncPeer

type SyncPeer interface {
	// ID retrieves the peer's unique identifier.
	ID() string

	// RequestAccountRange fetches a batch of accounts rooted in a specific account
	// trie, starting with the origin.
	RequestAccountRange(id uint64, root, origin, limit common.Hash, bytes int) error

	// RequestStorageRanges fetches a batch of storage slots belonging to one or
	// more accounts. If slots from only one account is requested, an origin marker
	// may also be used to retrieve from there.
	RequestStorageRanges(id uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, bytes int) error

	// RequestByteCodes fetches a batch of bytecodes by hash.
	RequestByteCodes(id uint64, hashes []common.Hash, bytes int) error

	// RequestTrieNodes fetches a batch of account or storage trie nodes rooted in
	// a specific state trie.
	RequestTrieNodes(id uint64, root common.Hash, count int, paths []TrieNodePathSet, bytes int) error

	// Log retrieves the peer's own contextual logger.
	Log() log.Logger
}

SyncPeer abstracts out the methods required for a peer to be synced against with the goal of allowing the construction of mock peers without the full blown networking.

type SyncPeerV2 added in v1.17.4

type SyncPeerV2 interface {
	// ID retrieves the peer's unique identifier.
	ID() string

	// RequestAccountRange fetches a batch of accounts rooted in a specific account
	// trie, starting with the origin.
	RequestAccountRange(id uint64, root, origin, limit common.Hash, bytes int) error

	// RequestStorageRanges fetches a batch of storage slots belonging to one or
	// more accounts. If slots from only one account is requested, an origin marker
	// may also be used to retrieve from there.
	RequestStorageRanges(id uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, bytes int) error

	// RequestByteCodes fetches a batch of bytecodes by hash.
	RequestByteCodes(id uint64, hashes []common.Hash, bytes int) error

	// RequestTrieNodes fetches a batch of account or storage trie nodes rooted in
	// a specific state trie. snap/2 never issues these requests itself, but the
	// method is retained so a single peer type can serve both the snap/1 and
	// snap/2 syncers (e.g. via the downloader's syncer abstraction).
	RequestTrieNodes(id uint64, root common.Hash, count int, paths []TrieNodePathSet, bytes int) error

	// RequestAccessLists fetches a batch of BALs by block hash.
	RequestAccessLists(id uint64, hashes []common.Hash, bytes int) error

	// Log retrieves the peer's own contextual logger.
	Log() log.Logger
}

SyncPeerV2 abstracts out the methods required for a peer to be synced against with the goal of allowing the construction of mock peers without the full blown networking.

type Syncer

type Syncer interface {
	Sync(pivot *types.Header, cancel chan struct{}) error
	Progress() Progress
	Register(peer SyncPeerV2) error
	Unregister(id string) error
	OnAccounts(peer SyncPeerV2, id uint64, hashes []common.Hash, accounts [][]byte, proof [][]byte) error
	OnStorage(peer SyncPeerV2, id uint64, hashes [][]common.Hash, slots [][][]byte, proof [][]byte) error
	OnByteCodes(peer SyncPeerV2, id uint64, bytecodes [][]byte) error
	OnTrieNodes(peer SyncPeerV2, id uint64, trienodes [][]byte) error
	OnAccessLists(peer SyncPeerV2, id uint64, lists rlp.RawList[rlp.RawValue]) error

	// FrozenPivot returns the pivot header the syncer is bound to, or nil if
	// the pivot may still be chosen and moved freely.
	FrozenPivot() *types.Header

	// Version is the snap protocol version this syncer implements.
	Version() uint
}

Syncer is the uniform view over the snap/1 (*syncer) and snap/2 (*syncerV2) state syncers, consumed by eth/downloader. Peers are passed as SyncPeerV2, which is a superset of SyncPeer, so a single peer value works for both underlying syncers.

func NewV1Syncer added in v1.17.4

func NewV1Syncer(db ethdb.Database, scheme string) Syncer

NewV1Syncer returns a Syncer backed by the snap/1 state syncer.

func NewV2Syncer added in v1.17.4

func NewV2Syncer(db ethdb.Database, scheme string) Syncer

NewV2Syncer returns a Syncer backed by the snap/2 state syncer.

type TrieNodePathSet

type TrieNodePathSet [][]byte

TrieNodePathSet is a list of trie node paths to retrieve. A naive way to represent trie nodes would be a simple list of `account || storage` path segments concatenated, but that would be very wasteful on the network.

Instead, this array special cases the first element as the path in the account trie and the remaining elements as paths in the storage trie. To address an account node, the slice should have a length of 1 consisting of only the account path. There's no need to be able to address both an account node and a storage node in the same request as it cannot happen that a slot is accessed before the account path is fully expanded.

type TrieNodesPacket

type TrieNodesPacket struct {
	ID    uint64   // ID of the request this is a response for
	Nodes [][]byte // Requested state trie nodes
}

TrieNodesPacket represents a state trie node query response.

func (*TrieNodesPacket) Kind

func (*TrieNodesPacket) Kind() byte

func (*TrieNodesPacket) Name

func (*TrieNodesPacket) Name() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL