wire.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. //! Pyth Wire Format
  2. //!
  3. //! Pyth uses a custom wire format when moving data between programs and chains. This module
  4. //! provides the serialization and deserialization logic for this format as well as definitions of
  5. //! data structures used in the PythNet ecosystem.
  6. //!
  7. //! See the `ser` submodule for a description of the Pyth Wire format.
  8. pub mod array;
  9. mod de;
  10. mod prefixed_vec;
  11. mod ser;
  12. pub use {
  13. de::{
  14. from_slice,
  15. Deserializer,
  16. DeserializerError,
  17. },
  18. prefixed_vec::PrefixedVec,
  19. ser::{
  20. to_vec,
  21. to_writer,
  22. Serializer,
  23. SerializerError,
  24. },
  25. };
  26. // Proof Format (V1)
  27. // --------------------------------------------------------------------------------
  28. // The definitions within each module can be updated with append-only data without requiring a new
  29. // module to be defined. So for example, it is possible to add new fields can be added to the end
  30. // of the `AccumulatorAccount` without moving to a `v1`.
  31. pub mod v1 {
  32. use {
  33. super::*,
  34. crate::{
  35. accumulators::merkle::MerklePath,
  36. error::Error,
  37. hashers::keccak256_160::Keccak160,
  38. require,
  39. },
  40. serde::{
  41. Deserialize,
  42. Serialize,
  43. },
  44. };
  45. pub const PYTHNET_ACCUMULATOR_UPDATE_MAGIC: &[u8; 4] = b"PNAU";
  46. // Transfer Format.
  47. // --------------------------------------------------------------------------------
  48. // This definition is what will be sent over the wire (I.E, pulled from PythNet and submitted
  49. // to target chains).
  50. #[derive(Clone, Debug, Hash, PartialEq, Serialize, Deserialize)]
  51. pub struct AccumulatorUpdateData {
  52. magic: [u8; 4],
  53. major_version: u8,
  54. minor_version: u8,
  55. trailing: Vec<u8>,
  56. pub proof: Proof,
  57. }
  58. impl AccumulatorUpdateData {
  59. pub fn new(proof: Proof) -> Self {
  60. Self {
  61. magic: *PYTHNET_ACCUMULATOR_UPDATE_MAGIC,
  62. major_version: 1,
  63. minor_version: 0,
  64. trailing: vec![],
  65. proof,
  66. }
  67. }
  68. pub fn try_from_slice(bytes: &[u8]) -> Result<Self, Error> {
  69. let message = from_slice::<byteorder::BE, Self>(bytes)
  70. .map_err(|_| Error::DeserializationError)?;
  71. require!(
  72. &message.magic[..] == PYTHNET_ACCUMULATOR_UPDATE_MAGIC,
  73. Error::InvalidMagic
  74. );
  75. require!(message.major_version == 1, Error::InvalidVersion);
  76. require!(message.minor_version == 0, Error::InvalidVersion);
  77. Ok(message)
  78. }
  79. }
  80. // A hash of some data.
  81. pub type Hash = [u8; 20];
  82. #[derive(Clone, Debug, Hash, PartialEq, Serialize, Deserialize)]
  83. pub enum Proof {
  84. WormholeMerkle {
  85. vaa: PrefixedVec<u16, u8>,
  86. updates: Vec<MerklePriceUpdate>,
  87. },
  88. }
  89. #[derive(Clone, Debug, Hash, PartialEq, Serialize, Deserialize)]
  90. pub struct MerklePriceUpdate {
  91. pub message: PrefixedVec<u16, u8>,
  92. pub proof: MerklePath<Keccak160>,
  93. }
  94. #[derive(Clone, Debug, Hash, PartialEq, Serialize, Deserialize)]
  95. pub struct WormholeMessage {
  96. pub magic: [u8; 4],
  97. pub payload: WormholePayload,
  98. }
  99. pub const ACCUMULATOR_UPDATE_WORMHOLE_VERIFICATION_MAGIC: &[u8; 4] = b"AUWV";
  100. impl WormholeMessage {
  101. pub fn new(payload: WormholePayload) -> Self {
  102. Self {
  103. magic: *ACCUMULATOR_UPDATE_WORMHOLE_VERIFICATION_MAGIC,
  104. payload,
  105. }
  106. }
  107. pub fn try_from_bytes(bytes: impl AsRef<[u8]>) -> Result<Self, Error> {
  108. let message = from_slice::<byteorder::BE, Self>(bytes.as_ref())
  109. .map_err(|_| Error::DeserializationError)?;
  110. require!(
  111. &message.magic[..] == ACCUMULATOR_UPDATE_WORMHOLE_VERIFICATION_MAGIC,
  112. Error::InvalidMagic
  113. );
  114. Ok(message)
  115. }
  116. }
  117. #[derive(Clone, Debug, Hash, PartialEq, Serialize, Deserialize)]
  118. pub enum WormholePayload {
  119. Merkle(WormholeMerkleRoot),
  120. }
  121. #[derive(Clone, Debug, Hash, PartialEq, Serialize, Deserialize)]
  122. pub struct WormholeMerkleRoot {
  123. pub slot: u64,
  124. pub ring_size: u32,
  125. pub root: Hash,
  126. }
  127. }
  128. #[cfg(test)]
  129. mod tests {
  130. use crate::wire::{
  131. array,
  132. v1::{
  133. AccumulatorUpdateData,
  134. Proof,
  135. },
  136. Deserializer,
  137. PrefixedVec,
  138. Serializer,
  139. };
  140. // Test the arbitrary fixed sized array serialization implementation.
  141. #[test]
  142. fn test_array_serde() {
  143. // Serialize an array into a buffer.
  144. let mut buffer = Vec::new();
  145. let mut cursor = std::io::Cursor::new(&mut buffer);
  146. let mut serializer: Serializer<_, byteorder::LE> = Serializer::new(&mut cursor);
  147. array::serialize(&[1u8; 37], &mut serializer).unwrap();
  148. // The result should not have been prefixed with a length byte.
  149. assert_eq!(buffer.len(), 37);
  150. // We should also be able to deserialize it back.
  151. let mut deserializer = Deserializer::<byteorder::LE>::new(&buffer);
  152. let deserialized: [u8; 37] = array::deserialize(&mut deserializer).unwrap();
  153. // The deserialized array should be the same as the original.
  154. assert_eq!(deserialized, [1u8; 37]);
  155. }
  156. // The array serializer should not interfere with other serializers. Here we
  157. // check serde_json to make sure an array is written as expected.
  158. #[test]
  159. fn test_array_serde_json() {
  160. // Serialize an array into a buffer.
  161. let mut buffer = Vec::new();
  162. let mut cursor = std::io::Cursor::new(&mut buffer);
  163. let mut serialized = serde_json::Serializer::new(&mut cursor);
  164. array::serialize(&[1u8; 7], &mut serialized).unwrap();
  165. let result = String::from_utf8(buffer).unwrap();
  166. assert_eq!(result, "[1,1,1,1,1,1,1]");
  167. // Deserializing should also work.
  168. let mut deserializer = serde_json::Deserializer::from_str(&result);
  169. let deserialized: [u8; 7] = array::deserialize(&mut deserializer).unwrap();
  170. assert_eq!(deserialized, [1u8; 7]);
  171. }
  172. // Golden Structure Test
  173. //
  174. // This test serializes a struct containing all the expected types we should
  175. // be able to handle and checks the output is as expected. The reason I
  176. // opted to serialize all in one struct instead of with separate tests is to
  177. // ensure that the positioning of elements when in relation to others is
  178. // also as expected. Especially when it comes to things such as nesting and
  179. // length prefixing.
  180. #[test]
  181. fn test_pyth_serde() {
  182. use serde::Serialize;
  183. // Setup Serializer.
  184. let mut buffer = Vec::new();
  185. let mut cursor = std::io::Cursor::new(&mut buffer);
  186. let mut serializer: Serializer<_, byteorder::LE> = Serializer::new(&mut cursor);
  187. // Golden Test Value. As binary data can be fickle to understand in
  188. // tests this should be kept commented with detail.
  189. #[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq)]
  190. struct GoldenStruct<'a> {
  191. // Test `unit` is not serialized to anything.
  192. unit: (),
  193. // Test `bool` is serialized to a single byte.
  194. t_bool: bool,
  195. // Test integer serializations.
  196. t_u8: u8,
  197. t_u16: u16,
  198. t_u32: u32,
  199. t_u64: u64,
  200. // Test `str` is serialized to a variable length array.
  201. t_string: String,
  202. t_str: &'a str,
  203. // Test `Vec` is serialized to a variable length array.
  204. t_vec: Vec<u8>,
  205. t_vec_empty: Vec<u8>,
  206. t_vec_nested: Vec<Vec<u8>>,
  207. t_vec_nested_empty: Vec<Vec<u8>>,
  208. t_slice: &'a [u8],
  209. t_slice_empty: &'a [u8],
  210. // Test tuples serialize as expected.
  211. t_tuple: (u8, u16, u32, u64, String, Vec<u8>, &'a [u8]),
  212. t_tuple_nested: ((u8, u16), (u32, u64)),
  213. // Test enum serializations.
  214. t_enum_unit: GoldenEnum,
  215. t_enum_newtype: GoldenEnum,
  216. t_enum_tuple: GoldenEnum,
  217. t_enum_struct: GoldenEnum,
  218. // Test nested structs, which includes our PrefixedVec implementations work as we expect.
  219. t_struct: GoldenNested<u8>,
  220. t_prefixed: PrefixedVec<u16, u8>,
  221. }
  222. #[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq)]
  223. struct GoldenNested<T> {
  224. nested_u8: T,
  225. nested_tuple: (u8, u8),
  226. }
  227. #[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq)]
  228. enum GoldenEnum {
  229. Unit,
  230. Newtype(u8),
  231. Tuple(u8, u16),
  232. Struct { a: u8, b: u16 },
  233. }
  234. // Serialize the golden test value.
  235. let golden_struct = GoldenStruct {
  236. unit: (),
  237. t_bool: true,
  238. t_u8: 1,
  239. t_u16: 2,
  240. t_u32: 3,
  241. t_u64: 4,
  242. t_string: "9".to_string(),
  243. t_str: "10",
  244. t_vec: vec![11, 12, 13],
  245. t_vec_empty: vec![],
  246. t_vec_nested: vec![vec![14, 15, 16], vec![17, 18, 19]],
  247. t_vec_nested_empty: vec![vec![], vec![]],
  248. t_slice: &[20, 21, 22],
  249. t_slice_empty: &[],
  250. t_tuple: (
  251. 29,
  252. 30,
  253. 31,
  254. 32,
  255. "10".to_string(),
  256. vec![35, 36, 37],
  257. &[38, 39, 40],
  258. ),
  259. t_tuple_nested: ((41, 42), (43, 44)),
  260. t_enum_unit: GoldenEnum::Unit,
  261. t_enum_newtype: GoldenEnum::Newtype(45),
  262. t_enum_tuple: GoldenEnum::Tuple(46, 47),
  263. t_enum_struct: GoldenEnum::Struct { a: 48, b: 49 },
  264. t_struct: GoldenNested {
  265. nested_u8: 50,
  266. nested_tuple: (51, 52),
  267. },
  268. t_prefixed: vec![0u8; 512].into(),
  269. };
  270. golden_struct.serialize(&mut serializer).unwrap();
  271. // The serialized output should be as expected.
  272. assert_eq!(
  273. &buffer,
  274. &[
  275. 1, // t_bool
  276. 1, // t_u8
  277. 2, 0, // t_u16
  278. 3, 0, 0, 0, // t_u32
  279. 4, 0, 0, 0, 0, 0, 0, 0, // t_u64
  280. 1, 57, // t_string
  281. 2, 49, 48, // t_str
  282. 3, 11, 12, 13, // t_vec
  283. 0, // t_vec_empty
  284. 2, 3, 14, 15, 16, 3, 17, 18, 19, // t_vec_nested
  285. 2, 0, 0, // t_vec_nested_empty
  286. 3, 20, 21, 22, // t_slice
  287. 0, // t_slice_empty
  288. 29, // t_tuple
  289. 30, 0, // u8
  290. 31, 0, 0, 0, // u16
  291. 32, 0, 0, 0, 0, 0, 0, 0, // u32
  292. 2, 49, 48, // "10"
  293. 3, 35, 36, 37, // [35, 36, 37]
  294. 3, 38, 39, 40, // [38, 39, 40]
  295. 41, 42, 0, 43, 0, 0, 0, 44, 0, 0, 0, 0, 0, 0, 0, // t_tuple_nested
  296. 0, // t_enum_unit
  297. 1, 45, // t_enum_newtype
  298. 2, 46, 47, 0, // t_enum_tuple
  299. 3, 48, 49, 0, // t_enum_struct
  300. 50, 51, 52, // t_nested
  301. 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  320. ]
  321. );
  322. // We should also be able to deserialize back into the original type.
  323. assert_eq!(
  324. golden_struct,
  325. crate::wire::from_slice::<byteorder::LE, _>(&buffer).unwrap()
  326. );
  327. }
  328. // Test if the AccumulatorUpdateData type can be serialized and deserialized
  329. // and still be the same as the original.
  330. #[test]
  331. fn test_accumulator_update_data_serde() {
  332. use serde::Serialize;
  333. // Serialize an empty update into a buffer.
  334. let empty_update = AccumulatorUpdateData::new(Proof::WormholeMerkle {
  335. vaa: PrefixedVec::from(vec![]),
  336. updates: vec![],
  337. });
  338. let mut buffer = Vec::new();
  339. let mut cursor = std::io::Cursor::new(&mut buffer);
  340. let mut serializer: Serializer<_, byteorder::LE> = Serializer::new(&mut cursor);
  341. empty_update.serialize(&mut serializer).unwrap();
  342. // Test if it can be deserialized back into the original type.
  343. let deserialized_update = AccumulatorUpdateData::try_from_slice(&buffer).unwrap();
  344. // The deserialized value should be the same as the original.
  345. assert_eq!(deserialized_update, empty_update);
  346. }
  347. }