1use alloc::vec::Vec;
9use alloy_primitives::Bytes;
10use alloy_rlp::{Decodable, Encodable};
11
12mod account;
13pub use account::{AccountData, SlimAccountBody};
14
15mod messages;
16pub use messages::{
17 AccountRangeMessage, BlockAccessListsMessage, ByteCodesMessage, GetAccountRangeMessage,
18 GetBlockAccessListsMessage, GetByteCodesMessage, GetStorageRangesMessage, RangeBound,
19 StorageData, StorageRangesMessage,
20};
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
24#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
25#[repr(u8)]
26pub enum SnapVersion {
27 #[default]
29 V2 = 2,
30}
31
32impl SnapVersion {
33 pub const fn message_count(self) -> u8 {
36 match self {
37 Self::V2 => 10,
38 }
39 }
40
41 pub const fn supports_message_id(self, id: u8) -> bool {
46 match self {
47 Self::V2 => {
49 id <= SnapMessageId::ByteCodes as u8 ||
50 id == SnapMessageId::GetBlockAccessLists as u8 ||
51 id == SnapMessageId::BlockAccessLists as u8
52 }
53 }
54 }
55}
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub enum SnapMessageId {
60 GetAccountRange = 0x00,
62 AccountRange = 0x01,
65 GetStorageRanges = 0x02,
67 StorageRanges = 0x03,
69 GetByteCodes = 0x04,
71 ByteCodes = 0x05,
73 GetBlockAccessLists = 0x08,
75 BlockAccessLists = 0x09,
77}
78
79impl SnapMessageId {
80 pub const fn response(self) -> Option<Self> {
83 match self {
84 Self::GetAccountRange => Some(Self::AccountRange),
85 Self::GetStorageRanges => Some(Self::StorageRanges),
86 Self::GetByteCodes => Some(Self::ByteCodes),
87 Self::GetBlockAccessLists => Some(Self::BlockAccessLists),
88 Self::AccountRange | Self::StorageRanges | Self::ByteCodes | Self::BlockAccessLists => {
89 None
90 }
91 }
92 }
93}
94
95#[derive(Debug, Clone, PartialEq, Eq)]
97pub enum SnapProtocolMessage {
98 GetAccountRange(GetAccountRangeMessage),
100 AccountRange(AccountRangeMessage),
102 GetStorageRanges(GetStorageRangesMessage),
104 StorageRanges(StorageRangesMessage),
106 GetByteCodes(GetByteCodesMessage),
108 ByteCodes(ByteCodesMessage),
110 GetBlockAccessLists(GetBlockAccessListsMessage),
112 BlockAccessLists(BlockAccessListsMessage),
114}
115
116#[derive(thiserror::Error, Debug)]
119pub enum SnapProtocolError {
120 #[error("empty snap message")]
122 Empty,
123 #[error("message id {0:#x} is invalid for snap/{1:?}")]
126 UnsupportedMessageId(u8, SnapVersion),
127 #[error("RLP error: {0}")]
129 Rlp(#[from] alloy_rlp::Error),
130 #[error("received unsolicited {message_id:?} response with request id {request_id}")]
134 UnsolicitedResponse {
135 message_id: SnapMessageId,
137 request_id: u64,
139 },
140 #[error(
145 "{message_id:?} response with request id {request_id} holds a list longer than the {max_items} items its request allows"
146 )]
147 ResponseExceedsRequest {
148 message_id: SnapMessageId,
150 request_id: u64,
152 max_items: usize,
154 },
155}
156
157impl SnapProtocolMessage {
158 pub const fn message_id(&self) -> SnapMessageId {
162 match self {
163 Self::GetAccountRange(_) => SnapMessageId::GetAccountRange,
164 Self::AccountRange(_) => SnapMessageId::AccountRange,
165 Self::GetStorageRanges(_) => SnapMessageId::GetStorageRanges,
166 Self::StorageRanges(_) => SnapMessageId::StorageRanges,
167 Self::GetByteCodes(_) => SnapMessageId::GetByteCodes,
168 Self::ByteCodes(_) => SnapMessageId::ByteCodes,
169 Self::GetBlockAccessLists(_) => SnapMessageId::GetBlockAccessLists,
170 Self::BlockAccessLists(_) => SnapMessageId::BlockAccessLists,
171 }
172 }
173
174 pub const fn request_id(&self) -> u64 {
176 match self {
177 Self::GetAccountRange(m) => m.request_id,
178 Self::AccountRange(m) => m.request_id,
179 Self::GetStorageRanges(m) => m.request_id,
180 Self::StorageRanges(m) => m.request_id,
181 Self::GetByteCodes(m) => m.request_id,
182 Self::ByteCodes(m) => m.request_id,
183 Self::GetBlockAccessLists(m) => m.request_id,
184 Self::BlockAccessLists(m) => m.request_id,
185 }
186 }
187
188 pub const fn is_response(&self) -> bool {
190 matches!(
191 self,
192 Self::AccountRange(_) |
193 Self::StorageRanges(_) |
194 Self::ByteCodes(_) |
195 Self::BlockAccessLists(_)
196 )
197 }
198
199 pub const fn set_request_id(&mut self, request_id: u64) {
202 match self {
203 Self::GetAccountRange(m) => m.request_id = request_id,
204 Self::AccountRange(m) => m.request_id = request_id,
205 Self::GetStorageRanges(m) => m.request_id = request_id,
206 Self::StorageRanges(m) => m.request_id = request_id,
207 Self::GetByteCodes(m) => m.request_id = request_id,
208 Self::ByteCodes(m) => m.request_id = request_id,
209 Self::GetBlockAccessLists(m) => m.request_id = request_id,
210 Self::BlockAccessLists(m) => m.request_id = request_id,
211 }
212 }
213
214 pub fn encode(&self) -> Bytes {
216 let mut buf = Vec::new();
217 buf.push(self.message_id() as u8);
219
220 match self {
222 Self::GetAccountRange(msg) => msg.encode(&mut buf),
223 Self::AccountRange(msg) => msg.encode(&mut buf),
224 Self::GetStorageRanges(msg) => msg.encode(&mut buf),
225 Self::StorageRanges(msg) => msg.encode(&mut buf),
226 Self::GetByteCodes(msg) => msg.encode(&mut buf),
227 Self::ByteCodes(msg) => msg.encode(&mut buf),
228 Self::GetBlockAccessLists(msg) => msg.encode(&mut buf),
229 Self::BlockAccessLists(msg) => msg.encode(&mut buf),
230 }
231
232 Bytes::from(buf)
233 }
234
235 pub fn decode(message_id: u8, buf: &mut &[u8]) -> Result<Self, alloy_rlp::Error> {
237 macro_rules! decode_snap_message_variant {
239 ($message_id:expr, $buf:expr, $id:expr, $variant:ident, $msg_type:ty) => {
240 if $message_id == $id as u8 {
241 return Ok(Self::$variant(<$msg_type>::decode($buf)?));
242 }
243 };
244 }
245
246 decode_snap_message_variant!(
248 message_id,
249 buf,
250 SnapMessageId::GetAccountRange,
251 GetAccountRange,
252 GetAccountRangeMessage
253 );
254 decode_snap_message_variant!(
255 message_id,
256 buf,
257 SnapMessageId::AccountRange,
258 AccountRange,
259 AccountRangeMessage
260 );
261 decode_snap_message_variant!(
262 message_id,
263 buf,
264 SnapMessageId::GetStorageRanges,
265 GetStorageRanges,
266 GetStorageRangesMessage
267 );
268 decode_snap_message_variant!(
269 message_id,
270 buf,
271 SnapMessageId::StorageRanges,
272 StorageRanges,
273 StorageRangesMessage
274 );
275 decode_snap_message_variant!(
276 message_id,
277 buf,
278 SnapMessageId::GetByteCodes,
279 GetByteCodes,
280 GetByteCodesMessage
281 );
282 decode_snap_message_variant!(
283 message_id,
284 buf,
285 SnapMessageId::ByteCodes,
286 ByteCodes,
287 ByteCodesMessage
288 );
289 decode_snap_message_variant!(
290 message_id,
291 buf,
292 SnapMessageId::GetBlockAccessLists,
293 GetBlockAccessLists,
294 GetBlockAccessListsMessage
295 );
296 decode_snap_message_variant!(
297 message_id,
298 buf,
299 SnapMessageId::BlockAccessLists,
300 BlockAccessLists,
301 BlockAccessListsMessage
302 );
303
304 Err(alloy_rlp::Error::Custom("Unknown message ID"))
305 }
306
307 pub fn decode_versioned(version: SnapVersion, bytes: &[u8]) -> Result<Self, SnapProtocolError> {
312 let (&id, mut body) = bytes.split_first().ok_or(SnapProtocolError::Empty)?;
313 if !version.supports_message_id(id) {
314 return Err(SnapProtocolError::UnsupportedMessageId(id, version));
315 }
316 let msg = Self::decode(id, &mut body)?;
317 if !body.is_empty() {
318 return Err(SnapProtocolError::Rlp(alloy_rlp::Error::UnexpectedLength));
319 }
320 Ok(msg)
321 }
322}
323
324#[cfg(test)]
325mod tests {
326 use super::*;
327 use crate::BlockAccessLists;
328 use alloy_primitives::{B256, KECCAK256_EMPTY, U256};
329 use alloy_trie::{TrieAccount, EMPTY_ROOT_HASH};
330 use test_case::test_case;
331
332 fn b256_from_u64(value: u64) -> B256 {
334 B256::left_padding_from(&value.to_be_bytes())
335 }
336
337 fn test_roundtrip(original: SnapProtocolMessage) {
339 let encoded = original.encode();
340
341 assert_eq!(encoded[0], original.message_id() as u8);
343
344 let mut buf = &encoded[1..];
345 let decoded = SnapProtocolMessage::decode(encoded[0], &mut buf).unwrap();
346
347 assert_eq!(decoded, original);
349 }
350
351 #[derive(alloy_rlp::RlpEncodable)]
355 struct GethStorageRequest {
356 request_id: u64,
357 root_hash: B256,
358 account_hashes: Vec<B256>,
359 origin: Bytes,
360 limit: Bytes,
361 response_bytes: u64,
362 }
363
364 #[test]
365 fn test_all_message_roundtrips() {
366 assert_eq!(SnapVersion::V2.message_count(), 10);
367
368 test_roundtrip(SnapProtocolMessage::GetAccountRange(GetAccountRangeMessage {
369 request_id: 42,
370 root_hash: b256_from_u64(123),
371 starting_hash: b256_from_u64(456),
372 limit_hash: b256_from_u64(789),
373 response_bytes: 1024,
374 }));
375
376 test_roundtrip(SnapProtocolMessage::AccountRange(AccountRangeMessage {
377 request_id: 42,
378 accounts: vec![AccountData::from_trie_account(
379 b256_from_u64(123),
380 &TrieAccount::new(7, U256::from(42), EMPTY_ROOT_HASH, KECCAK256_EMPTY),
381 )],
382 proof: vec![Bytes::from(vec![4, 5, 6])],
383 }));
384
385 test_roundtrip(SnapProtocolMessage::GetStorageRanges(GetStorageRangesMessage {
386 request_id: 42,
387 root_hash: b256_from_u64(123),
388 account_hashes: vec![b256_from_u64(456)],
389 starting_hash: b256_from_u64(789).into(),
390 limit_hash: b256_from_u64(101112).into(),
391 response_bytes: 2048,
392 }));
393
394 test_roundtrip(SnapProtocolMessage::GetStorageRanges(GetStorageRangesMessage {
396 request_id: 43,
397 root_hash: b256_from_u64(123),
398 account_hashes: vec![b256_from_u64(456), b256_from_u64(789)],
399 starting_hash: RangeBound::default(),
400 limit_hash: RangeBound::default(),
401 response_bytes: 2048,
402 }));
403
404 test_roundtrip(SnapProtocolMessage::StorageRanges(StorageRangesMessage {
405 request_id: 42,
406 slots: vec![vec![StorageData {
407 hash: b256_from_u64(123),
408 data: Bytes::from(vec![1, 2, 3]),
409 }]],
410 proof: vec![Bytes::from(vec![4, 5, 6])],
411 }));
412
413 test_roundtrip(SnapProtocolMessage::GetByteCodes(GetByteCodesMessage {
414 request_id: 42,
415 hashes: vec![b256_from_u64(123)],
416 response_bytes: 1024,
417 }));
418
419 test_roundtrip(SnapProtocolMessage::ByteCodes(ByteCodesMessage {
420 request_id: 42,
421 codes: vec![Bytes::from(vec![1, 2, 3])],
422 }));
423
424 test_roundtrip(SnapProtocolMessage::GetBlockAccessLists(GetBlockAccessListsMessage {
425 request_id: 42,
426 block_hashes: vec![b256_from_u64(123), b256_from_u64(456)],
427 response_bytes: 4096,
428 }));
429
430 test_roundtrip(SnapProtocolMessage::BlockAccessLists(BlockAccessListsMessage {
431 request_id: 42,
432 block_access_lists: BlockAccessLists(vec![
433 Some(Bytes::from_static(&[alloy_rlp::EMPTY_LIST_CODE])),
434 Some(Bytes::from_static(&[0xc1, alloy_rlp::EMPTY_LIST_CODE])),
435 ]),
436 }));
437 }
438
439 #[test]
440 fn test_unknown_message_id() {
441 let data = Bytes::from(vec![1, 2, 3, 4]);
443 let mut buf = data.as_ref();
444
445 let result = SnapProtocolMessage::decode(255, &mut buf);
447
448 assert!(result.is_err());
449 if let Err(e) = result {
450 assert_eq!(e.to_string(), "Unknown message ID");
451 }
452 }
453
454 #[test]
455 fn test_snap_v2_message_validity() {
456 let v2 = SnapVersion::V2;
457 for id in 0x00..=0x05 {
459 assert!(v2.supports_message_id(id), "snap/2 should accept {id:#x}");
460 }
461 assert!(!v2.supports_message_id(0x06));
463 assert!(!v2.supports_message_id(0x07));
464 assert!(v2.supports_message_id(SnapMessageId::GetBlockAccessLists as u8));
466 assert!(v2.supports_message_id(SnapMessageId::BlockAccessLists as u8));
467 assert!(!v2.supports_message_id(0x0a));
468 assert!(!v2.supports_message_id(0xff));
469 }
470
471 #[test_case(
472 SnapProtocolMessage::GetAccountRange(GetAccountRangeMessage {
473 request_id: 1, root_hash: B256::ZERO, starting_hash: B256::ZERO,
474 limit_hash: B256::ZERO, response_bytes: 0,
475 }), 1, false ; "get_account_range is a request"
476 )]
477 #[test_case(
478 SnapProtocolMessage::AccountRange(AccountRangeMessage {
479 request_id: 2, accounts: vec![], proof: vec![],
480 }), 2, true ; "account_range is a response"
481 )]
482 #[test_case(
483 SnapProtocolMessage::GetStorageRanges(GetStorageRangesMessage {
484 request_id: 3, root_hash: B256::ZERO, account_hashes: vec![],
485 starting_hash: B256::ZERO.into(), limit_hash: B256::ZERO.into(), response_bytes: 0,
486 }), 3, false ; "get_storage_ranges is a request"
487 )]
488 #[test_case(
489 SnapProtocolMessage::StorageRanges(StorageRangesMessage {
490 request_id: 4, slots: vec![], proof: vec![],
491 }), 4, true ; "storage_ranges is a response"
492 )]
493 #[test_case(
494 SnapProtocolMessage::GetByteCodes(GetByteCodesMessage {
495 request_id: 5, hashes: vec![], response_bytes: 0,
496 }), 5, false ; "get_byte_codes is a request"
497 )]
498 #[test_case(
499 SnapProtocolMessage::ByteCodes(ByteCodesMessage { request_id: 6, codes: vec![] }),
500 6, true ; "byte_codes is a response"
501 )]
502 #[test_case(
503 SnapProtocolMessage::GetBlockAccessLists(GetBlockAccessListsMessage {
504 request_id: 7, block_hashes: vec![], response_bytes: 0,
505 }), 7, false ; "get_block_access_lists is a request"
506 )]
507 #[test_case(
508 SnapProtocolMessage::BlockAccessLists(BlockAccessListsMessage {
509 request_id: 8, block_access_lists: BlockAccessLists(vec![]),
510 }), 8, true ; "block_access_lists is a response"
511 )]
512 fn request_id_and_is_response(msg: SnapProtocolMessage, expected_id: u64, is_response: bool) {
513 assert_eq!(msg.request_id(), expected_id);
514 assert_eq!(msg.is_response(), is_response);
515 }
516
517 #[test_case(
518 SnapProtocolMessage::GetAccountRange(GetAccountRangeMessage {
519 request_id: 1, root_hash: B256::ZERO, starting_hash: B256::ZERO,
520 limit_hash: B256::ZERO, response_bytes: 0,
521 }) ; "get_account_range"
522 )]
523 #[test_case(
524 SnapProtocolMessage::AccountRange(AccountRangeMessage {
525 request_id: 1, accounts: vec![], proof: vec![],
526 }) ; "account_range"
527 )]
528 #[test_case(
529 SnapProtocolMessage::GetStorageRanges(GetStorageRangesMessage {
530 request_id: 1, root_hash: B256::ZERO, account_hashes: vec![],
531 starting_hash: B256::ZERO.into(), limit_hash: B256::ZERO.into(), response_bytes: 0,
532 }) ; "get_storage_ranges"
533 )]
534 #[test_case(
535 SnapProtocolMessage::StorageRanges(StorageRangesMessage {
536 request_id: 1, slots: vec![], proof: vec![],
537 }) ; "storage_ranges"
538 )]
539 #[test_case(
540 SnapProtocolMessage::GetByteCodes(GetByteCodesMessage {
541 request_id: 1, hashes: vec![], response_bytes: 0,
542 }) ; "get_byte_codes"
543 )]
544 #[test_case(
545 SnapProtocolMessage::ByteCodes(ByteCodesMessage { request_id: 1, codes: vec![] }) ;
546 "byte_codes"
547 )]
548 #[test_case(
549 SnapProtocolMessage::GetBlockAccessLists(GetBlockAccessListsMessage {
550 request_id: 1, block_hashes: vec![], response_bytes: 0,
551 }) ; "get_block_access_lists"
552 )]
553 #[test_case(
554 SnapProtocolMessage::BlockAccessLists(BlockAccessListsMessage {
555 request_id: 1, block_access_lists: BlockAccessLists(vec![]),
556 }) ; "block_access_lists"
557 )]
558 fn per_variant_request_id_and_round_trip(mut msg: SnapProtocolMessage) {
559 msg.set_request_id(42);
561 assert_eq!(msg.request_id(), 42);
562
563 let decoded =
565 SnapProtocolMessage::decode_versioned(SnapVersion::V2, &msg.encode()).unwrap();
566 assert_eq!(decoded, msg);
567 }
568
569 #[test]
570 fn decode_versioned_rejects_empty() {
571 assert!(matches!(
573 SnapProtocolMessage::decode_versioned(SnapVersion::V2, &[]),
574 Err(SnapProtocolError::Empty)
575 ));
576 }
577
578 #[test]
579 fn decode_versioned_rejects_trie_node_ids_in_v2() {
580 for id in [0x06u8, 0x07] {
583 assert!(matches!(
584 SnapProtocolMessage::decode_versioned(SnapVersion::V2, &[id]),
585 Err(SnapProtocolError::UnsupportedMessageId(got, SnapVersion::V2)) if got == id
586 ));
587 }
588 }
589
590 #[test]
591 fn decode_versioned_reports_malformed_body() {
592 assert!(matches!(
595 SnapProtocolMessage::decode_versioned(SnapVersion::V2, &[0x08, 0xff]),
596 Err(SnapProtocolError::Rlp(_))
597 ));
598 }
599
600 #[test]
601 fn decode_versioned_rejects_trailing_bytes() {
602 let original = SnapProtocolMessage::GetBlockAccessLists(GetBlockAccessListsMessage {
605 request_id: 7,
606 block_hashes: vec![b256_from_u64(1)],
607 response_bytes: 1024,
608 });
609 let mut framed = original.encode().to_vec();
610 framed.push(0xff);
611 assert!(matches!(
612 SnapProtocolMessage::decode_versioned(SnapVersion::V2, &framed),
613 Err(SnapProtocolError::Rlp(alloy_rlp::Error::UnexpectedLength))
614 ));
615 }
616
617 #[test]
618 fn get_storage_ranges_decodes_geths_empty_origin_and_limit() {
619 let body = alloy_rlp::encode(GethStorageRequest {
620 request_id: 21,
621 root_hash: B256::ZERO,
622 account_hashes: vec![B256::repeat_byte(1), B256::repeat_byte(2)],
623 origin: Bytes::new(),
624 limit: Bytes::new(),
625 response_bytes: 1024,
626 });
627 let mut framed = vec![SnapMessageId::GetStorageRanges as u8];
628 framed.extend_from_slice(&body);
629
630 let decoded = SnapProtocolMessage::decode_versioned(SnapVersion::V2, &framed).unwrap();
631 let SnapProtocolMessage::GetStorageRanges(msg) = decoded else {
632 panic!("expected a GetStorageRanges message");
633 };
634 assert_eq!(msg.starting_hash.unwrap_or(B256::ZERO), B256::ZERO);
635 assert_eq!(msg.limit_hash.unwrap_or(B256::repeat_byte(0xff)), B256::repeat_byte(0xff));
636 }
637}